babylon.max.js 2.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646
  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. var KeyboardEventTypes = (function () {
  20. function KeyboardEventTypes() {
  21. }
  22. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  23. get: function () {
  24. return KeyboardEventTypes._KEYDOWN;
  25. },
  26. enumerable: true,
  27. configurable: true
  28. });
  29. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  30. get: function () {
  31. return KeyboardEventTypes._KEYUP;
  32. },
  33. enumerable: true,
  34. configurable: true
  35. });
  36. KeyboardEventTypes._KEYDOWN = 0x01;
  37. KeyboardEventTypes._KEYUP = 0x02;
  38. return KeyboardEventTypes;
  39. }());
  40. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  41. var KeyboardInfo = (function () {
  42. function KeyboardInfo(type, event) {
  43. this.type = type;
  44. this.event = event;
  45. }
  46. return KeyboardInfo;
  47. }());
  48. BABYLON.KeyboardInfo = KeyboardInfo;
  49. /**
  50. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  51. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  52. */
  53. var KeyboardInfoPre = (function (_super) {
  54. __extends(KeyboardInfoPre, _super);
  55. function KeyboardInfoPre(type, event) {
  56. var _this = _super.call(this, type, event) || this;
  57. _this.skipOnPointerObservable = false;
  58. return _this;
  59. }
  60. return KeyboardInfoPre;
  61. }(KeyboardInfo));
  62. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  63. })(BABYLON || (BABYLON = {}));
  64. //# sourceMappingURL=babylon.keyboardEvents.js.map
  65. var BABYLON;
  66. (function (BABYLON) {
  67. var PointerEventTypes = (function () {
  68. function PointerEventTypes() {
  69. }
  70. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  71. get: function () {
  72. return PointerEventTypes._POINTERDOWN;
  73. },
  74. enumerable: true,
  75. configurable: true
  76. });
  77. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  78. get: function () {
  79. return PointerEventTypes._POINTERUP;
  80. },
  81. enumerable: true,
  82. configurable: true
  83. });
  84. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  85. get: function () {
  86. return PointerEventTypes._POINTERMOVE;
  87. },
  88. enumerable: true,
  89. configurable: true
  90. });
  91. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  92. get: function () {
  93. return PointerEventTypes._POINTERWHEEL;
  94. },
  95. enumerable: true,
  96. configurable: true
  97. });
  98. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  99. get: function () {
  100. return PointerEventTypes._POINTERPICK;
  101. },
  102. enumerable: true,
  103. configurable: true
  104. });
  105. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  106. get: function () {
  107. return PointerEventTypes._POINTERTAP;
  108. },
  109. enumerable: true,
  110. configurable: true
  111. });
  112. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  113. get: function () {
  114. return PointerEventTypes._POINTERDOUBLETAP;
  115. },
  116. enumerable: true,
  117. configurable: true
  118. });
  119. PointerEventTypes._POINTERDOWN = 0x01;
  120. PointerEventTypes._POINTERUP = 0x02;
  121. PointerEventTypes._POINTERMOVE = 0x04;
  122. PointerEventTypes._POINTERWHEEL = 0x08;
  123. PointerEventTypes._POINTERPICK = 0x10;
  124. PointerEventTypes._POINTERTAP = 0x20;
  125. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  126. return PointerEventTypes;
  127. }());
  128. BABYLON.PointerEventTypes = PointerEventTypes;
  129. var PointerInfoBase = (function () {
  130. function PointerInfoBase(type, event) {
  131. this.type = type;
  132. this.event = event;
  133. }
  134. return PointerInfoBase;
  135. }());
  136. BABYLON.PointerInfoBase = PointerInfoBase;
  137. /**
  138. * This class is used to store pointer related info for the onPrePointerObservable event.
  139. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  140. */
  141. var PointerInfoPre = (function (_super) {
  142. __extends(PointerInfoPre, _super);
  143. function PointerInfoPre(type, event, localX, localY) {
  144. var _this = _super.call(this, type, event) || this;
  145. _this.skipOnPointerObservable = false;
  146. _this.localPosition = new BABYLON.Vector2(localX, localY);
  147. return _this;
  148. }
  149. return PointerInfoPre;
  150. }(PointerInfoBase));
  151. BABYLON.PointerInfoPre = PointerInfoPre;
  152. /**
  153. * This type contains all the data related to a pointer event in Babylon.js.
  154. * 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.
  155. */
  156. var PointerInfo = (function (_super) {
  157. __extends(PointerInfo, _super);
  158. function PointerInfo(type, event, pickInfo) {
  159. var _this = _super.call(this, type, event) || this;
  160. _this.pickInfo = pickInfo;
  161. return _this;
  162. }
  163. return PointerInfo;
  164. }(PointerInfoBase));
  165. BABYLON.PointerInfo = PointerInfo;
  166. })(BABYLON || (BABYLON = {}));
  167. //# sourceMappingURL=babylon.pointerEvents.js.map
  168. var BABYLON;
  169. (function (BABYLON) {
  170. BABYLON.ToGammaSpace = 1 / 2.2;
  171. BABYLON.ToLinearSpace = 2.2;
  172. BABYLON.Epsilon = 0.001;
  173. var Color3 = (function () {
  174. /**
  175. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  176. */
  177. function Color3(r, g, b) {
  178. if (r === void 0) { r = 0; }
  179. if (g === void 0) { g = 0; }
  180. if (b === void 0) { b = 0; }
  181. this.r = r;
  182. this.g = g;
  183. this.b = b;
  184. }
  185. /**
  186. * Returns a string with the Color3 current values.
  187. */
  188. Color3.prototype.toString = function () {
  189. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  190. };
  191. /**
  192. * Returns the string "Color3".
  193. */
  194. Color3.prototype.getClassName = function () {
  195. return "Color3";
  196. };
  197. /**
  198. * Returns the Color3 hash code.
  199. */
  200. Color3.prototype.getHashCode = function () {
  201. var hash = this.r || 0;
  202. hash = (hash * 397) ^ (this.g || 0);
  203. hash = (hash * 397) ^ (this.b || 0);
  204. return hash;
  205. };
  206. // Operators
  207. /**
  208. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  209. * Returns the Color3.
  210. */
  211. Color3.prototype.toArray = function (array, index) {
  212. if (index === undefined) {
  213. index = 0;
  214. }
  215. array[index] = this.r;
  216. array[index + 1] = this.g;
  217. array[index + 2] = this.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color4 object from the current Color3 and the passed alpha.
  222. */
  223. Color3.prototype.toColor4 = function (alpha) {
  224. if (alpha === void 0) { alpha = 1; }
  225. return new Color4(this.r, this.g, this.b, alpha);
  226. };
  227. /**
  228. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  229. */
  230. Color3.prototype.asArray = function () {
  231. var result = [];
  232. this.toArray(result, 0);
  233. return result;
  234. };
  235. /**
  236. * Returns the luminance value (float).
  237. */
  238. Color3.prototype.toLuminance = function () {
  239. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  240. };
  241. /**
  242. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  243. * Returns this new object.
  244. */
  245. Color3.prototype.multiply = function (otherColor) {
  246. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  247. };
  248. /**
  249. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  250. * Returns the current Color3.
  251. */
  252. Color3.prototype.multiplyToRef = function (otherColor, result) {
  253. result.r = this.r * otherColor.r;
  254. result.g = this.g * otherColor.g;
  255. result.b = this.b * otherColor.b;
  256. return this;
  257. };
  258. /**
  259. * Boolean : True if the rgb values are equal to the passed ones.
  260. */
  261. Color3.prototype.equals = function (otherColor) {
  262. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  263. };
  264. /**
  265. * Boolean : True if the rgb values are equal to the passed ones.
  266. */
  267. Color3.prototype.equalsFloats = function (r, g, b) {
  268. return this.r === r && this.g === g && this.b === b;
  269. };
  270. /**
  271. * Multiplies in place each rgb value by scale.
  272. * Returns the updated Color3.
  273. */
  274. Color3.prototype.scale = function (scale) {
  275. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  276. };
  277. /**
  278. * Multiplies the rgb values by scale and stores the result into "result".
  279. * Returns the unmodified current Color3.
  280. */
  281. Color3.prototype.scaleToRef = function (scale, result) {
  282. result.r = this.r * scale;
  283. result.g = this.g * scale;
  284. result.b = this.b * scale;
  285. return this;
  286. };
  287. /**
  288. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  289. */
  290. Color3.prototype.add = function (otherColor) {
  291. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  292. };
  293. /**
  294. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  295. * Returns the unmodified current Color3.
  296. */
  297. Color3.prototype.addToRef = function (otherColor, result) {
  298. result.r = this.r + otherColor.r;
  299. result.g = this.g + otherColor.g;
  300. result.b = this.b + otherColor.b;
  301. return this;
  302. };
  303. /**
  304. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  305. */
  306. Color3.prototype.subtract = function (otherColor) {
  307. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  308. };
  309. /**
  310. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  311. * Returns the unmodified current Color3.
  312. */
  313. Color3.prototype.subtractToRef = function (otherColor, result) {
  314. result.r = this.r - otherColor.r;
  315. result.g = this.g - otherColor.g;
  316. result.b = this.b - otherColor.b;
  317. return this;
  318. };
  319. /**
  320. * Returns a new Color3 copied the current one.
  321. */
  322. Color3.prototype.clone = function () {
  323. return new Color3(this.r, this.g, this.b);
  324. };
  325. /**
  326. * Copies the rgb values from the source in the current Color3.
  327. * Returns the updated Color3.
  328. */
  329. Color3.prototype.copyFrom = function (source) {
  330. this.r = source.r;
  331. this.g = source.g;
  332. this.b = source.b;
  333. return this;
  334. };
  335. /**
  336. * Updates the Color3 rgb values from the passed floats.
  337. * Returns the Color3.
  338. */
  339. Color3.prototype.copyFromFloats = function (r, g, b) {
  340. this.r = r;
  341. this.g = g;
  342. this.b = b;
  343. return this;
  344. };
  345. /**
  346. * Updates the Color3 rgb values from the passed floats.
  347. * Returns the Color3.
  348. */
  349. Color3.prototype.set = function (r, g, b) {
  350. return this.copyFromFloats(r, g, b);
  351. };
  352. /**
  353. * Returns the Color3 hexadecimal code as a string.
  354. */
  355. Color3.prototype.toHexString = function () {
  356. var intR = (this.r * 255) | 0;
  357. var intG = (this.g * 255) | 0;
  358. var intB = (this.b * 255) | 0;
  359. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  360. };
  361. /**
  362. * Returns a new Color3 converted to linear space.
  363. */
  364. Color3.prototype.toLinearSpace = function () {
  365. var convertedColor = new Color3();
  366. this.toLinearSpaceToRef(convertedColor);
  367. return convertedColor;
  368. };
  369. /**
  370. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  371. * Returns the unmodified Color3.
  372. */
  373. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  374. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  375. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  376. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  377. return this;
  378. };
  379. /**
  380. * Returns a new Color3 converted to gamma space.
  381. */
  382. Color3.prototype.toGammaSpace = function () {
  383. var convertedColor = new Color3();
  384. this.toGammaSpaceToRef(convertedColor);
  385. return convertedColor;
  386. };
  387. /**
  388. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  389. * Returns the unmodified Color3.
  390. */
  391. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  392. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  393. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  394. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  395. return this;
  396. };
  397. // Statics
  398. /**
  399. * Creates a new Color3 from the string containing valid hexadecimal values.
  400. */
  401. Color3.FromHexString = function (hex) {
  402. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  403. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  404. return new Color3(0, 0, 0);
  405. }
  406. var r = parseInt(hex.substring(1, 3), 16);
  407. var g = parseInt(hex.substring(3, 5), 16);
  408. var b = parseInt(hex.substring(5, 7), 16);
  409. return Color3.FromInts(r, g, b);
  410. };
  411. /**
  412. * Creates a new Vector3 from the startind index of the passed array.
  413. */
  414. Color3.FromArray = function (array, offset) {
  415. if (offset === void 0) { offset = 0; }
  416. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  417. };
  418. /**
  419. * Creates a new Color3 from integer values ( < 256).
  420. */
  421. Color3.FromInts = function (r, g, b) {
  422. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  423. };
  424. /**
  425. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  426. */
  427. Color3.Lerp = function (start, end, amount) {
  428. var r = start.r + ((end.r - start.r) * amount);
  429. var g = start.g + ((end.g - start.g) * amount);
  430. var b = start.b + ((end.b - start.b) * amount);
  431. return new Color3(r, g, b);
  432. };
  433. Color3.Red = function () { return new Color3(1, 0, 0); };
  434. Color3.Green = function () { return new Color3(0, 1, 0); };
  435. Color3.Blue = function () { return new Color3(0, 0, 1); };
  436. Color3.Black = function () { return new Color3(0, 0, 0); };
  437. Color3.White = function () { return new Color3(1, 1, 1); };
  438. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  439. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  440. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  441. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  442. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  443. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  444. return Color3;
  445. }());
  446. BABYLON.Color3 = Color3;
  447. var Color4 = (function () {
  448. /**
  449. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  450. */
  451. function Color4(r, g, b, a) {
  452. if (r === void 0) { r = 0; }
  453. if (g === void 0) { g = 0; }
  454. if (b === void 0) { b = 0; }
  455. if (a === void 0) { a = 1; }
  456. this.r = r;
  457. this.g = g;
  458. this.b = b;
  459. this.a = a;
  460. }
  461. // Operators
  462. /**
  463. * Adds in place the passed Color4 values to the current Color4.
  464. * Returns the updated Color4.
  465. */
  466. Color4.prototype.addInPlace = function (right) {
  467. this.r += right.r;
  468. this.g += right.g;
  469. this.b += right.b;
  470. this.a += right.a;
  471. return this;
  472. };
  473. /**
  474. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  475. */
  476. Color4.prototype.asArray = function () {
  477. var result = [];
  478. this.toArray(result, 0);
  479. return result;
  480. };
  481. /**
  482. * Stores from the starting index in the passed array the Color4 successive values.
  483. * Returns the Color4.
  484. */
  485. Color4.prototype.toArray = function (array, index) {
  486. if (index === undefined) {
  487. index = 0;
  488. }
  489. array[index] = this.r;
  490. array[index + 1] = this.g;
  491. array[index + 2] = this.b;
  492. array[index + 3] = this.a;
  493. return this;
  494. };
  495. /**
  496. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  497. */
  498. Color4.prototype.add = function (right) {
  499. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  500. };
  501. /**
  502. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  503. */
  504. Color4.prototype.subtract = function (right) {
  505. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  506. };
  507. /**
  508. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  509. * Returns the Color4.
  510. */
  511. Color4.prototype.subtractToRef = function (right, result) {
  512. result.r = this.r - right.r;
  513. result.g = this.g - right.g;
  514. result.b = this.b - right.b;
  515. result.a = this.a - right.a;
  516. return this;
  517. };
  518. /**
  519. * Creates a new Color4 with the current Color4 values multiplied by scale.
  520. */
  521. Color4.prototype.scale = function (scale) {
  522. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  523. };
  524. /**
  525. * Multiplies the current Color4 values by scale and stores the result in "result".
  526. * Returns the Color4.
  527. */
  528. Color4.prototype.scaleToRef = function (scale, result) {
  529. result.r = this.r * scale;
  530. result.g = this.g * scale;
  531. result.b = this.b * scale;
  532. result.a = this.a * scale;
  533. return this;
  534. };
  535. /**
  536. * Multipy an RGBA Color4 value by another and return a new Color4 object
  537. * @param color The Color4 (RGBA) value to multiply by
  538. * @returns A new Color4.
  539. */
  540. Color4.prototype.multiply = function (color) {
  541. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  542. };
  543. /**
  544. * Multipy an RGBA Color4 value by another and push the result in a reference value
  545. * @param color The Color4 (RGBA) value to multiply by
  546. * @param result The Color4 (RGBA) to fill the result in
  547. * @returns the result Color4.
  548. */
  549. Color4.prototype.multiplyToRef = function (color, result) {
  550. result.r = this.r * color.r;
  551. result.g = this.g * color.g;
  552. result.b = this.b * color.b;
  553. result.a = this.a * color.a;
  554. return result;
  555. };
  556. /**
  557. * Returns a string with the Color4 values.
  558. */
  559. Color4.prototype.toString = function () {
  560. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  561. };
  562. /**
  563. * Returns the string "Color4"
  564. */
  565. Color4.prototype.getClassName = function () {
  566. return "Color4";
  567. };
  568. /**
  569. * Return the Color4 hash code as a number.
  570. */
  571. Color4.prototype.getHashCode = function () {
  572. var hash = this.r || 0;
  573. hash = (hash * 397) ^ (this.g || 0);
  574. hash = (hash * 397) ^ (this.b || 0);
  575. hash = (hash * 397) ^ (this.a || 0);
  576. return hash;
  577. };
  578. /**
  579. * Creates a new Color4 copied from the current one.
  580. */
  581. Color4.prototype.clone = function () {
  582. return new Color4(this.r, this.g, this.b, this.a);
  583. };
  584. /**
  585. * Copies the passed Color4 values into the current one.
  586. * Returns the updated Color4.
  587. */
  588. Color4.prototype.copyFrom = function (source) {
  589. this.r = source.r;
  590. this.g = source.g;
  591. this.b = source.b;
  592. this.a = source.a;
  593. return this;
  594. };
  595. /**
  596. * Copies the passed float values into the current one.
  597. * Returns the updated Color4.
  598. */
  599. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  600. this.r = r;
  601. this.g = g;
  602. this.b = b;
  603. this.a = a;
  604. return this;
  605. };
  606. /**
  607. * Copies the passed float values into the current one.
  608. * Returns the updated Color4.
  609. */
  610. Color4.prototype.set = function (r, g, b, a) {
  611. return this.copyFromFloats(r, g, b, a);
  612. };
  613. /**
  614. * Returns a string containing the hexadecimal Color4 code.
  615. */
  616. Color4.prototype.toHexString = function () {
  617. var intR = (this.r * 255) | 0;
  618. var intG = (this.g * 255) | 0;
  619. var intB = (this.b * 255) | 0;
  620. var intA = (this.a * 255) | 0;
  621. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  622. };
  623. /**
  624. * Returns a new Color4 converted to linear space.
  625. */
  626. Color4.prototype.toLinearSpace = function () {
  627. var convertedColor = new Color4();
  628. this.toLinearSpaceToRef(convertedColor);
  629. return convertedColor;
  630. };
  631. /**
  632. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  633. * Returns the unmodified Color4.
  634. */
  635. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  636. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  637. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  638. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  639. convertedColor.a = this.a;
  640. return this;
  641. };
  642. /**
  643. * Returns a new Color4 converted to gamma space.
  644. */
  645. Color4.prototype.toGammaSpace = function () {
  646. var convertedColor = new Color4();
  647. this.toGammaSpaceToRef(convertedColor);
  648. return convertedColor;
  649. };
  650. /**
  651. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  652. * Returns the unmodified Color4.
  653. */
  654. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  655. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  656. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  657. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  658. convertedColor.a = this.a;
  659. return this;
  660. };
  661. // Statics
  662. /**
  663. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  664. */
  665. Color4.FromHexString = function (hex) {
  666. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  667. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  668. return new Color4(0.0, 0.0, 0.0, 0.0);
  669. }
  670. var r = parseInt(hex.substring(1, 3), 16);
  671. var g = parseInt(hex.substring(3, 5), 16);
  672. var b = parseInt(hex.substring(5, 7), 16);
  673. var a = parseInt(hex.substring(7, 9), 16);
  674. return Color4.FromInts(r, g, b, a);
  675. };
  676. /**
  677. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  678. */
  679. Color4.Lerp = function (left, right, amount) {
  680. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  681. Color4.LerpToRef(left, right, amount, result);
  682. return result;
  683. };
  684. /**
  685. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  686. */
  687. Color4.LerpToRef = function (left, right, amount, result) {
  688. result.r = left.r + (right.r - left.r) * amount;
  689. result.g = left.g + (right.g - left.g) * amount;
  690. result.b = left.b + (right.b - left.b) * amount;
  691. result.a = left.a + (right.a - left.a) * amount;
  692. };
  693. /**
  694. * Creates a new Color4 from the starting index element of the passed array.
  695. */
  696. Color4.FromArray = function (array, offset) {
  697. if (offset === void 0) { offset = 0; }
  698. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  699. };
  700. /**
  701. * Creates a new Color4 from the passed integers ( < 256 ).
  702. */
  703. Color4.FromInts = function (r, g, b, a) {
  704. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  705. };
  706. Color4.CheckColors4 = function (colors, count) {
  707. // Check if color3 was used
  708. if (colors.length === count * 3) {
  709. var colors4 = [];
  710. for (var index = 0; index < colors.length; index += 3) {
  711. var newIndex = (index / 3) * 4;
  712. colors4[newIndex] = colors[index];
  713. colors4[newIndex + 1] = colors[index + 1];
  714. colors4[newIndex + 2] = colors[index + 2];
  715. colors4[newIndex + 3] = 1.0;
  716. }
  717. return colors4;
  718. }
  719. return colors;
  720. };
  721. return Color4;
  722. }());
  723. BABYLON.Color4 = Color4;
  724. var Vector2 = (function () {
  725. /**
  726. * Creates a new Vector2 from the passed x and y coordinates.
  727. */
  728. function Vector2(x, y) {
  729. this.x = x;
  730. this.y = y;
  731. }
  732. /**
  733. * Returns a string with the Vector2 coordinates.
  734. */
  735. Vector2.prototype.toString = function () {
  736. return "{X: " + this.x + " Y:" + this.y + "}";
  737. };
  738. /**
  739. * Returns the string "Vector2"
  740. */
  741. Vector2.prototype.getClassName = function () {
  742. return "Vector2";
  743. };
  744. /**
  745. * Returns the Vector2 hash code as a number.
  746. */
  747. Vector2.prototype.getHashCode = function () {
  748. var hash = this.x || 0;
  749. hash = (hash * 397) ^ (this.y || 0);
  750. return hash;
  751. };
  752. // Operators
  753. /**
  754. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  755. * Returns the Vector2.
  756. */
  757. Vector2.prototype.toArray = function (array, index) {
  758. if (index === void 0) { index = 0; }
  759. array[index] = this.x;
  760. array[index + 1] = this.y;
  761. return this;
  762. };
  763. /**
  764. * Returns a new array with 2 elements : the Vector2 coordinates.
  765. */
  766. Vector2.prototype.asArray = function () {
  767. var result = [];
  768. this.toArray(result, 0);
  769. return result;
  770. };
  771. /**
  772. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  773. * Returns the updated Vector2.
  774. */
  775. Vector2.prototype.copyFrom = function (source) {
  776. this.x = source.x;
  777. this.y = source.y;
  778. return this;
  779. };
  780. /**
  781. * Sets the Vector2 coordinates with the passed floats.
  782. * Returns the updated Vector2.
  783. */
  784. Vector2.prototype.copyFromFloats = function (x, y) {
  785. this.x = x;
  786. this.y = y;
  787. return this;
  788. };
  789. /**
  790. * Sets the Vector2 coordinates with the passed floats.
  791. * Returns the updated Vector2.
  792. */
  793. Vector2.prototype.set = function (x, y) {
  794. return this.copyFromFloats(x, y);
  795. };
  796. /**
  797. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  798. */
  799. Vector2.prototype.add = function (otherVector) {
  800. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  801. };
  802. /**
  803. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  804. * Returns the Vector2.
  805. */
  806. Vector2.prototype.addToRef = function (otherVector, result) {
  807. result.x = this.x + otherVector.x;
  808. result.y = this.y + otherVector.y;
  809. return this;
  810. };
  811. /**
  812. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  813. * Returns the updated Vector2.
  814. */
  815. Vector2.prototype.addInPlace = function (otherVector) {
  816. this.x += otherVector.x;
  817. this.y += otherVector.y;
  818. return this;
  819. };
  820. /**
  821. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  822. */
  823. Vector2.prototype.addVector3 = function (otherVector) {
  824. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  825. };
  826. /**
  827. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  828. */
  829. Vector2.prototype.subtract = function (otherVector) {
  830. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  831. };
  832. /**
  833. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  834. * Returns the Vector2.
  835. */
  836. Vector2.prototype.subtractToRef = function (otherVector, result) {
  837. result.x = this.x - otherVector.x;
  838. result.y = this.y - otherVector.y;
  839. return this;
  840. };
  841. /**
  842. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  843. * Returns the updated Vector2.
  844. */
  845. Vector2.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. return this;
  849. };
  850. /**
  851. * Multiplies in place the current Vector2 coordinates by the passed ones.
  852. * Returns the updated Vector2.
  853. */
  854. Vector2.prototype.multiplyInPlace = function (otherVector) {
  855. this.x *= otherVector.x;
  856. this.y *= otherVector.y;
  857. return this;
  858. };
  859. /**
  860. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  861. */
  862. Vector2.prototype.multiply = function (otherVector) {
  863. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  864. };
  865. /**
  866. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  867. * Returns the Vector2.
  868. */
  869. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  870. result.x = this.x * otherVector.x;
  871. result.y = this.y * otherVector.y;
  872. return this;
  873. };
  874. /**
  875. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  876. */
  877. Vector2.prototype.multiplyByFloats = function (x, y) {
  878. return new Vector2(this.x * x, this.y * y);
  879. };
  880. /**
  881. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  882. */
  883. Vector2.prototype.divide = function (otherVector) {
  884. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  885. };
  886. /**
  887. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  888. * Returns the Vector2.
  889. */
  890. Vector2.prototype.divideToRef = function (otherVector, result) {
  891. result.x = this.x / otherVector.x;
  892. result.y = this.y / otherVector.y;
  893. return this;
  894. };
  895. /**
  896. * Returns a new Vector2 with current Vector2 negated coordinates.
  897. */
  898. Vector2.prototype.negate = function () {
  899. return new Vector2(-this.x, -this.y);
  900. };
  901. /**
  902. * Multiply the Vector2 coordinates by scale.
  903. * Returns the updated Vector2.
  904. */
  905. Vector2.prototype.scaleInPlace = function (scale) {
  906. this.x *= scale;
  907. this.y *= scale;
  908. return this;
  909. };
  910. /**
  911. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  912. */
  913. Vector2.prototype.scale = function (scale) {
  914. return new Vector2(this.x * scale, this.y * scale);
  915. };
  916. /**
  917. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  918. */
  919. Vector2.prototype.equals = function (otherVector) {
  920. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  921. };
  922. /**
  923. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  924. */
  925. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  926. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  927. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  928. };
  929. // Properties
  930. /**
  931. * Returns the vector length (float).
  932. */
  933. Vector2.prototype.length = function () {
  934. return Math.sqrt(this.x * this.x + this.y * this.y);
  935. };
  936. /**
  937. * Returns the vector squared length (float);
  938. */
  939. Vector2.prototype.lengthSquared = function () {
  940. return (this.x * this.x + this.y * this.y);
  941. };
  942. // Methods
  943. /**
  944. * Normalize the vector.
  945. * Returns the updated Vector2.
  946. */
  947. Vector2.prototype.normalize = function () {
  948. var len = this.length();
  949. if (len === 0)
  950. return this;
  951. var num = 1.0 / len;
  952. this.x *= num;
  953. this.y *= num;
  954. return this;
  955. };
  956. /**
  957. * Returns a new Vector2 copied from the Vector2.
  958. */
  959. Vector2.prototype.clone = function () {
  960. return new Vector2(this.x, this.y);
  961. };
  962. // Statics
  963. /**
  964. * Returns a new Vector2(0, 0)
  965. */
  966. Vector2.Zero = function () {
  967. return new Vector2(0, 0);
  968. };
  969. /**
  970. * Returns a new Vector2(1, 1)
  971. */
  972. Vector2.One = function () {
  973. return new Vector2(1, 1);
  974. };
  975. /**
  976. * Returns a new Vector2 set from the passed index element of the passed array.
  977. */
  978. Vector2.FromArray = function (array, offset) {
  979. if (offset === void 0) { offset = 0; }
  980. return new Vector2(array[offset], array[offset + 1]);
  981. };
  982. /**
  983. * Sets "result" from the passed index element of the passed array.
  984. */
  985. Vector2.FromArrayToRef = function (array, offset, result) {
  986. result.x = array[offset];
  987. result.y = array[offset + 1];
  988. };
  989. /**
  990. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  991. */
  992. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  993. var squared = amount * amount;
  994. var cubed = amount * squared;
  995. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  996. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  997. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  998. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  999. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1000. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1001. return new Vector2(x, y);
  1002. };
  1003. /**
  1004. * 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".
  1005. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1006. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1007. */
  1008. Vector2.Clamp = function (value, min, max) {
  1009. var x = value.x;
  1010. x = (x > max.x) ? max.x : x;
  1011. x = (x < min.x) ? min.x : x;
  1012. var y = value.y;
  1013. y = (y > max.y) ? max.y : y;
  1014. y = (y < min.y) ? min.y : y;
  1015. return new Vector2(x, y);
  1016. };
  1017. /**
  1018. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1019. */
  1020. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1021. var squared = amount * amount;
  1022. var cubed = amount * squared;
  1023. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1024. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1025. var part3 = (cubed - (2.0 * squared)) + amount;
  1026. var part4 = cubed - squared;
  1027. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1028. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1029. return new Vector2(x, y);
  1030. };
  1031. /**
  1032. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1033. */
  1034. Vector2.Lerp = function (start, end, amount) {
  1035. var x = start.x + ((end.x - start.x) * amount);
  1036. var y = start.y + ((end.y - start.y) * amount);
  1037. return new Vector2(x, y);
  1038. };
  1039. /**
  1040. * Returns the dot product (float) of the vector "left" and the vector "right".
  1041. */
  1042. Vector2.Dot = function (left, right) {
  1043. return left.x * right.x + left.y * right.y;
  1044. };
  1045. /**
  1046. * Returns a new Vector2 equal to the normalized passed vector.
  1047. */
  1048. Vector2.Normalize = function (vector) {
  1049. var newVector = vector.clone();
  1050. newVector.normalize();
  1051. return newVector;
  1052. };
  1053. /**
  1054. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1055. */
  1056. Vector2.Minimize = function (left, right) {
  1057. var x = (left.x < right.x) ? left.x : right.x;
  1058. var y = (left.y < right.y) ? left.y : right.y;
  1059. return new Vector2(x, y);
  1060. };
  1061. /**
  1062. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1063. */
  1064. Vector2.Maximize = function (left, right) {
  1065. var x = (left.x > right.x) ? left.x : right.x;
  1066. var y = (left.y > right.y) ? left.y : right.y;
  1067. return new Vector2(x, y);
  1068. };
  1069. /**
  1070. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1071. */
  1072. Vector2.Transform = function (vector, transformation) {
  1073. var r = Vector2.Zero();
  1074. Vector2.TransformToRef(vector, transformation, r);
  1075. return r;
  1076. };
  1077. /**
  1078. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1079. */
  1080. Vector2.TransformToRef = function (vector, transformation, result) {
  1081. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1082. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1083. result.x = x;
  1084. result.y = y;
  1085. };
  1086. /**
  1087. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1088. */
  1089. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1090. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1091. var sign = a < 0 ? -1 : 1;
  1092. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1093. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1094. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1095. };
  1096. /**
  1097. * Returns the distance (float) between the vectors "value1" and "value2".
  1098. */
  1099. Vector2.Distance = function (value1, value2) {
  1100. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1101. };
  1102. /**
  1103. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1104. */
  1105. Vector2.DistanceSquared = function (value1, value2) {
  1106. var x = value1.x - value2.x;
  1107. var y = value1.y - value2.y;
  1108. return (x * x) + (y * y);
  1109. };
  1110. /**
  1111. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1112. */
  1113. Vector2.Center = function (value1, value2) {
  1114. var center = value1.add(value2);
  1115. center.scaleInPlace(0.5);
  1116. return center;
  1117. };
  1118. /**
  1119. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1120. */
  1121. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1122. var l2 = Vector2.DistanceSquared(segA, segB);
  1123. if (l2 === 0.0) {
  1124. return Vector2.Distance(p, segA);
  1125. }
  1126. var v = segB.subtract(segA);
  1127. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1128. var proj = segA.add(v.multiplyByFloats(t, t));
  1129. return Vector2.Distance(p, proj);
  1130. };
  1131. return Vector2;
  1132. }());
  1133. BABYLON.Vector2 = Vector2;
  1134. var Vector3 = (function () {
  1135. /**
  1136. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1137. * A Vector3 is the main object used in 3D geometry.
  1138. * It can represent etiher the coordinates of a point the space, either a direction.
  1139. */
  1140. function Vector3(x, y, z) {
  1141. this.x = x;
  1142. this.y = y;
  1143. this.z = z;
  1144. }
  1145. /**
  1146. * Returns a string with the Vector3 coordinates.
  1147. */
  1148. Vector3.prototype.toString = function () {
  1149. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1150. };
  1151. /**
  1152. * Returns the string "Vector3"
  1153. */
  1154. Vector3.prototype.getClassName = function () {
  1155. return "Vector3";
  1156. };
  1157. /**
  1158. * Returns the Vector hash code.
  1159. */
  1160. Vector3.prototype.getHashCode = function () {
  1161. var hash = this.x || 0;
  1162. hash = (hash * 397) ^ (this.y || 0);
  1163. hash = (hash * 397) ^ (this.z || 0);
  1164. return hash;
  1165. };
  1166. // Operators
  1167. /**
  1168. * Returns a new array with three elements : the coordinates the Vector3.
  1169. */
  1170. Vector3.prototype.asArray = function () {
  1171. var result = [];
  1172. this.toArray(result, 0);
  1173. return result;
  1174. };
  1175. /**
  1176. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1177. * Returns the Vector3.
  1178. */
  1179. Vector3.prototype.toArray = function (array, index) {
  1180. if (index === void 0) { index = 0; }
  1181. array[index] = this.x;
  1182. array[index + 1] = this.y;
  1183. array[index + 2] = this.z;
  1184. return this;
  1185. };
  1186. /**
  1187. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1188. */
  1189. Vector3.prototype.toQuaternion = function () {
  1190. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1191. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1192. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1193. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1194. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1195. var cosy = Math.cos(this.y * 0.5);
  1196. var siny = Math.sin(this.y * 0.5);
  1197. result.x = coszMinusx * siny;
  1198. result.y = -sinzMinusx * siny;
  1199. result.z = sinxPlusz * cosy;
  1200. result.w = cosxPlusz * cosy;
  1201. return result;
  1202. };
  1203. /**
  1204. * Adds the passed vector to the current Vector3.
  1205. * Returns the updated Vector3.
  1206. */
  1207. Vector3.prototype.addInPlace = function (otherVector) {
  1208. this.x += otherVector.x;
  1209. this.y += otherVector.y;
  1210. this.z += otherVector.z;
  1211. return this;
  1212. };
  1213. /**
  1214. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1215. */
  1216. Vector3.prototype.add = function (otherVector) {
  1217. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1218. };
  1219. /**
  1220. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1221. * Returns the current Vector3.
  1222. */
  1223. Vector3.prototype.addToRef = function (otherVector, result) {
  1224. result.x = this.x + otherVector.x;
  1225. result.y = this.y + otherVector.y;
  1226. result.z = this.z + otherVector.z;
  1227. return this;
  1228. };
  1229. /**
  1230. * Subtract the passed vector from the current Vector3.
  1231. * Returns the updated Vector3.
  1232. */
  1233. Vector3.prototype.subtractInPlace = function (otherVector) {
  1234. this.x -= otherVector.x;
  1235. this.y -= otherVector.y;
  1236. this.z -= otherVector.z;
  1237. return this;
  1238. };
  1239. /**
  1240. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1241. */
  1242. Vector3.prototype.subtract = function (otherVector) {
  1243. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1244. };
  1245. /**
  1246. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1247. * Returns the current Vector3.
  1248. */
  1249. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1250. result.x = this.x - otherVector.x;
  1251. result.y = this.y - otherVector.y;
  1252. result.z = this.z - otherVector.z;
  1253. return this;
  1254. };
  1255. /**
  1256. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1257. */
  1258. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1259. return new Vector3(this.x - x, this.y - y, this.z - z);
  1260. };
  1261. /**
  1262. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1263. * Returns the current Vector3.
  1264. */
  1265. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1266. result.x = this.x - x;
  1267. result.y = this.y - y;
  1268. result.z = this.z - z;
  1269. return this;
  1270. };
  1271. /**
  1272. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1273. */
  1274. Vector3.prototype.negate = function () {
  1275. return new Vector3(-this.x, -this.y, -this.z);
  1276. };
  1277. /**
  1278. * Multiplies the Vector3 coordinates by the float "scale".
  1279. * Returns the updated Vector3.
  1280. */
  1281. Vector3.prototype.scaleInPlace = function (scale) {
  1282. this.x *= scale;
  1283. this.y *= scale;
  1284. this.z *= scale;
  1285. return this;
  1286. };
  1287. /**
  1288. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1289. */
  1290. Vector3.prototype.scale = function (scale) {
  1291. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1292. };
  1293. /**
  1294. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1295. * Returns the current Vector3.
  1296. */
  1297. Vector3.prototype.scaleToRef = function (scale, result) {
  1298. result.x = this.x * scale;
  1299. result.y = this.y * scale;
  1300. result.z = this.z * scale;
  1301. return this;
  1302. };
  1303. /**
  1304. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1305. */
  1306. Vector3.prototype.equals = function (otherVector) {
  1307. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1308. };
  1309. /**
  1310. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1311. */
  1312. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1313. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1314. 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);
  1315. };
  1316. /**
  1317. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1318. */
  1319. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1320. return this.x === x && this.y === y && this.z === z;
  1321. };
  1322. /**
  1323. * Muliplies the current Vector3 coordinates by the passed ones.
  1324. * Returns the updated Vector3.
  1325. */
  1326. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1327. this.x *= otherVector.x;
  1328. this.y *= otherVector.y;
  1329. this.z *= otherVector.z;
  1330. return this;
  1331. };
  1332. /**
  1333. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1334. */
  1335. Vector3.prototype.multiply = function (otherVector) {
  1336. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1337. };
  1338. /**
  1339. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1340. * Returns the current Vector3.
  1341. */
  1342. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1343. result.x = this.x * otherVector.x;
  1344. result.y = this.y * otherVector.y;
  1345. result.z = this.z * otherVector.z;
  1346. return this;
  1347. };
  1348. /**
  1349. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1350. */
  1351. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1352. return new Vector3(this.x * x, this.y * y, this.z * z);
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1356. */
  1357. Vector3.prototype.divide = function (otherVector) {
  1358. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1359. };
  1360. /**
  1361. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1362. * Returns the current Vector3.
  1363. */
  1364. Vector3.prototype.divideToRef = function (otherVector, result) {
  1365. result.x = this.x / otherVector.x;
  1366. result.y = this.y / otherVector.y;
  1367. result.z = this.z / otherVector.z;
  1368. return this;
  1369. };
  1370. /**
  1371. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1372. * Returns the updated Vector3.
  1373. */
  1374. Vector3.prototype.MinimizeInPlace = function (other) {
  1375. if (other.x < this.x)
  1376. this.x = other.x;
  1377. if (other.y < this.y)
  1378. this.y = other.y;
  1379. if (other.z < this.z)
  1380. this.z = other.z;
  1381. return this;
  1382. };
  1383. /**
  1384. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1385. * Returns the updated Vector3.
  1386. */
  1387. Vector3.prototype.MaximizeInPlace = function (other) {
  1388. if (other.x > this.x)
  1389. this.x = other.x;
  1390. if (other.y > this.y)
  1391. this.y = other.y;
  1392. if (other.z > this.z)
  1393. this.z = other.z;
  1394. return this;
  1395. };
  1396. // Properties
  1397. /**
  1398. * Returns the length of the Vector3 (float).
  1399. */
  1400. Vector3.prototype.length = function () {
  1401. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1402. };
  1403. /**
  1404. * Returns the squared length of the Vector3 (float).
  1405. */
  1406. Vector3.prototype.lengthSquared = function () {
  1407. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1408. };
  1409. // Methods
  1410. /**
  1411. * Normalize the current Vector3.
  1412. * Returns the updated Vector3.
  1413. */
  1414. Vector3.prototype.normalize = function () {
  1415. var len = this.length();
  1416. if (len === 0 || len === 1.0)
  1417. return this;
  1418. var num = 1.0 / len;
  1419. this.x *= num;
  1420. this.y *= num;
  1421. this.z *= num;
  1422. return this;
  1423. };
  1424. /**
  1425. * Returns a new Vector3 copied from the current Vector3.
  1426. */
  1427. Vector3.prototype.clone = function () {
  1428. return new Vector3(this.x, this.y, this.z);
  1429. };
  1430. /**
  1431. * Copies the passed vector coordinates to the current Vector3 ones.
  1432. * Returns the updated Vector3.
  1433. */
  1434. Vector3.prototype.copyFrom = function (source) {
  1435. this.x = source.x;
  1436. this.y = source.y;
  1437. this.z = source.z;
  1438. return this;
  1439. };
  1440. /**
  1441. * Copies the passed floats to the current Vector3 coordinates.
  1442. * Returns the updated Vector3.
  1443. */
  1444. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1445. this.x = x;
  1446. this.y = y;
  1447. this.z = z;
  1448. return this;
  1449. };
  1450. /**
  1451. * Copies the passed floats to the current Vector3 coordinates.
  1452. * Returns the updated Vector3.
  1453. */
  1454. Vector3.prototype.set = function (x, y, z) {
  1455. return this.copyFromFloats(x, y, z);
  1456. };
  1457. // Statics
  1458. /**
  1459. *
  1460. */
  1461. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1462. var d0 = Vector3.Dot(vector0, axis) - size;
  1463. var d1 = Vector3.Dot(vector1, axis) - size;
  1464. var s = d0 / (d0 - d1);
  1465. return s;
  1466. };
  1467. /**
  1468. * Returns a new Vector3 set from the index "offset" of the passed array.
  1469. */
  1470. Vector3.FromArray = function (array, offset) {
  1471. if (!offset) {
  1472. offset = 0;
  1473. }
  1474. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1475. };
  1476. /**
  1477. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1478. * This function is deprecated. Use FromArray instead.
  1479. */
  1480. Vector3.FromFloatArray = function (array, offset) {
  1481. return Vector3.FromArray(array, offset);
  1482. };
  1483. /**
  1484. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1485. */
  1486. Vector3.FromArrayToRef = function (array, offset, result) {
  1487. result.x = array[offset];
  1488. result.y = array[offset + 1];
  1489. result.z = array[offset + 2];
  1490. };
  1491. /**
  1492. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1493. * This function is deprecated. Use FromArrayToRef instead.
  1494. */
  1495. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1496. return Vector3.FromArrayToRef(array, offset, result);
  1497. };
  1498. /**
  1499. * Sets the passed vector "result" with the passed floats.
  1500. */
  1501. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1502. result.x = x;
  1503. result.y = y;
  1504. result.z = z;
  1505. };
  1506. /**
  1507. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1508. */
  1509. Vector3.Zero = function () {
  1510. return new Vector3(0.0, 0.0, 0.0);
  1511. };
  1512. /**
  1513. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1514. */
  1515. Vector3.One = function () {
  1516. return new Vector3(1.0, 1.0, 1.0);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1520. */
  1521. Vector3.Up = function () {
  1522. return new Vector3(0.0, 1.0, 0.0);
  1523. };
  1524. /**
  1525. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1526. */
  1527. Vector3.Forward = function () {
  1528. return new Vector3(0.0, 0.0, 1.0);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1532. */
  1533. Vector3.Right = function () {
  1534. return new Vector3(1.0, 0.0, 0.0);
  1535. };
  1536. /**
  1537. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1538. */
  1539. Vector3.Left = function () {
  1540. return new Vector3(-1.0, 0.0, 0.0);
  1541. };
  1542. /**
  1543. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1544. * This method computes tranformed coordinates only, not transformed direction vectors.
  1545. */
  1546. Vector3.TransformCoordinates = function (vector, transformation) {
  1547. var result = Vector3.Zero();
  1548. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1549. return result;
  1550. };
  1551. /**
  1552. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1553. * This method computes tranformed coordinates only, not transformed direction vectors.
  1554. */
  1555. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1556. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1557. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1558. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1559. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1560. result.x = x / w;
  1561. result.y = y / w;
  1562. result.z = z / w;
  1563. };
  1564. /**
  1565. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1566. * This method computes tranformed coordinates only, not transformed direction vectors.
  1567. */
  1568. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1569. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1570. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1571. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1572. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1573. result.x = rx / rw;
  1574. result.y = ry / rw;
  1575. result.z = rz / rw;
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1579. * This methods computes transformed normalized direction vectors only.
  1580. */
  1581. Vector3.TransformNormal = function (vector, transformation) {
  1582. var result = Vector3.Zero();
  1583. Vector3.TransformNormalToRef(vector, transformation, result);
  1584. return result;
  1585. };
  1586. /**
  1587. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1588. * This methods computes transformed normalized direction vectors only.
  1589. */
  1590. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1591. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1592. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1593. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1594. result.x = x;
  1595. result.y = y;
  1596. result.z = z;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1600. * This methods computes transformed normalized direction vectors only.
  1601. */
  1602. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1603. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1604. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1605. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1606. };
  1607. /**
  1608. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1609. */
  1610. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1611. var squared = amount * amount;
  1612. var cubed = amount * squared;
  1613. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1614. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1615. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1616. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1617. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1618. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1619. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1620. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1621. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1622. return new Vector3(x, y, z);
  1623. };
  1624. /**
  1625. * 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".
  1626. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1627. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1628. */
  1629. Vector3.Clamp = function (value, min, max) {
  1630. var x = value.x;
  1631. x = (x > max.x) ? max.x : x;
  1632. x = (x < min.x) ? min.x : x;
  1633. var y = value.y;
  1634. y = (y > max.y) ? max.y : y;
  1635. y = (y < min.y) ? min.y : y;
  1636. var z = value.z;
  1637. z = (z > max.z) ? max.z : z;
  1638. z = (z < min.z) ? min.z : z;
  1639. return new Vector3(x, y, z);
  1640. };
  1641. /**
  1642. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1643. */
  1644. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1645. var squared = amount * amount;
  1646. var cubed = amount * squared;
  1647. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1648. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1649. var part3 = (cubed - (2.0 * squared)) + amount;
  1650. var part4 = cubed - squared;
  1651. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1652. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1653. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1654. return new Vector3(x, y, z);
  1655. };
  1656. /**
  1657. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1658. */
  1659. Vector3.Lerp = function (start, end, amount) {
  1660. var result = new Vector3(0, 0, 0);
  1661. Vector3.LerpToRef(start, end, amount, result);
  1662. return result;
  1663. };
  1664. /**
  1665. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1666. */
  1667. Vector3.LerpToRef = function (start, end, amount, result) {
  1668. result.x = start.x + ((end.x - start.x) * amount);
  1669. result.y = start.y + ((end.y - start.y) * amount);
  1670. result.z = start.z + ((end.z - start.z) * amount);
  1671. };
  1672. /**
  1673. * Returns the dot product (float) between the vectors "left" and "right".
  1674. */
  1675. Vector3.Dot = function (left, right) {
  1676. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1677. };
  1678. /**
  1679. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1680. * The cross product is then orthogonal to both "left" and "right".
  1681. */
  1682. Vector3.Cross = function (left, right) {
  1683. var result = Vector3.Zero();
  1684. Vector3.CrossToRef(left, right, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the cross product of "left" and "right".
  1689. * The cross product is then orthogonal to both "left" and "right".
  1690. */
  1691. Vector3.CrossToRef = function (left, right, result) {
  1692. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1693. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1694. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1695. result.copyFrom(MathTmp.Vector3[0]);
  1696. };
  1697. /**
  1698. * Returns a new Vector3 as the normalization of the passed vector.
  1699. */
  1700. Vector3.Normalize = function (vector) {
  1701. var result = Vector3.Zero();
  1702. Vector3.NormalizeToRef(vector, result);
  1703. return result;
  1704. };
  1705. /**
  1706. * Sets the passed vector "result" with the normalization of the passed first vector.
  1707. */
  1708. Vector3.NormalizeToRef = function (vector, result) {
  1709. result.copyFrom(vector);
  1710. result.normalize();
  1711. };
  1712. Vector3.Project = function (vector, world, transform, viewport) {
  1713. var cw = viewport.width;
  1714. var ch = viewport.height;
  1715. var cx = viewport.x;
  1716. var cy = viewport.y;
  1717. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1718. 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);
  1719. var matrix = MathTmp.Matrix[0];
  1720. world.multiplyToRef(transform, matrix);
  1721. matrix.multiplyToRef(viewportMatrix, matrix);
  1722. return Vector3.TransformCoordinates(vector, matrix);
  1723. };
  1724. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1725. var matrix = MathTmp.Matrix[0];
  1726. world.multiplyToRef(transform, matrix);
  1727. matrix.invert();
  1728. source.x = source.x / viewportWidth * 2 - 1;
  1729. source.y = -(source.y / viewportHeight * 2 - 1);
  1730. var vector = Vector3.TransformCoordinates(source, matrix);
  1731. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1732. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1733. vector = vector.scale(1.0 / num);
  1734. }
  1735. return vector;
  1736. };
  1737. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1738. var matrix = MathTmp.Matrix[0];
  1739. world.multiplyToRef(view, matrix);
  1740. matrix.multiplyToRef(projection, matrix);
  1741. matrix.invert();
  1742. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1743. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1744. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1745. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1746. vector = vector.scale(1.0 / num);
  1747. }
  1748. return vector;
  1749. };
  1750. Vector3.Minimize = function (left, right) {
  1751. var min = left.clone();
  1752. min.MinimizeInPlace(right);
  1753. return min;
  1754. };
  1755. Vector3.Maximize = function (left, right) {
  1756. var max = left.clone();
  1757. max.MaximizeInPlace(right);
  1758. return max;
  1759. };
  1760. /**
  1761. * Returns the distance (float) between the vectors "value1" and "value2".
  1762. */
  1763. Vector3.Distance = function (value1, value2) {
  1764. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1765. };
  1766. /**
  1767. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1768. */
  1769. Vector3.DistanceSquared = function (value1, value2) {
  1770. var x = value1.x - value2.x;
  1771. var y = value1.y - value2.y;
  1772. var z = value1.z - value2.z;
  1773. return (x * x) + (y * y) + (z * z);
  1774. };
  1775. /**
  1776. * Returns a new Vector3 located at the center between "value1" and "value2".
  1777. */
  1778. Vector3.Center = function (value1, value2) {
  1779. var center = value1.add(value2);
  1780. center.scaleInPlace(0.5);
  1781. return center;
  1782. };
  1783. /**
  1784. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1785. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1786. * to something in order to rotate it from its local system to the given target system.
  1787. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1788. * Returns a new Vector3.
  1789. */
  1790. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1791. var rotation = Vector3.Zero();
  1792. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1793. return rotation;
  1794. };
  1795. /**
  1796. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1797. */
  1798. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1799. var quat = MathTmp.Quaternion[0];
  1800. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1801. quat.toEulerAnglesToRef(ref);
  1802. };
  1803. return Vector3;
  1804. }());
  1805. BABYLON.Vector3 = Vector3;
  1806. //Vector4 class created for EulerAngle class conversion to Quaternion
  1807. var Vector4 = (function () {
  1808. /**
  1809. * Creates a Vector4 object from the passed floats.
  1810. */
  1811. function Vector4(x, y, z, w) {
  1812. this.x = x;
  1813. this.y = y;
  1814. this.z = z;
  1815. this.w = w;
  1816. }
  1817. /**
  1818. * Returns the string with the Vector4 coordinates.
  1819. */
  1820. Vector4.prototype.toString = function () {
  1821. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1822. };
  1823. /**
  1824. * Returns the string "Vector4".
  1825. */
  1826. Vector4.prototype.getClassName = function () {
  1827. return "Vector4";
  1828. };
  1829. /**
  1830. * Returns the Vector4 hash code.
  1831. */
  1832. Vector4.prototype.getHashCode = function () {
  1833. var hash = this.x || 0;
  1834. hash = (hash * 397) ^ (this.y || 0);
  1835. hash = (hash * 397) ^ (this.z || 0);
  1836. hash = (hash * 397) ^ (this.w || 0);
  1837. return hash;
  1838. };
  1839. // Operators
  1840. /**
  1841. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.asArray = function () {
  1844. var result = [];
  1845. this.toArray(result, 0);
  1846. return result;
  1847. };
  1848. /**
  1849. * Populates the passed array from the passed index with the Vector4 coordinates.
  1850. * Returns the Vector4.
  1851. */
  1852. Vector4.prototype.toArray = function (array, index) {
  1853. if (index === undefined) {
  1854. index = 0;
  1855. }
  1856. array[index] = this.x;
  1857. array[index + 1] = this.y;
  1858. array[index + 2] = this.z;
  1859. array[index + 3] = this.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Adds the passed vector to the current Vector4.
  1864. * Returns the updated Vector4.
  1865. */
  1866. Vector4.prototype.addInPlace = function (otherVector) {
  1867. this.x += otherVector.x;
  1868. this.y += otherVector.y;
  1869. this.z += otherVector.z;
  1870. this.w += otherVector.w;
  1871. return this;
  1872. };
  1873. /**
  1874. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1875. */
  1876. Vector4.prototype.add = function (otherVector) {
  1877. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1878. };
  1879. /**
  1880. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1881. * Returns the current Vector4.
  1882. */
  1883. Vector4.prototype.addToRef = function (otherVector, result) {
  1884. result.x = this.x + otherVector.x;
  1885. result.y = this.y + otherVector.y;
  1886. result.z = this.z + otherVector.z;
  1887. result.w = this.w + otherVector.w;
  1888. return this;
  1889. };
  1890. /**
  1891. * Subtract in place the passed vector from the current Vector4.
  1892. * Returns the updated Vector4.
  1893. */
  1894. Vector4.prototype.subtractInPlace = function (otherVector) {
  1895. this.x -= otherVector.x;
  1896. this.y -= otherVector.y;
  1897. this.z -= otherVector.z;
  1898. this.w -= otherVector.w;
  1899. return this;
  1900. };
  1901. /**
  1902. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1903. */
  1904. Vector4.prototype.subtract = function (otherVector) {
  1905. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1906. };
  1907. /**
  1908. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1909. * Returns the current Vector4.
  1910. */
  1911. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1912. result.x = this.x - otherVector.x;
  1913. result.y = this.y - otherVector.y;
  1914. result.z = this.z - otherVector.z;
  1915. result.w = this.w - otherVector.w;
  1916. return this;
  1917. };
  1918. /**
  1919. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1920. */
  1921. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1922. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1923. };
  1924. /**
  1925. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1926. * Returns the current Vector4.
  1927. */
  1928. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1929. result.x = this.x - x;
  1930. result.y = this.y - y;
  1931. result.z = this.z - z;
  1932. result.w = this.w - w;
  1933. return this;
  1934. };
  1935. /**
  1936. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1937. */
  1938. Vector4.prototype.negate = function () {
  1939. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1940. };
  1941. /**
  1942. * Multiplies the current Vector4 coordinates by scale (float).
  1943. * Returns the updated Vector4.
  1944. */
  1945. Vector4.prototype.scaleInPlace = function (scale) {
  1946. this.x *= scale;
  1947. this.y *= scale;
  1948. this.z *= scale;
  1949. this.w *= scale;
  1950. return this;
  1951. };
  1952. /**
  1953. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1954. */
  1955. Vector4.prototype.scale = function (scale) {
  1956. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1957. };
  1958. /**
  1959. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1960. * Returns the current Vector4.
  1961. */
  1962. Vector4.prototype.scaleToRef = function (scale, result) {
  1963. result.x = this.x * scale;
  1964. result.y = this.y * scale;
  1965. result.z = this.z * scale;
  1966. result.w = this.w * scale;
  1967. return this;
  1968. };
  1969. /**
  1970. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1971. */
  1972. Vector4.prototype.equals = function (otherVector) {
  1973. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1974. };
  1975. /**
  1976. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1977. */
  1978. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1979. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1980. return otherVector
  1981. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1982. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1983. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1984. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1985. };
  1986. /**
  1987. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1988. */
  1989. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1990. return this.x === x && this.y === y && this.z === z && this.w === w;
  1991. };
  1992. /**
  1993. * Multiplies in place the current Vector4 by the passed one.
  1994. * Returns the updated Vector4.
  1995. */
  1996. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1997. this.x *= otherVector.x;
  1998. this.y *= otherVector.y;
  1999. this.z *= otherVector.z;
  2000. this.w *= otherVector.w;
  2001. return this;
  2002. };
  2003. /**
  2004. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2005. */
  2006. Vector4.prototype.multiply = function (otherVector) {
  2007. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2011. * Returns the current Vector4.
  2012. */
  2013. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2014. result.x = this.x * otherVector.x;
  2015. result.y = this.y * otherVector.y;
  2016. result.z = this.z * otherVector.z;
  2017. result.w = this.w * otherVector.w;
  2018. return this;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2022. */
  2023. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2024. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2028. */
  2029. Vector4.prototype.divide = function (otherVector) {
  2030. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.divideToRef = function (otherVector, result) {
  2037. result.x = this.x / otherVector.x;
  2038. result.y = this.y / otherVector.y;
  2039. result.z = this.z / otherVector.z;
  2040. result.w = this.w / otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2045. */
  2046. Vector4.prototype.MinimizeInPlace = function (other) {
  2047. if (other.x < this.x)
  2048. this.x = other.x;
  2049. if (other.y < this.y)
  2050. this.y = other.y;
  2051. if (other.z < this.z)
  2052. this.z = other.z;
  2053. if (other.w < this.w)
  2054. this.w = other.w;
  2055. return this;
  2056. };
  2057. /**
  2058. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2059. */
  2060. Vector4.prototype.MaximizeInPlace = function (other) {
  2061. if (other.x > this.x)
  2062. this.x = other.x;
  2063. if (other.y > this.y)
  2064. this.y = other.y;
  2065. if (other.z > this.z)
  2066. this.z = other.z;
  2067. if (other.w > this.w)
  2068. this.w = other.w;
  2069. return this;
  2070. };
  2071. // Properties
  2072. /**
  2073. * Returns the Vector4 length (float).
  2074. */
  2075. Vector4.prototype.length = function () {
  2076. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2077. };
  2078. /**
  2079. * Returns the Vector4 squared length (float).
  2080. */
  2081. Vector4.prototype.lengthSquared = function () {
  2082. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2083. };
  2084. // Methods
  2085. /**
  2086. * Normalizes in place the Vector4.
  2087. * Returns the updated Vector4.
  2088. */
  2089. Vector4.prototype.normalize = function () {
  2090. var len = this.length();
  2091. if (len === 0)
  2092. return this;
  2093. var num = 1.0 / len;
  2094. this.x *= num;
  2095. this.y *= num;
  2096. this.z *= num;
  2097. this.w *= num;
  2098. return this;
  2099. };
  2100. /**
  2101. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2102. */
  2103. Vector4.prototype.toVector3 = function () {
  2104. return new Vector3(this.x, this.y, this.z);
  2105. };
  2106. /**
  2107. * Returns a new Vector4 copied from the current one.
  2108. */
  2109. Vector4.prototype.clone = function () {
  2110. return new Vector4(this.x, this.y, this.z, this.w);
  2111. };
  2112. /**
  2113. * Updates the current Vector4 with the passed one coordinates.
  2114. * Returns the updated Vector4.
  2115. */
  2116. Vector4.prototype.copyFrom = function (source) {
  2117. this.x = source.x;
  2118. this.y = source.y;
  2119. this.z = source.z;
  2120. this.w = source.w;
  2121. return this;
  2122. };
  2123. /**
  2124. * Updates the current Vector4 coordinates with the passed floats.
  2125. * Returns the updated Vector4.
  2126. */
  2127. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2128. this.x = x;
  2129. this.y = y;
  2130. this.z = z;
  2131. this.w = w;
  2132. return this;
  2133. };
  2134. /**
  2135. * Updates the current Vector4 coordinates with the passed floats.
  2136. * Returns the updated Vector4.
  2137. */
  2138. Vector4.prototype.set = function (x, y, z, w) {
  2139. return this.copyFromFloats(x, y, z, w);
  2140. };
  2141. // Statics
  2142. /**
  2143. * Returns a new Vector4 set from the starting index of the passed array.
  2144. */
  2145. Vector4.FromArray = function (array, offset) {
  2146. if (!offset) {
  2147. offset = 0;
  2148. }
  2149. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2150. };
  2151. /**
  2152. * Updates the passed vector "result" from the starting index of the passed array.
  2153. */
  2154. Vector4.FromArrayToRef = function (array, offset, result) {
  2155. result.x = array[offset];
  2156. result.y = array[offset + 1];
  2157. result.z = array[offset + 2];
  2158. result.w = array[offset + 3];
  2159. };
  2160. /**
  2161. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2162. */
  2163. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2164. Vector4.FromArrayToRef(array, offset, result);
  2165. };
  2166. /**
  2167. * Updates the passed vector "result" coordinates from the passed floats.
  2168. */
  2169. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2170. result.x = x;
  2171. result.y = y;
  2172. result.z = z;
  2173. result.w = w;
  2174. };
  2175. /**
  2176. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2177. */
  2178. Vector4.Zero = function () {
  2179. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2180. };
  2181. /**
  2182. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2183. */
  2184. Vector4.One = function () {
  2185. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2186. };
  2187. /**
  2188. * Returns a new normalized Vector4 from the passed one.
  2189. */
  2190. Vector4.Normalize = function (vector) {
  2191. var result = Vector4.Zero();
  2192. Vector4.NormalizeToRef(vector, result);
  2193. return result;
  2194. };
  2195. /**
  2196. * Updates the passed vector "result" from the normalization of the passed one.
  2197. */
  2198. Vector4.NormalizeToRef = function (vector, result) {
  2199. result.copyFrom(vector);
  2200. result.normalize();
  2201. };
  2202. Vector4.Minimize = function (left, right) {
  2203. var min = left.clone();
  2204. min.MinimizeInPlace(right);
  2205. return min;
  2206. };
  2207. Vector4.Maximize = function (left, right) {
  2208. var max = left.clone();
  2209. max.MaximizeInPlace(right);
  2210. return max;
  2211. };
  2212. /**
  2213. * Returns the distance (float) between the vectors "value1" and "value2".
  2214. */
  2215. Vector4.Distance = function (value1, value2) {
  2216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2217. };
  2218. /**
  2219. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2220. */
  2221. Vector4.DistanceSquared = function (value1, value2) {
  2222. var x = value1.x - value2.x;
  2223. var y = value1.y - value2.y;
  2224. var z = value1.z - value2.z;
  2225. var w = value1.w - value2.w;
  2226. return (x * x) + (y * y) + (z * z) + (w * w);
  2227. };
  2228. /**
  2229. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2230. */
  2231. Vector4.Center = function (value1, value2) {
  2232. var center = value1.add(value2);
  2233. center.scaleInPlace(0.5);
  2234. return center;
  2235. };
  2236. /**
  2237. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2238. * This methods computes transformed normalized direction vectors only.
  2239. */
  2240. Vector4.TransformNormal = function (vector, transformation) {
  2241. var result = Vector4.Zero();
  2242. Vector4.TransformNormalToRef(vector, transformation, result);
  2243. return result;
  2244. };
  2245. /**
  2246. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2247. * This methods computes transformed normalized direction vectors only.
  2248. */
  2249. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2250. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2251. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2252. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2253. result.x = x;
  2254. result.y = y;
  2255. result.z = z;
  2256. result.w = vector.w;
  2257. };
  2258. /**
  2259. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2260. * This methods computes transformed normalized direction vectors only.
  2261. */
  2262. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2263. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2264. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2265. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2266. result.w = w;
  2267. };
  2268. return Vector4;
  2269. }());
  2270. BABYLON.Vector4 = Vector4;
  2271. var Size = (function () {
  2272. /**
  2273. * Creates a Size object from the passed width and height (floats).
  2274. */
  2275. function Size(width, height) {
  2276. this.width = width;
  2277. this.height = height;
  2278. }
  2279. // Returns a string with the Size width and height.
  2280. Size.prototype.toString = function () {
  2281. return "{W: " + this.width + ", H: " + this.height + "}";
  2282. };
  2283. /**
  2284. * Returns the string "Size"
  2285. */
  2286. Size.prototype.getClassName = function () {
  2287. return "Size";
  2288. };
  2289. /**
  2290. * Returns the Size hash code.
  2291. */
  2292. Size.prototype.getHashCode = function () {
  2293. var hash = this.width || 0;
  2294. hash = (hash * 397) ^ (this.height || 0);
  2295. return hash;
  2296. };
  2297. /**
  2298. * Updates the current size from the passed one.
  2299. * Returns the updated Size.
  2300. */
  2301. Size.prototype.copyFrom = function (src) {
  2302. this.width = src.width;
  2303. this.height = src.height;
  2304. };
  2305. /**
  2306. * Updates in place the current Size from the passed floats.
  2307. * Returns the updated Size.
  2308. */
  2309. Size.prototype.copyFromFloats = function (width, height) {
  2310. this.width = width;
  2311. this.height = height;
  2312. return this;
  2313. };
  2314. /**
  2315. * Updates in place the current Size from the passed floats.
  2316. * Returns the updated Size.
  2317. */
  2318. Size.prototype.set = function (width, height) {
  2319. return this.copyFromFloats(width, height);
  2320. };
  2321. /**
  2322. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2323. */
  2324. Size.prototype.multiplyByFloats = function (w, h) {
  2325. return new Size(this.width * w, this.height * h);
  2326. };
  2327. /**
  2328. * Returns a new Size copied from the passed one.
  2329. */
  2330. Size.prototype.clone = function () {
  2331. return new Size(this.width, this.height);
  2332. };
  2333. /**
  2334. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2335. */
  2336. Size.prototype.equals = function (other) {
  2337. if (!other) {
  2338. return false;
  2339. }
  2340. return (this.width === other.width) && (this.height === other.height);
  2341. };
  2342. Object.defineProperty(Size.prototype, "surface", {
  2343. /**
  2344. * Returns the surface of the Size : width * height (float).
  2345. */
  2346. get: function () {
  2347. return this.width * this.height;
  2348. },
  2349. enumerable: true,
  2350. configurable: true
  2351. });
  2352. /**
  2353. * Returns a new Size set to (0.0, 0.0)
  2354. */
  2355. Size.Zero = function () {
  2356. return new Size(0.0, 0.0);
  2357. };
  2358. /**
  2359. * Returns a new Size set as the addition result of the current Size and the passed one.
  2360. */
  2361. Size.prototype.add = function (otherSize) {
  2362. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2363. return r;
  2364. };
  2365. /**
  2366. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2367. */
  2368. Size.prototype.subtract = function (otherSize) {
  2369. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2370. return r;
  2371. };
  2372. /**
  2373. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2374. */
  2375. Size.Lerp = function (start, end, amount) {
  2376. var w = start.width + ((end.width - start.width) * amount);
  2377. var h = start.height + ((end.height - start.height) * amount);
  2378. return new Size(w, h);
  2379. };
  2380. return Size;
  2381. }());
  2382. BABYLON.Size = Size;
  2383. var Quaternion = (function () {
  2384. /**
  2385. * Creates a new Quaternion from the passed floats.
  2386. */
  2387. function Quaternion(x, y, z, w) {
  2388. if (x === void 0) { x = 0.0; }
  2389. if (y === void 0) { y = 0.0; }
  2390. if (z === void 0) { z = 0.0; }
  2391. if (w === void 0) { w = 1.0; }
  2392. this.x = x;
  2393. this.y = y;
  2394. this.z = z;
  2395. this.w = w;
  2396. }
  2397. /**
  2398. * Returns a string with the Quaternion coordinates.
  2399. */
  2400. Quaternion.prototype.toString = function () {
  2401. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2402. };
  2403. /**
  2404. * Returns the string "Quaternion".
  2405. */
  2406. Quaternion.prototype.getClassName = function () {
  2407. return "Quaternion";
  2408. };
  2409. /**
  2410. * Returns the Quaternion hash code.
  2411. */
  2412. Quaternion.prototype.getHashCode = function () {
  2413. var hash = this.x || 0;
  2414. hash = (hash * 397) ^ (this.y || 0);
  2415. hash = (hash * 397) ^ (this.z || 0);
  2416. hash = (hash * 397) ^ (this.w || 0);
  2417. return hash;
  2418. };
  2419. /**
  2420. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2421. */
  2422. Quaternion.prototype.asArray = function () {
  2423. return [this.x, this.y, this.z, this.w];
  2424. };
  2425. /**
  2426. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2427. */
  2428. Quaternion.prototype.equals = function (otherQuaternion) {
  2429. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2430. };
  2431. /**
  2432. * Returns a new Quaternion copied from the current one.
  2433. */
  2434. Quaternion.prototype.clone = function () {
  2435. return new Quaternion(this.x, this.y, this.z, this.w);
  2436. };
  2437. /**
  2438. * Updates the current Quaternion from the passed one coordinates.
  2439. * Returns the updated Quaterion.
  2440. */
  2441. Quaternion.prototype.copyFrom = function (other) {
  2442. this.x = other.x;
  2443. this.y = other.y;
  2444. this.z = other.z;
  2445. this.w = other.w;
  2446. return this;
  2447. };
  2448. /**
  2449. * Updates the current Quaternion from the passed float coordinates.
  2450. * Returns the updated Quaterion.
  2451. */
  2452. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2453. this.x = x;
  2454. this.y = y;
  2455. this.z = z;
  2456. this.w = w;
  2457. return this;
  2458. };
  2459. /**
  2460. * Updates the current Quaternion from the passed float coordinates.
  2461. * Returns the updated Quaterion.
  2462. */
  2463. Quaternion.prototype.set = function (x, y, z, w) {
  2464. return this.copyFromFloats(x, y, z, w);
  2465. };
  2466. /**
  2467. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2468. */
  2469. Quaternion.prototype.add = function (other) {
  2470. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2471. };
  2472. /**
  2473. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2474. */
  2475. Quaternion.prototype.subtract = function (other) {
  2476. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2477. };
  2478. /**
  2479. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2480. */
  2481. Quaternion.prototype.scale = function (value) {
  2482. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2483. };
  2484. /**
  2485. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2486. */
  2487. Quaternion.prototype.multiply = function (q1) {
  2488. var result = new Quaternion(0, 0, 0, 1.0);
  2489. this.multiplyToRef(q1, result);
  2490. return result;
  2491. };
  2492. /**
  2493. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2494. * Returns the current Quaternion.
  2495. */
  2496. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2497. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2498. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2499. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2500. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2501. result.copyFromFloats(x, y, z, w);
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.multiplyInPlace = function (q1) {
  2509. this.multiplyToRef(q1, this);
  2510. return this;
  2511. };
  2512. /**
  2513. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2514. * Returns the current Quaternion.
  2515. */
  2516. Quaternion.prototype.conjugateToRef = function (ref) {
  2517. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2518. return this;
  2519. };
  2520. /**
  2521. * Conjugates in place the current Quaternion.
  2522. * Returns the updated Quaternion.
  2523. */
  2524. Quaternion.prototype.conjugateInPlace = function () {
  2525. this.x *= -1;
  2526. this.y *= -1;
  2527. this.z *= -1;
  2528. return this;
  2529. };
  2530. /**
  2531. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2532. */
  2533. Quaternion.prototype.conjugate = function () {
  2534. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2535. return result;
  2536. };
  2537. /**
  2538. * Returns the Quaternion length (float).
  2539. */
  2540. Quaternion.prototype.length = function () {
  2541. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2542. };
  2543. /**
  2544. * Normalize in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.normalize = function () {
  2548. var length = 1.0 / this.length();
  2549. this.x *= length;
  2550. this.y *= length;
  2551. this.z *= length;
  2552. this.w *= length;
  2553. return this;
  2554. };
  2555. /**
  2556. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2557. */
  2558. Quaternion.prototype.toEulerAngles = function (order) {
  2559. if (order === void 0) { order = "YZX"; }
  2560. var result = Vector3.Zero();
  2561. this.toEulerAnglesToRef(result, order);
  2562. return result;
  2563. };
  2564. /**
  2565. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2566. * Returns the current Quaternion.
  2567. */
  2568. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2569. if (order === void 0) { order = "YZX"; }
  2570. var qz = this.z;
  2571. var qx = this.x;
  2572. var qy = this.y;
  2573. var qw = this.w;
  2574. var sqw = qw * qw;
  2575. var sqz = qz * qz;
  2576. var sqx = qx * qx;
  2577. var sqy = qy * qy;
  2578. var zAxisY = qy * qz - qx * qw;
  2579. var limit = .4999999;
  2580. if (zAxisY < -limit) {
  2581. result.y = 2 * Math.atan2(qy, qw);
  2582. result.x = Math.PI / 2;
  2583. result.z = 0;
  2584. }
  2585. else if (zAxisY > limit) {
  2586. result.y = 2 * Math.atan2(qy, qw);
  2587. result.x = -Math.PI / 2;
  2588. result.z = 0;
  2589. }
  2590. else {
  2591. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2592. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2593. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2594. }
  2595. return this;
  2596. };
  2597. /**
  2598. * Updates the passed rotation matrix with the current Quaternion values.
  2599. * Returns the current Quaternion.
  2600. */
  2601. Quaternion.prototype.toRotationMatrix = function (result) {
  2602. var xx = this.x * this.x;
  2603. var yy = this.y * this.y;
  2604. var zz = this.z * this.z;
  2605. var xy = this.x * this.y;
  2606. var zw = this.z * this.w;
  2607. var zx = this.z * this.x;
  2608. var yw = this.y * this.w;
  2609. var yz = this.y * this.z;
  2610. var xw = this.x * this.w;
  2611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2612. result.m[1] = 2.0 * (xy + zw);
  2613. result.m[2] = 2.0 * (zx - yw);
  2614. result.m[3] = 0;
  2615. result.m[4] = 2.0 * (xy - zw);
  2616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2617. result.m[6] = 2.0 * (yz + xw);
  2618. result.m[7] = 0;
  2619. result.m[8] = 2.0 * (zx + yw);
  2620. result.m[9] = 2.0 * (yz - xw);
  2621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2622. result.m[11] = 0;
  2623. result.m[12] = 0;
  2624. result.m[13] = 0;
  2625. result.m[14] = 0;
  2626. result.m[15] = 1.0;
  2627. result._markAsUpdated();
  2628. return this;
  2629. };
  2630. /**
  2631. * Updates the current Quaternion from the passed rotation matrix values.
  2632. * Returns the updated Quaternion.
  2633. */
  2634. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2635. Quaternion.FromRotationMatrixToRef(matrix, this);
  2636. return this;
  2637. };
  2638. // Statics
  2639. /**
  2640. * Returns a new Quaternion set from the passed rotation matrix values.
  2641. */
  2642. Quaternion.FromRotationMatrix = function (matrix) {
  2643. var result = new Quaternion();
  2644. Quaternion.FromRotationMatrixToRef(matrix, result);
  2645. return result;
  2646. };
  2647. /**
  2648. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2649. */
  2650. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2651. var data = matrix.m;
  2652. var m11 = data[0], m12 = data[4], m13 = data[8];
  2653. var m21 = data[1], m22 = data[5], m23 = data[9];
  2654. var m31 = data[2], m32 = data[6], m33 = data[10];
  2655. var trace = m11 + m22 + m33;
  2656. var s;
  2657. if (trace > 0) {
  2658. s = 0.5 / Math.sqrt(trace + 1.0);
  2659. result.w = 0.25 / s;
  2660. result.x = (m32 - m23) * s;
  2661. result.y = (m13 - m31) * s;
  2662. result.z = (m21 - m12) * s;
  2663. }
  2664. else if (m11 > m22 && m11 > m33) {
  2665. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2666. result.w = (m32 - m23) / s;
  2667. result.x = 0.25 * s;
  2668. result.y = (m12 + m21) / s;
  2669. result.z = (m13 + m31) / s;
  2670. }
  2671. else if (m22 > m33) {
  2672. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2673. result.w = (m13 - m31) / s;
  2674. result.x = (m12 + m21) / s;
  2675. result.y = 0.25 * s;
  2676. result.z = (m23 + m32) / s;
  2677. }
  2678. else {
  2679. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2680. result.w = (m21 - m12) / s;
  2681. result.x = (m13 + m31) / s;
  2682. result.y = (m23 + m32) / s;
  2683. result.z = 0.25 * s;
  2684. }
  2685. };
  2686. /**
  2687. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2688. */
  2689. Quaternion.Zero = function () {
  2690. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2691. };
  2692. /**
  2693. * Returns a new Quaternion as the inverted current Quaternion.
  2694. */
  2695. Quaternion.Inverse = function (q) {
  2696. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2697. };
  2698. /**
  2699. * Returns the identity Quaternion.
  2700. */
  2701. Quaternion.Identity = function () {
  2702. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2703. };
  2704. Quaternion.IsIdentity = function (quaternion) {
  2705. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2706. };
  2707. /**
  2708. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2709. */
  2710. Quaternion.RotationAxis = function (axis, angle) {
  2711. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2712. };
  2713. /**
  2714. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2715. */
  2716. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2717. var sin = Math.sin(angle / 2);
  2718. axis.normalize();
  2719. result.w = Math.cos(angle / 2);
  2720. result.x = axis.x * sin;
  2721. result.y = axis.y * sin;
  2722. result.z = axis.z * sin;
  2723. return result;
  2724. };
  2725. /**
  2726. * Retuns a new Quaternion set from the starting index of the passed array.
  2727. */
  2728. Quaternion.FromArray = function (array, offset) {
  2729. if (!offset) {
  2730. offset = 0;
  2731. }
  2732. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2733. };
  2734. /**
  2735. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2736. */
  2737. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2738. var q = new Quaternion();
  2739. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2740. return q;
  2741. };
  2742. /**
  2743. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2744. */
  2745. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2746. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2747. var halfRoll = roll * 0.5;
  2748. var halfPitch = pitch * 0.5;
  2749. var halfYaw = yaw * 0.5;
  2750. var sinRoll = Math.sin(halfRoll);
  2751. var cosRoll = Math.cos(halfRoll);
  2752. var sinPitch = Math.sin(halfPitch);
  2753. var cosPitch = Math.cos(halfPitch);
  2754. var sinYaw = Math.sin(halfYaw);
  2755. var cosYaw = Math.cos(halfYaw);
  2756. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2757. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2758. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2759. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2760. };
  2761. /**
  2762. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2763. */
  2764. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2765. var result = new Quaternion();
  2766. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2767. return result;
  2768. };
  2769. /**
  2770. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2771. */
  2772. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2773. // Produces a quaternion from Euler angles in the z-x-z orientation
  2774. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2775. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2776. var halfBeta = beta * 0.5;
  2777. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2778. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2779. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2780. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2781. };
  2782. /**
  2783. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2784. * cf to Vector3.RotationFromAxis() documentation.
  2785. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2786. */
  2787. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2788. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2789. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2790. return quat;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2794. * cf to Vector3.RotationFromAxis() documentation.
  2795. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2796. */
  2797. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2798. var rotMat = MathTmp.Matrix[0];
  2799. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2800. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2801. };
  2802. Quaternion.Slerp = function (left, right, amount) {
  2803. var result = Quaternion.Identity();
  2804. Quaternion.SlerpToRef(left, right, amount, result);
  2805. return result;
  2806. };
  2807. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2808. var num2;
  2809. var num3;
  2810. var num = amount;
  2811. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2812. var flag = false;
  2813. if (num4 < 0) {
  2814. flag = true;
  2815. num4 = -num4;
  2816. }
  2817. if (num4 > 0.999999) {
  2818. num3 = 1 - num;
  2819. num2 = flag ? -num : num;
  2820. }
  2821. else {
  2822. var num5 = Math.acos(num4);
  2823. var num6 = (1.0 / Math.sin(num5));
  2824. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2825. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2826. }
  2827. result.x = (num3 * left.x) + (num2 * right.x);
  2828. result.y = (num3 * left.y) + (num2 * right.y);
  2829. result.z = (num3 * left.z) + (num2 * right.z);
  2830. result.w = (num3 * left.w) + (num2 * right.w);
  2831. };
  2832. /**
  2833. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2834. */
  2835. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2836. var squared = amount * amount;
  2837. var cubed = amount * squared;
  2838. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2839. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2840. var part3 = (cubed - (2.0 * squared)) + amount;
  2841. var part4 = cubed - squared;
  2842. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2843. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2844. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2845. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2846. return new Quaternion(x, y, z, w);
  2847. };
  2848. return Quaternion;
  2849. }());
  2850. BABYLON.Quaternion = Quaternion;
  2851. var Matrix = (function () {
  2852. function Matrix() {
  2853. this._isIdentity = false;
  2854. this._isIdentityDirty = true;
  2855. this.m = new Float32Array(16);
  2856. this._markAsUpdated();
  2857. }
  2858. Matrix.prototype._markAsUpdated = function () {
  2859. this.updateFlag = Matrix._updateFlagSeed++;
  2860. this._isIdentityDirty = true;
  2861. };
  2862. // Properties
  2863. /**
  2864. * Boolean : True is the matrix is the identity matrix
  2865. */
  2866. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2867. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2868. if (this._isIdentityDirty) {
  2869. this._isIdentityDirty = false;
  2870. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2871. this._isIdentity = false;
  2872. }
  2873. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2874. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2875. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2876. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2877. this._isIdentity = false;
  2878. }
  2879. else {
  2880. this._isIdentity = true;
  2881. }
  2882. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2883. this._isIdentity = false;
  2884. }
  2885. }
  2886. return this._isIdentity;
  2887. };
  2888. /**
  2889. * Returns the matrix determinant (float).
  2890. */
  2891. Matrix.prototype.determinant = function () {
  2892. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2893. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2894. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2895. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2896. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2897. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2898. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2899. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2900. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2901. };
  2902. // Methods
  2903. /**
  2904. * Returns the matrix underlying array.
  2905. */
  2906. Matrix.prototype.toArray = function () {
  2907. return this.m;
  2908. };
  2909. /**
  2910. * Returns the matrix underlying array.
  2911. */
  2912. Matrix.prototype.asArray = function () {
  2913. return this.toArray();
  2914. };
  2915. /**
  2916. * Inverts in place the Matrix.
  2917. * Returns the Matrix inverted.
  2918. */
  2919. Matrix.prototype.invert = function () {
  2920. this.invertToRef(this);
  2921. return this;
  2922. };
  2923. /**
  2924. * Sets all the matrix elements to zero.
  2925. * Returns the Matrix.
  2926. */
  2927. Matrix.prototype.reset = function () {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = 0.0;
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2936. */
  2937. Matrix.prototype.add = function (other) {
  2938. var result = new Matrix();
  2939. this.addToRef(other, result);
  2940. return result;
  2941. };
  2942. /**
  2943. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.addToRef = function (other, result) {
  2947. for (var index = 0; index < 16; index++) {
  2948. result.m[index] = this.m[index] + other.m[index];
  2949. }
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Adds in place the passed matrix to the current Matrix.
  2955. * Returns the updated Matrix.
  2956. */
  2957. Matrix.prototype.addToSelf = function (other) {
  2958. for (var index = 0; index < 16; index++) {
  2959. this.m[index] += other.m[index];
  2960. }
  2961. this._markAsUpdated();
  2962. return this;
  2963. };
  2964. /**
  2965. * Sets the passed matrix with the current inverted Matrix.
  2966. * Returns the unmodified current Matrix.
  2967. */
  2968. Matrix.prototype.invertToRef = function (other) {
  2969. var l1 = this.m[0];
  2970. var l2 = this.m[1];
  2971. var l3 = this.m[2];
  2972. var l4 = this.m[3];
  2973. var l5 = this.m[4];
  2974. var l6 = this.m[5];
  2975. var l7 = this.m[6];
  2976. var l8 = this.m[7];
  2977. var l9 = this.m[8];
  2978. var l10 = this.m[9];
  2979. var l11 = this.m[10];
  2980. var l12 = this.m[11];
  2981. var l13 = this.m[12];
  2982. var l14 = this.m[13];
  2983. var l15 = this.m[14];
  2984. var l16 = this.m[15];
  2985. var l17 = (l11 * l16) - (l12 * l15);
  2986. var l18 = (l10 * l16) - (l12 * l14);
  2987. var l19 = (l10 * l15) - (l11 * l14);
  2988. var l20 = (l9 * l16) - (l12 * l13);
  2989. var l21 = (l9 * l15) - (l11 * l13);
  2990. var l22 = (l9 * l14) - (l10 * l13);
  2991. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2992. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2993. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2994. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2995. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2996. var l28 = (l7 * l16) - (l8 * l15);
  2997. var l29 = (l6 * l16) - (l8 * l14);
  2998. var l30 = (l6 * l15) - (l7 * l14);
  2999. var l31 = (l5 * l16) - (l8 * l13);
  3000. var l32 = (l5 * l15) - (l7 * l13);
  3001. var l33 = (l5 * l14) - (l6 * l13);
  3002. var l34 = (l7 * l12) - (l8 * l11);
  3003. var l35 = (l6 * l12) - (l8 * l10);
  3004. var l36 = (l6 * l11) - (l7 * l10);
  3005. var l37 = (l5 * l12) - (l8 * l9);
  3006. var l38 = (l5 * l11) - (l7 * l9);
  3007. var l39 = (l5 * l10) - (l6 * l9);
  3008. other.m[0] = l23 * l27;
  3009. other.m[4] = l24 * l27;
  3010. other.m[8] = l25 * l27;
  3011. other.m[12] = l26 * l27;
  3012. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3013. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3014. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3015. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3016. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3017. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3018. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3019. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3020. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3021. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3022. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3023. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3024. other._markAsUpdated();
  3025. return this;
  3026. };
  3027. /**
  3028. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3029. * Returns the updated Matrix.
  3030. */
  3031. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3032. this.m[12] = x;
  3033. this.m[13] = y;
  3034. this.m[14] = z;
  3035. this._markAsUpdated();
  3036. return this;
  3037. };
  3038. /**
  3039. * Inserts the translation vector in the current Matrix.
  3040. * Returns the updated Matrix.
  3041. */
  3042. Matrix.prototype.setTranslation = function (vector3) {
  3043. this.m[12] = vector3.x;
  3044. this.m[13] = vector3.y;
  3045. this.m[14] = vector3.z;
  3046. this._markAsUpdated();
  3047. return this;
  3048. };
  3049. /**
  3050. * Returns a new Vector3 as the extracted translation from the Matrix.
  3051. */
  3052. Matrix.prototype.getTranslation = function () {
  3053. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3054. };
  3055. /**
  3056. * Fill a Vector3 with the extracted translation from the Matrix.
  3057. */
  3058. Matrix.prototype.getTranslationToRef = function (result) {
  3059. result.x = this.m[12];
  3060. result.y = this.m[13];
  3061. result.z = this.m[14];
  3062. return this;
  3063. };
  3064. /**
  3065. * Remove rotation and scaling part from the Matrix.
  3066. * Returns the updated Matrix.
  3067. */
  3068. Matrix.prototype.removeRotationAndScaling = function () {
  3069. this.setRowFromFloats(0, 1, 0, 0, 0);
  3070. this.setRowFromFloats(1, 0, 1, 0, 0);
  3071. this.setRowFromFloats(2, 0, 0, 1, 0);
  3072. return this;
  3073. };
  3074. /**
  3075. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3076. */
  3077. Matrix.prototype.multiply = function (other) {
  3078. var result = new Matrix();
  3079. this.multiplyToRef(other, result);
  3080. return result;
  3081. };
  3082. /**
  3083. * Updates the current Matrix from the passed one values.
  3084. * Returns the updated Matrix.
  3085. */
  3086. Matrix.prototype.copyFrom = function (other) {
  3087. for (var index = 0; index < 16; index++) {
  3088. this.m[index] = other.m[index];
  3089. }
  3090. this._markAsUpdated();
  3091. return this;
  3092. };
  3093. /**
  3094. * Populates the passed array from the starting index with the Matrix values.
  3095. * Returns the Matrix.
  3096. */
  3097. Matrix.prototype.copyToArray = function (array, offset) {
  3098. if (offset === void 0) { offset = 0; }
  3099. for (var index = 0; index < 16; index++) {
  3100. array[offset + index] = this.m[index];
  3101. }
  3102. return this;
  3103. };
  3104. /**
  3105. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3106. */
  3107. Matrix.prototype.multiplyToRef = function (other, result) {
  3108. this.multiplyToArray(other, result.m, 0);
  3109. result._markAsUpdated();
  3110. return this;
  3111. };
  3112. /**
  3113. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3114. */
  3115. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3116. var tm0 = this.m[0];
  3117. var tm1 = this.m[1];
  3118. var tm2 = this.m[2];
  3119. var tm3 = this.m[3];
  3120. var tm4 = this.m[4];
  3121. var tm5 = this.m[5];
  3122. var tm6 = this.m[6];
  3123. var tm7 = this.m[7];
  3124. var tm8 = this.m[8];
  3125. var tm9 = this.m[9];
  3126. var tm10 = this.m[10];
  3127. var tm11 = this.m[11];
  3128. var tm12 = this.m[12];
  3129. var tm13 = this.m[13];
  3130. var tm14 = this.m[14];
  3131. var tm15 = this.m[15];
  3132. var om0 = other.m[0];
  3133. var om1 = other.m[1];
  3134. var om2 = other.m[2];
  3135. var om3 = other.m[3];
  3136. var om4 = other.m[4];
  3137. var om5 = other.m[5];
  3138. var om6 = other.m[6];
  3139. var om7 = other.m[7];
  3140. var om8 = other.m[8];
  3141. var om9 = other.m[9];
  3142. var om10 = other.m[10];
  3143. var om11 = other.m[11];
  3144. var om12 = other.m[12];
  3145. var om13 = other.m[13];
  3146. var om14 = other.m[14];
  3147. var om15 = other.m[15];
  3148. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3149. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3150. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3151. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3152. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3153. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3154. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3155. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3156. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3157. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3158. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3159. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3160. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3161. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3162. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3163. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3164. return this;
  3165. };
  3166. /**
  3167. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3168. */
  3169. Matrix.prototype.equals = function (value) {
  3170. return value &&
  3171. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3172. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3173. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3174. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3175. };
  3176. /**
  3177. * Returns a new Matrix from the current Matrix.
  3178. */
  3179. Matrix.prototype.clone = function () {
  3180. 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]);
  3181. };
  3182. /**
  3183. * Returns the string "Matrix"
  3184. */
  3185. Matrix.prototype.getClassName = function () {
  3186. return "Matrix";
  3187. };
  3188. /**
  3189. * Returns the Matrix hash code.
  3190. */
  3191. Matrix.prototype.getHashCode = function () {
  3192. var hash = this.m[0] || 0;
  3193. for (var i = 1; i < 16; i++) {
  3194. hash = (hash * 397) ^ (this.m[i] || 0);
  3195. }
  3196. return hash;
  3197. };
  3198. /**
  3199. * Decomposes the current Matrix into :
  3200. * - a scale vector3 passed as a reference to update,
  3201. * - a rotation quaternion passed as a reference to update,
  3202. * - a translation vector3 passed as a reference to update.
  3203. * Returns the boolean `true`.
  3204. */
  3205. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3206. translation.x = this.m[12];
  3207. translation.y = this.m[13];
  3208. translation.z = this.m[14];
  3209. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3210. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3211. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3212. if (this.determinant() <= 0) {
  3213. scale.y *= -1;
  3214. }
  3215. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3216. rotation.x = 0;
  3217. rotation.y = 0;
  3218. rotation.z = 0;
  3219. rotation.w = 1;
  3220. return false;
  3221. }
  3222. 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]);
  3223. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3224. return true;
  3225. };
  3226. /**
  3227. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3228. */
  3229. Matrix.prototype.getRotationMatrix = function () {
  3230. var result = Matrix.Identity();
  3231. this.getRotationMatrixToRef(result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3236. * Returns the current Matrix.
  3237. */
  3238. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3239. var m = this.m;
  3240. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3241. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3242. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3243. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3244. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3245. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3246. 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);
  3247. return this;
  3248. };
  3249. // Statics
  3250. /**
  3251. * Returns a new Matrix set from the starting index of the passed array.
  3252. */
  3253. Matrix.FromArray = function (array, offset) {
  3254. var result = new Matrix();
  3255. if (!offset) {
  3256. offset = 0;
  3257. }
  3258. Matrix.FromArrayToRef(array, offset, result);
  3259. return result;
  3260. };
  3261. /**
  3262. * Sets the passed "result" matrix from the starting index of the passed array.
  3263. */
  3264. Matrix.FromArrayToRef = function (array, offset, result) {
  3265. for (var index = 0; index < 16; index++) {
  3266. result.m[index] = array[index + offset];
  3267. }
  3268. result._markAsUpdated();
  3269. };
  3270. /**
  3271. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3272. */
  3273. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3274. for (var index = 0; index < 16; index++) {
  3275. result.m[index] = array[index + offset] * scale;
  3276. }
  3277. result._markAsUpdated();
  3278. };
  3279. /**
  3280. * Sets the passed matrix "result" with the 16 passed floats.
  3281. */
  3282. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3283. result.m[0] = initialM11;
  3284. result.m[1] = initialM12;
  3285. result.m[2] = initialM13;
  3286. result.m[3] = initialM14;
  3287. result.m[4] = initialM21;
  3288. result.m[5] = initialM22;
  3289. result.m[6] = initialM23;
  3290. result.m[7] = initialM24;
  3291. result.m[8] = initialM31;
  3292. result.m[9] = initialM32;
  3293. result.m[10] = initialM33;
  3294. result.m[11] = initialM34;
  3295. result.m[12] = initialM41;
  3296. result.m[13] = initialM42;
  3297. result.m[14] = initialM43;
  3298. result.m[15] = initialM44;
  3299. result._markAsUpdated();
  3300. };
  3301. /**
  3302. * Returns the index-th row of the current matrix as a new Vector4.
  3303. */
  3304. Matrix.prototype.getRow = function (index) {
  3305. if (index < 0 || index > 3) {
  3306. return null;
  3307. }
  3308. var i = index * 4;
  3309. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3310. };
  3311. /**
  3312. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3313. * Returns the updated Matrix.
  3314. */
  3315. Matrix.prototype.setRow = function (index, row) {
  3316. if (index < 0 || index > 3) {
  3317. return this;
  3318. }
  3319. var i = index * 4;
  3320. this.m[i + 0] = row.x;
  3321. this.m[i + 1] = row.y;
  3322. this.m[i + 2] = row.z;
  3323. this.m[i + 3] = row.w;
  3324. this._markAsUpdated();
  3325. return this;
  3326. };
  3327. /**
  3328. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3329. * Returns the updated Matrix.
  3330. */
  3331. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3332. if (index < 0 || index > 3) {
  3333. return this;
  3334. }
  3335. var i = index * 4;
  3336. this.m[i + 0] = x;
  3337. this.m[i + 1] = y;
  3338. this.m[i + 2] = z;
  3339. this.m[i + 3] = w;
  3340. this._markAsUpdated();
  3341. return this;
  3342. };
  3343. /**
  3344. * Returns a new Matrix set from the 16 passed floats.
  3345. */
  3346. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3347. var result = new Matrix();
  3348. result.m[0] = initialM11;
  3349. result.m[1] = initialM12;
  3350. result.m[2] = initialM13;
  3351. result.m[3] = initialM14;
  3352. result.m[4] = initialM21;
  3353. result.m[5] = initialM22;
  3354. result.m[6] = initialM23;
  3355. result.m[7] = initialM24;
  3356. result.m[8] = initialM31;
  3357. result.m[9] = initialM32;
  3358. result.m[10] = initialM33;
  3359. result.m[11] = initialM34;
  3360. result.m[12] = initialM41;
  3361. result.m[13] = initialM42;
  3362. result.m[14] = initialM43;
  3363. result.m[15] = initialM44;
  3364. return result;
  3365. };
  3366. /**
  3367. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3368. */
  3369. Matrix.Compose = function (scale, rotation, translation) {
  3370. var result = Matrix.Identity();
  3371. Matrix.ComposeToRef(scale, rotation, translation, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3376. */
  3377. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3378. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3379. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3380. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3381. result.setTranslation(translation);
  3382. };
  3383. /**
  3384. * Returns a new indentity Matrix.
  3385. */
  3386. Matrix.Identity = function () {
  3387. 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);
  3388. };
  3389. /**
  3390. * Sets the passed "result" as an identity matrix.
  3391. */
  3392. Matrix.IdentityToRef = function (result) {
  3393. 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);
  3394. };
  3395. /**
  3396. * Returns a new zero Matrix.
  3397. */
  3398. Matrix.Zero = function () {
  3399. 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);
  3400. };
  3401. /**
  3402. * Returns a new rotation matrix for "angle" radians around the X axis.
  3403. */
  3404. Matrix.RotationX = function (angle) {
  3405. var result = new Matrix();
  3406. Matrix.RotationXToRef(angle, result);
  3407. return result;
  3408. };
  3409. /**
  3410. * Returns a new Matrix as the passed inverted one.
  3411. */
  3412. Matrix.Invert = function (source) {
  3413. var result = new Matrix();
  3414. source.invertToRef(result);
  3415. return result;
  3416. };
  3417. /**
  3418. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3419. */
  3420. Matrix.RotationXToRef = function (angle, result) {
  3421. var s = Math.sin(angle);
  3422. var c = Math.cos(angle);
  3423. result.m[0] = 1.0;
  3424. result.m[15] = 1.0;
  3425. result.m[5] = c;
  3426. result.m[10] = c;
  3427. result.m[9] = -s;
  3428. result.m[6] = s;
  3429. result.m[1] = 0.0;
  3430. result.m[2] = 0.0;
  3431. result.m[3] = 0.0;
  3432. result.m[4] = 0.0;
  3433. result.m[7] = 0.0;
  3434. result.m[8] = 0.0;
  3435. result.m[11] = 0.0;
  3436. result.m[12] = 0.0;
  3437. result.m[13] = 0.0;
  3438. result.m[14] = 0.0;
  3439. result._markAsUpdated();
  3440. };
  3441. /**
  3442. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3443. */
  3444. Matrix.RotationY = function (angle) {
  3445. var result = new Matrix();
  3446. Matrix.RotationYToRef(angle, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3451. */
  3452. Matrix.RotationYToRef = function (angle, result) {
  3453. var s = Math.sin(angle);
  3454. var c = Math.cos(angle);
  3455. result.m[5] = 1.0;
  3456. result.m[15] = 1.0;
  3457. result.m[0] = c;
  3458. result.m[2] = -s;
  3459. result.m[8] = s;
  3460. result.m[10] = c;
  3461. result.m[1] = 0.0;
  3462. result.m[3] = 0.0;
  3463. result.m[4] = 0.0;
  3464. result.m[6] = 0.0;
  3465. result.m[7] = 0.0;
  3466. result.m[9] = 0.0;
  3467. result.m[11] = 0.0;
  3468. result.m[12] = 0.0;
  3469. result.m[13] = 0.0;
  3470. result.m[14] = 0.0;
  3471. result._markAsUpdated();
  3472. };
  3473. /**
  3474. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3475. */
  3476. Matrix.RotationZ = function (angle) {
  3477. var result = new Matrix();
  3478. Matrix.RotationZToRef(angle, result);
  3479. return result;
  3480. };
  3481. /**
  3482. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3483. */
  3484. Matrix.RotationZToRef = function (angle, result) {
  3485. var s = Math.sin(angle);
  3486. var c = Math.cos(angle);
  3487. result.m[10] = 1.0;
  3488. result.m[15] = 1.0;
  3489. result.m[0] = c;
  3490. result.m[1] = s;
  3491. result.m[4] = -s;
  3492. result.m[5] = c;
  3493. result.m[2] = 0.0;
  3494. result.m[3] = 0.0;
  3495. result.m[6] = 0.0;
  3496. result.m[7] = 0.0;
  3497. result.m[8] = 0.0;
  3498. result.m[9] = 0.0;
  3499. result.m[11] = 0.0;
  3500. result.m[12] = 0.0;
  3501. result.m[13] = 0.0;
  3502. result.m[14] = 0.0;
  3503. result._markAsUpdated();
  3504. };
  3505. /**
  3506. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3507. */
  3508. Matrix.RotationAxis = function (axis, angle) {
  3509. var result = Matrix.Zero();
  3510. Matrix.RotationAxisToRef(axis, angle, result);
  3511. return result;
  3512. };
  3513. /**
  3514. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3515. */
  3516. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3517. var s = Math.sin(-angle);
  3518. var c = Math.cos(-angle);
  3519. var c1 = 1 - c;
  3520. axis.normalize();
  3521. result.m[0] = (axis.x * axis.x) * c1 + c;
  3522. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3523. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3524. result.m[3] = 0.0;
  3525. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3526. result.m[5] = (axis.y * axis.y) * c1 + c;
  3527. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3528. result.m[7] = 0.0;
  3529. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3530. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3531. result.m[10] = (axis.z * axis.z) * c1 + c;
  3532. result.m[11] = 0.0;
  3533. result.m[15] = 1.0;
  3534. result._markAsUpdated();
  3535. };
  3536. /**
  3537. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3538. */
  3539. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3540. var result = new Matrix();
  3541. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3546. */
  3547. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3548. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3549. this._tempQuaternion.toRotationMatrix(result);
  3550. };
  3551. /**
  3552. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3553. */
  3554. Matrix.Scaling = function (x, y, z) {
  3555. var result = Matrix.Zero();
  3556. Matrix.ScalingToRef(x, y, z, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3561. */
  3562. Matrix.ScalingToRef = function (x, y, z, result) {
  3563. result.m[0] = x;
  3564. result.m[1] = 0.0;
  3565. result.m[2] = 0.0;
  3566. result.m[3] = 0.0;
  3567. result.m[4] = 0.0;
  3568. result.m[5] = y;
  3569. result.m[6] = 0.0;
  3570. result.m[7] = 0.0;
  3571. result.m[8] = 0.0;
  3572. result.m[9] = 0.0;
  3573. result.m[10] = z;
  3574. result.m[11] = 0.0;
  3575. result.m[12] = 0.0;
  3576. result.m[13] = 0.0;
  3577. result.m[14] = 0.0;
  3578. result.m[15] = 1.0;
  3579. result._markAsUpdated();
  3580. };
  3581. /**
  3582. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3583. */
  3584. Matrix.Translation = function (x, y, z) {
  3585. var result = Matrix.Identity();
  3586. Matrix.TranslationToRef(x, y, z, result);
  3587. return result;
  3588. };
  3589. /**
  3590. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3591. */
  3592. Matrix.TranslationToRef = function (x, y, z, result) {
  3593. 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);
  3594. };
  3595. /**
  3596. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3597. */
  3598. Matrix.Lerp = function (startValue, endValue, gradient) {
  3599. var result = Matrix.Zero();
  3600. for (var index = 0; index < 16; index++) {
  3601. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3602. }
  3603. result._markAsUpdated();
  3604. return result;
  3605. };
  3606. /**
  3607. * Returns a new Matrix whose values are computed by :
  3608. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3609. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3610. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3611. */
  3612. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3613. var startScale = new Vector3(0, 0, 0);
  3614. var startRotation = new Quaternion();
  3615. var startTranslation = new Vector3(0, 0, 0);
  3616. startValue.decompose(startScale, startRotation, startTranslation);
  3617. var endScale = new Vector3(0, 0, 0);
  3618. var endRotation = new Quaternion();
  3619. var endTranslation = new Vector3(0, 0, 0);
  3620. endValue.decompose(endScale, endRotation, endTranslation);
  3621. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3622. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3623. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3624. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3625. };
  3626. /**
  3627. * 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".
  3628. * This methods works for a Left-Handed system.
  3629. */
  3630. Matrix.LookAtLH = function (eye, target, up) {
  3631. var result = Matrix.Zero();
  3632. Matrix.LookAtLHToRef(eye, target, up, result);
  3633. return result;
  3634. };
  3635. /**
  3636. * 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".
  3637. * This methods works for a Left-Handed system.
  3638. */
  3639. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3640. // Z axis
  3641. target.subtractToRef(eye, this._zAxis);
  3642. this._zAxis.normalize();
  3643. // X axis
  3644. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3645. if (this._xAxis.lengthSquared() === 0) {
  3646. this._xAxis.x = 1.0;
  3647. }
  3648. else {
  3649. this._xAxis.normalize();
  3650. }
  3651. // Y axis
  3652. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3653. this._yAxis.normalize();
  3654. // Eye angles
  3655. var ex = -Vector3.Dot(this._xAxis, eye);
  3656. var ey = -Vector3.Dot(this._yAxis, eye);
  3657. var ez = -Vector3.Dot(this._zAxis, eye);
  3658. 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);
  3659. };
  3660. /**
  3661. * 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".
  3662. * This methods works for a Right-Handed system.
  3663. */
  3664. Matrix.LookAtRH = function (eye, target, up) {
  3665. var result = Matrix.Zero();
  3666. Matrix.LookAtRHToRef(eye, target, up, result);
  3667. return result;
  3668. };
  3669. /**
  3670. * 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".
  3671. * This methods works for a Left-Handed system.
  3672. */
  3673. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3674. // Z axis
  3675. eye.subtractToRef(target, this._zAxis);
  3676. this._zAxis.normalize();
  3677. // X axis
  3678. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3679. if (this._xAxis.lengthSquared() === 0) {
  3680. this._xAxis.x = 1.0;
  3681. }
  3682. else {
  3683. this._xAxis.normalize();
  3684. }
  3685. // Y axis
  3686. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3687. this._yAxis.normalize();
  3688. // Eye angles
  3689. var ex = -Vector3.Dot(this._xAxis, eye);
  3690. var ey = -Vector3.Dot(this._yAxis, eye);
  3691. var ez = -Vector3.Dot(this._zAxis, eye);
  3692. 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);
  3693. };
  3694. /**
  3695. * 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.
  3696. */
  3697. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3698. var matrix = Matrix.Zero();
  3699. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3700. return matrix;
  3701. };
  3702. /**
  3703. * 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.
  3704. */
  3705. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3706. var n = znear;
  3707. var f = zfar;
  3708. var a = 2.0 / width;
  3709. var b = 2.0 / height;
  3710. var c = 2.0 / (f - n);
  3711. var d = -(f + n) / (f - n);
  3712. 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);
  3713. };
  3714. /**
  3715. * 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.
  3716. */
  3717. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3718. var matrix = Matrix.Zero();
  3719. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3720. return matrix;
  3721. };
  3722. /**
  3723. * 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.
  3724. */
  3725. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3726. var n = znear;
  3727. var f = zfar;
  3728. var a = 2.0 / (right - left);
  3729. var b = 2.0 / (top - bottom);
  3730. var c = 2.0 / (f - n);
  3731. var d = -(f + n) / (f - n);
  3732. var i0 = (left + right) / (left - right);
  3733. var i1 = (top + bottom) / (bottom - top);
  3734. 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);
  3735. };
  3736. /**
  3737. * 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.
  3738. */
  3739. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3740. var matrix = Matrix.Zero();
  3741. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3742. return matrix;
  3743. };
  3744. /**
  3745. * 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.
  3746. */
  3747. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3748. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3749. result.m[10] *= -1.0;
  3750. };
  3751. /**
  3752. * 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.
  3753. */
  3754. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3755. var matrix = Matrix.Zero();
  3756. var n = znear;
  3757. var f = zfar;
  3758. var a = 2.0 * n / width;
  3759. var b = 2.0 * n / height;
  3760. var c = (f + n) / (f - n);
  3761. var d = -2.0 * f * n / (f - n);
  3762. 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);
  3763. return matrix;
  3764. };
  3765. /**
  3766. * 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.
  3767. */
  3768. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3769. var matrix = Matrix.Zero();
  3770. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3771. return matrix;
  3772. };
  3773. /**
  3774. * 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.
  3775. */
  3776. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3777. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3778. var n = znear;
  3779. var f = zfar;
  3780. var t = 1.0 / (Math.tan(fov * 0.5));
  3781. var a = isVerticalFovFixed ? (t / aspect) : t;
  3782. var b = isVerticalFovFixed ? t : (t * aspect);
  3783. var c = (f + n) / (f - n);
  3784. var d = -2.0 * f * n / (f - n);
  3785. 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);
  3786. };
  3787. /**
  3788. * 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.
  3789. */
  3790. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3791. var matrix = Matrix.Zero();
  3792. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3793. return matrix;
  3794. };
  3795. /**
  3796. * 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.
  3797. */
  3798. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3799. //alternatively this could be expressed as:
  3800. // m = PerspectiveFovLHToRef
  3801. // m[10] *= -1.0;
  3802. // m[11] *= -1.0;
  3803. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3804. var n = znear;
  3805. var f = zfar;
  3806. var t = 1.0 / (Math.tan(fov * 0.5));
  3807. var a = isVerticalFovFixed ? (t / aspect) : t;
  3808. var b = isVerticalFovFixed ? t : (t * aspect);
  3809. var c = -(f + n) / (f - n);
  3810. var d = -2 * f * n / (f - n);
  3811. 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);
  3812. };
  3813. /**
  3814. * 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.
  3815. */
  3816. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3817. if (rightHanded === void 0) { rightHanded = false; }
  3818. var rightHandedFactor = rightHanded ? -1 : 1;
  3819. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3820. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3821. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3822. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3823. var xScale = 2.0 / (leftTan + rightTan);
  3824. var yScale = 2.0 / (upTan + downTan);
  3825. result.m[0] = xScale;
  3826. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3827. result.m[5] = yScale;
  3828. result.m[6] = result.m[7] = 0.0;
  3829. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3830. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3831. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3832. result.m[10] = -zfar / (znear - zfar);
  3833. result.m[11] = 1.0 * rightHandedFactor;
  3834. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3835. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3836. // result.m[14] = (znear * zfar) / (znear - zfar);
  3837. result._markAsUpdated();
  3838. };
  3839. /**
  3840. * Returns the final transformation matrix : world * view * projection * viewport
  3841. */
  3842. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3843. var cw = viewport.width;
  3844. var ch = viewport.height;
  3845. var cx = viewport.x;
  3846. var cy = viewport.y;
  3847. 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);
  3848. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3849. };
  3850. /**
  3851. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3852. */
  3853. Matrix.GetAsMatrix2x2 = function (matrix) {
  3854. return new Float32Array([
  3855. matrix.m[0], matrix.m[1],
  3856. matrix.m[4], matrix.m[5]
  3857. ]);
  3858. };
  3859. /**
  3860. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3861. */
  3862. Matrix.GetAsMatrix3x3 = function (matrix) {
  3863. return new Float32Array([
  3864. matrix.m[0], matrix.m[1], matrix.m[2],
  3865. matrix.m[4], matrix.m[5], matrix.m[6],
  3866. matrix.m[8], matrix.m[9], matrix.m[10]
  3867. ]);
  3868. };
  3869. /**
  3870. * Compute the transpose of the passed Matrix.
  3871. * Returns a new Matrix.
  3872. */
  3873. Matrix.Transpose = function (matrix) {
  3874. var result = new Matrix();
  3875. result.m[0] = matrix.m[0];
  3876. result.m[1] = matrix.m[4];
  3877. result.m[2] = matrix.m[8];
  3878. result.m[3] = matrix.m[12];
  3879. result.m[4] = matrix.m[1];
  3880. result.m[5] = matrix.m[5];
  3881. result.m[6] = matrix.m[9];
  3882. result.m[7] = matrix.m[13];
  3883. result.m[8] = matrix.m[2];
  3884. result.m[9] = matrix.m[6];
  3885. result.m[10] = matrix.m[10];
  3886. result.m[11] = matrix.m[14];
  3887. result.m[12] = matrix.m[3];
  3888. result.m[13] = matrix.m[7];
  3889. result.m[14] = matrix.m[11];
  3890. result.m[15] = matrix.m[15];
  3891. return result;
  3892. };
  3893. /**
  3894. * Returns a new Matrix as the reflection matrix across the passed plane.
  3895. */
  3896. Matrix.Reflection = function (plane) {
  3897. var matrix = new Matrix();
  3898. Matrix.ReflectionToRef(plane, matrix);
  3899. return matrix;
  3900. };
  3901. /**
  3902. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3903. */
  3904. Matrix.ReflectionToRef = function (plane, result) {
  3905. plane.normalize();
  3906. var x = plane.normal.x;
  3907. var y = plane.normal.y;
  3908. var z = plane.normal.z;
  3909. var temp = -2 * x;
  3910. var temp2 = -2 * y;
  3911. var temp3 = -2 * z;
  3912. result.m[0] = (temp * x) + 1;
  3913. result.m[1] = temp2 * x;
  3914. result.m[2] = temp3 * x;
  3915. result.m[3] = 0.0;
  3916. result.m[4] = temp * y;
  3917. result.m[5] = (temp2 * y) + 1;
  3918. result.m[6] = temp3 * y;
  3919. result.m[7] = 0.0;
  3920. result.m[8] = temp * z;
  3921. result.m[9] = temp2 * z;
  3922. result.m[10] = (temp3 * z) + 1;
  3923. result.m[11] = 0.0;
  3924. result.m[12] = temp * plane.d;
  3925. result.m[13] = temp2 * plane.d;
  3926. result.m[14] = temp3 * plane.d;
  3927. result.m[15] = 1.0;
  3928. result._markAsUpdated();
  3929. };
  3930. /**
  3931. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3932. */
  3933. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3934. result.m[0] = xaxis.x;
  3935. result.m[1] = xaxis.y;
  3936. result.m[2] = xaxis.z;
  3937. result.m[3] = 0.0;
  3938. result.m[4] = yaxis.x;
  3939. result.m[5] = yaxis.y;
  3940. result.m[6] = yaxis.z;
  3941. result.m[7] = 0.0;
  3942. result.m[8] = zaxis.x;
  3943. result.m[9] = zaxis.y;
  3944. result.m[10] = zaxis.z;
  3945. result.m[11] = 0.0;
  3946. result.m[12] = 0.0;
  3947. result.m[13] = 0.0;
  3948. result.m[14] = 0.0;
  3949. result.m[15] = 1.0;
  3950. result._markAsUpdated();
  3951. };
  3952. /**
  3953. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3954. */
  3955. Matrix.FromQuaternionToRef = function (quat, result) {
  3956. var xx = quat.x * quat.x;
  3957. var yy = quat.y * quat.y;
  3958. var zz = quat.z * quat.z;
  3959. var xy = quat.x * quat.y;
  3960. var zw = quat.z * quat.w;
  3961. var zx = quat.z * quat.x;
  3962. var yw = quat.y * quat.w;
  3963. var yz = quat.y * quat.z;
  3964. var xw = quat.x * quat.w;
  3965. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3966. result.m[1] = 2.0 * (xy + zw);
  3967. result.m[2] = 2.0 * (zx - yw);
  3968. result.m[3] = 0.0;
  3969. result.m[4] = 2.0 * (xy - zw);
  3970. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3971. result.m[6] = 2.0 * (yz + xw);
  3972. result.m[7] = 0.0;
  3973. result.m[8] = 2.0 * (zx + yw);
  3974. result.m[9] = 2.0 * (yz - xw);
  3975. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3976. result.m[11] = 0.0;
  3977. result.m[12] = 0.0;
  3978. result.m[13] = 0.0;
  3979. result.m[14] = 0.0;
  3980. result.m[15] = 1.0;
  3981. result._markAsUpdated();
  3982. };
  3983. Matrix._tempQuaternion = new Quaternion();
  3984. Matrix._xAxis = Vector3.Zero();
  3985. Matrix._yAxis = Vector3.Zero();
  3986. Matrix._zAxis = Vector3.Zero();
  3987. Matrix._updateFlagSeed = 0;
  3988. return Matrix;
  3989. }());
  3990. BABYLON.Matrix = Matrix;
  3991. var Plane = (function () {
  3992. /**
  3993. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3994. */
  3995. function Plane(a, b, c, d) {
  3996. this.normal = new Vector3(a, b, c);
  3997. this.d = d;
  3998. }
  3999. /**
  4000. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4001. */
  4002. Plane.prototype.asArray = function () {
  4003. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4004. };
  4005. // Methods
  4006. /**
  4007. * Returns a new plane copied from the current Plane.
  4008. */
  4009. Plane.prototype.clone = function () {
  4010. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4011. };
  4012. /**
  4013. * Returns the string "Plane".
  4014. */
  4015. Plane.prototype.getClassName = function () {
  4016. return "Plane";
  4017. };
  4018. /**
  4019. * Returns the Plane hash code.
  4020. */
  4021. Plane.prototype.getHashCode = function () {
  4022. var hash = this.normal.getHashCode();
  4023. hash = (hash * 397) ^ (this.d || 0);
  4024. return hash;
  4025. };
  4026. /**
  4027. * Normalize the current Plane in place.
  4028. * Returns the updated Plane.
  4029. */
  4030. Plane.prototype.normalize = function () {
  4031. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4032. var magnitude = 0.0;
  4033. if (norm !== 0) {
  4034. magnitude = 1.0 / norm;
  4035. }
  4036. this.normal.x *= magnitude;
  4037. this.normal.y *= magnitude;
  4038. this.normal.z *= magnitude;
  4039. this.d *= magnitude;
  4040. return this;
  4041. };
  4042. /**
  4043. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4044. */
  4045. Plane.prototype.transform = function (transformation) {
  4046. var transposedMatrix = Matrix.Transpose(transformation);
  4047. var x = this.normal.x;
  4048. var y = this.normal.y;
  4049. var z = this.normal.z;
  4050. var d = this.d;
  4051. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4052. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4053. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4054. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4055. return new Plane(normalX, normalY, normalZ, finalD);
  4056. };
  4057. /**
  4058. * Returns the dot product (float) of the point coordinates and the plane normal.
  4059. */
  4060. Plane.prototype.dotCoordinate = function (point) {
  4061. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4062. };
  4063. /**
  4064. * Updates the current Plane from the plane defined by the three passed points.
  4065. * Returns the updated Plane.
  4066. */
  4067. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4068. var x1 = point2.x - point1.x;
  4069. var y1 = point2.y - point1.y;
  4070. var z1 = point2.z - point1.z;
  4071. var x2 = point3.x - point1.x;
  4072. var y2 = point3.y - point1.y;
  4073. var z2 = point3.z - point1.z;
  4074. var yz = (y1 * z2) - (z1 * y2);
  4075. var xz = (z1 * x2) - (x1 * z2);
  4076. var xy = (x1 * y2) - (y1 * x2);
  4077. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4078. var invPyth;
  4079. if (pyth !== 0) {
  4080. invPyth = 1.0 / pyth;
  4081. }
  4082. else {
  4083. invPyth = 0.0;
  4084. }
  4085. this.normal.x = yz * invPyth;
  4086. this.normal.y = xz * invPyth;
  4087. this.normal.z = xy * invPyth;
  4088. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4089. return this;
  4090. };
  4091. /**
  4092. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4093. */
  4094. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4095. var dot = Vector3.Dot(this.normal, direction);
  4096. return (dot <= epsilon);
  4097. };
  4098. /**
  4099. * Returns the signed distance (float) from the passed point to the Plane.
  4100. */
  4101. Plane.prototype.signedDistanceTo = function (point) {
  4102. return Vector3.Dot(point, this.normal) + this.d;
  4103. };
  4104. // Statics
  4105. /**
  4106. * Returns a new Plane from the passed array.
  4107. */
  4108. Plane.FromArray = function (array) {
  4109. return new Plane(array[0], array[1], array[2], array[3]);
  4110. };
  4111. /**
  4112. * Returns a new Plane defined by the three passed points.
  4113. */
  4114. Plane.FromPoints = function (point1, point2, point3) {
  4115. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4116. result.copyFromPoints(point1, point2, point3);
  4117. return result;
  4118. };
  4119. /**
  4120. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4121. * Note : the vector "normal" is updated because normalized.
  4122. */
  4123. Plane.FromPositionAndNormal = function (origin, normal) {
  4124. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4125. normal.normalize();
  4126. result.normal = normal;
  4127. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4128. return result;
  4129. };
  4130. /**
  4131. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4132. */
  4133. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4134. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4135. return Vector3.Dot(point, normal) + d;
  4136. };
  4137. return Plane;
  4138. }());
  4139. BABYLON.Plane = Plane;
  4140. var Viewport = (function () {
  4141. /**
  4142. * Creates a Viewport object located at (x, y) and sized (width, height).
  4143. */
  4144. function Viewport(x, y, width, height) {
  4145. this.x = x;
  4146. this.y = y;
  4147. this.width = width;
  4148. this.height = height;
  4149. }
  4150. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4151. if (renderWidthOrEngine.getRenderWidth) {
  4152. var engine = renderWidthOrEngine;
  4153. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4154. }
  4155. var renderWidth = renderWidthOrEngine;
  4156. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4157. };
  4158. /**
  4159. * Returns a new Viewport copied from the current one.
  4160. */
  4161. Viewport.prototype.clone = function () {
  4162. return new Viewport(this.x, this.y, this.width, this.height);
  4163. };
  4164. return Viewport;
  4165. }());
  4166. BABYLON.Viewport = Viewport;
  4167. var Frustum = (function () {
  4168. function Frustum() {
  4169. }
  4170. /**
  4171. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4172. */
  4173. Frustum.GetPlanes = function (transform) {
  4174. var frustumPlanes = [];
  4175. for (var index = 0; index < 6; index++) {
  4176. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4177. }
  4178. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4179. return frustumPlanes;
  4180. };
  4181. /**
  4182. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4183. */
  4184. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4185. // Near
  4186. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4187. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4188. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4189. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4190. frustumPlanes[0].normalize();
  4191. // Far
  4192. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4193. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4194. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4195. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4196. frustumPlanes[1].normalize();
  4197. // Left
  4198. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4199. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4200. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4201. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4202. frustumPlanes[2].normalize();
  4203. // Right
  4204. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4205. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4206. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4207. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4208. frustumPlanes[3].normalize();
  4209. // Top
  4210. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4211. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4212. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4213. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4214. frustumPlanes[4].normalize();
  4215. // Bottom
  4216. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4217. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4218. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4219. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4220. frustumPlanes[5].normalize();
  4221. };
  4222. return Frustum;
  4223. }());
  4224. BABYLON.Frustum = Frustum;
  4225. var Space;
  4226. (function (Space) {
  4227. Space[Space["LOCAL"] = 0] = "LOCAL";
  4228. Space[Space["WORLD"] = 1] = "WORLD";
  4229. Space[Space["BONE"] = 2] = "BONE";
  4230. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4231. var Axis = (function () {
  4232. function Axis() {
  4233. }
  4234. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4235. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4236. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4237. return Axis;
  4238. }());
  4239. BABYLON.Axis = Axis;
  4240. ;
  4241. var BezierCurve = (function () {
  4242. function BezierCurve() {
  4243. }
  4244. /**
  4245. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4246. */
  4247. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4248. // Extract X (which is equal to time here)
  4249. var f0 = 1 - 3 * x2 + 3 * x1;
  4250. var f1 = 3 * x2 - 6 * x1;
  4251. var f2 = 3 * x1;
  4252. var refinedT = t;
  4253. for (var i = 0; i < 5; i++) {
  4254. var refinedT2 = refinedT * refinedT;
  4255. var refinedT3 = refinedT2 * refinedT;
  4256. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4257. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4258. refinedT -= (x - t) * slope;
  4259. refinedT = Math.min(1, Math.max(0, refinedT));
  4260. }
  4261. // Resolve cubic bezier for the given x
  4262. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4263. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4264. Math.pow(refinedT, 3);
  4265. };
  4266. return BezierCurve;
  4267. }());
  4268. BABYLON.BezierCurve = BezierCurve;
  4269. var Orientation;
  4270. (function (Orientation) {
  4271. Orientation[Orientation["CW"] = 0] = "CW";
  4272. Orientation[Orientation["CCW"] = 1] = "CCW";
  4273. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4274. var Angle = (function () {
  4275. /**
  4276. * Creates an Angle object of "radians" radians (float).
  4277. */
  4278. function Angle(radians) {
  4279. var _this = this;
  4280. /**
  4281. * Returns the Angle value in degrees (float).
  4282. */
  4283. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4284. /**
  4285. * Returns the Angle value in radians (float).
  4286. */
  4287. this.radians = function () { return _this._radians; };
  4288. this._radians = radians;
  4289. if (this._radians < 0.0)
  4290. this._radians += (2.0 * Math.PI);
  4291. }
  4292. /**
  4293. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4294. */
  4295. Angle.BetweenTwoPoints = function (a, b) {
  4296. var delta = b.subtract(a);
  4297. var theta = Math.atan2(delta.y, delta.x);
  4298. return new Angle(theta);
  4299. };
  4300. /**
  4301. * Returns a new Angle object from the passed float in radians.
  4302. */
  4303. Angle.FromRadians = function (radians) {
  4304. return new Angle(radians);
  4305. };
  4306. /**
  4307. * Returns a new Angle object from the passed float in degrees.
  4308. */
  4309. Angle.FromDegrees = function (degrees) {
  4310. return new Angle(degrees * Math.PI / 180.0);
  4311. };
  4312. return Angle;
  4313. }());
  4314. BABYLON.Angle = Angle;
  4315. var Arc2 = (function () {
  4316. /**
  4317. * Creates an Arc object from the three passed points : start, middle and end.
  4318. */
  4319. function Arc2(startPoint, midPoint, endPoint) {
  4320. this.startPoint = startPoint;
  4321. this.midPoint = midPoint;
  4322. this.endPoint = endPoint;
  4323. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4324. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4325. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4326. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4327. 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);
  4328. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4329. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4330. var a1 = this.startAngle.degrees();
  4331. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4332. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4333. // angles correction
  4334. if (a2 - a1 > +180.0)
  4335. a2 -= 360.0;
  4336. if (a2 - a1 < -180.0)
  4337. a2 += 360.0;
  4338. if (a3 - a2 > +180.0)
  4339. a3 -= 360.0;
  4340. if (a3 - a2 < -180.0)
  4341. a3 += 360.0;
  4342. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4343. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4344. }
  4345. return Arc2;
  4346. }());
  4347. BABYLON.Arc2 = Arc2;
  4348. var Path2 = (function () {
  4349. /**
  4350. * Creates a Path2 object from the starting 2D coordinates x and y.
  4351. */
  4352. function Path2(x, y) {
  4353. this._points = new Array();
  4354. this._length = 0.0;
  4355. this.closed = false;
  4356. this._points.push(new Vector2(x, y));
  4357. }
  4358. /**
  4359. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4360. * Returns the updated Path2.
  4361. */
  4362. Path2.prototype.addLineTo = function (x, y) {
  4363. if (closed) {
  4364. //Tools.Error("cannot add lines to closed paths");
  4365. return this;
  4366. }
  4367. var newPoint = new Vector2(x, y);
  4368. var previousPoint = this._points[this._points.length - 1];
  4369. this._points.push(newPoint);
  4370. this._length += newPoint.subtract(previousPoint).length();
  4371. return this;
  4372. };
  4373. /**
  4374. * 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.
  4375. * Returns the updated Path2.
  4376. */
  4377. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4378. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4379. if (closed) {
  4380. //Tools.Error("cannot add arcs to closed paths");
  4381. return this;
  4382. }
  4383. var startPoint = this._points[this._points.length - 1];
  4384. var midPoint = new Vector2(midX, midY);
  4385. var endPoint = new Vector2(endX, endY);
  4386. var arc = new Arc2(startPoint, midPoint, endPoint);
  4387. var increment = arc.angle.radians() / numberOfSegments;
  4388. if (arc.orientation === Orientation.CW)
  4389. increment *= -1;
  4390. var currentAngle = arc.startAngle.radians() + increment;
  4391. for (var i = 0; i < numberOfSegments; i++) {
  4392. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4393. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4394. this.addLineTo(x, y);
  4395. currentAngle += increment;
  4396. }
  4397. return this;
  4398. };
  4399. /**
  4400. * Closes the Path2.
  4401. * Returns the Path2.
  4402. */
  4403. Path2.prototype.close = function () {
  4404. this.closed = true;
  4405. return this;
  4406. };
  4407. /**
  4408. * Returns the Path2 total length (float).
  4409. */
  4410. Path2.prototype.length = function () {
  4411. var result = this._length;
  4412. if (!this.closed) {
  4413. var lastPoint = this._points[this._points.length - 1];
  4414. var firstPoint = this._points[0];
  4415. result += (firstPoint.subtract(lastPoint).length());
  4416. }
  4417. return result;
  4418. };
  4419. /**
  4420. * Returns the Path2 internal array of points.
  4421. */
  4422. Path2.prototype.getPoints = function () {
  4423. return this._points;
  4424. };
  4425. /**
  4426. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4427. */
  4428. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4429. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4430. //Tools.Error("normalized length position should be between 0 and 1.");
  4431. return Vector2.Zero();
  4432. }
  4433. var lengthPosition = normalizedLengthPosition * this.length();
  4434. var previousOffset = 0;
  4435. for (var i = 0; i < this._points.length; i++) {
  4436. var j = (i + 1) % this._points.length;
  4437. var a = this._points[i];
  4438. var b = this._points[j];
  4439. var bToA = b.subtract(a);
  4440. var nextOffset = (bToA.length() + previousOffset);
  4441. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4442. var dir = bToA.normalize();
  4443. var localOffset = lengthPosition - previousOffset;
  4444. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4445. }
  4446. previousOffset = nextOffset;
  4447. }
  4448. //Tools.Error("internal error");
  4449. return Vector2.Zero();
  4450. };
  4451. /**
  4452. * Returns a new Path2 starting at the coordinates (x, y).
  4453. */
  4454. Path2.StartingAt = function (x, y) {
  4455. return new Path2(x, y);
  4456. };
  4457. return Path2;
  4458. }());
  4459. BABYLON.Path2 = Path2;
  4460. var Path3D = (function () {
  4461. /**
  4462. * new Path3D(path, normal, raw)
  4463. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4464. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4465. * path : an array of Vector3, the curve axis of the Path3D
  4466. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4467. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4468. */
  4469. function Path3D(path, firstNormal, raw) {
  4470. this.path = path;
  4471. this._curve = new Array();
  4472. this._distances = new Array();
  4473. this._tangents = new Array();
  4474. this._normals = new Array();
  4475. this._binormals = new Array();
  4476. for (var p = 0; p < path.length; p++) {
  4477. this._curve[p] = path[p].clone(); // hard copy
  4478. }
  4479. this._raw = raw || false;
  4480. this._compute(firstNormal);
  4481. }
  4482. /**
  4483. * Returns the Path3D array of successive Vector3 designing its curve.
  4484. */
  4485. Path3D.prototype.getCurve = function () {
  4486. return this._curve;
  4487. };
  4488. /**
  4489. * Returns an array populated with tangent vectors on each Path3D curve point.
  4490. */
  4491. Path3D.prototype.getTangents = function () {
  4492. return this._tangents;
  4493. };
  4494. /**
  4495. * Returns an array populated with normal vectors on each Path3D curve point.
  4496. */
  4497. Path3D.prototype.getNormals = function () {
  4498. return this._normals;
  4499. };
  4500. /**
  4501. * Returns an array populated with binormal vectors on each Path3D curve point.
  4502. */
  4503. Path3D.prototype.getBinormals = function () {
  4504. return this._binormals;
  4505. };
  4506. /**
  4507. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4508. */
  4509. Path3D.prototype.getDistances = function () {
  4510. return this._distances;
  4511. };
  4512. /**
  4513. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4514. * Returns the same object updated.
  4515. */
  4516. Path3D.prototype.update = function (path, firstNormal) {
  4517. for (var p = 0; p < path.length; p++) {
  4518. this._curve[p].x = path[p].x;
  4519. this._curve[p].y = path[p].y;
  4520. this._curve[p].z = path[p].z;
  4521. }
  4522. this._compute(firstNormal);
  4523. return this;
  4524. };
  4525. // private function compute() : computes tangents, normals and binormals
  4526. Path3D.prototype._compute = function (firstNormal) {
  4527. var l = this._curve.length;
  4528. // first and last tangents
  4529. this._tangents[0] = this._getFirstNonNullVector(0);
  4530. if (!this._raw) {
  4531. this._tangents[0].normalize();
  4532. }
  4533. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4534. if (!this._raw) {
  4535. this._tangents[l - 1].normalize();
  4536. }
  4537. // normals and binormals at first point : arbitrary vector with _normalVector()
  4538. var tg0 = this._tangents[0];
  4539. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4540. this._normals[0] = pp0;
  4541. if (!this._raw) {
  4542. this._normals[0].normalize();
  4543. }
  4544. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4545. if (!this._raw) {
  4546. this._binormals[0].normalize();
  4547. }
  4548. this._distances[0] = 0.0;
  4549. // normals and binormals : next points
  4550. var prev; // previous vector (segment)
  4551. var cur; // current vector (segment)
  4552. var curTang; // current tangent
  4553. // previous normal
  4554. var prevBinor; // previous binormal
  4555. for (var i = 1; i < l; i++) {
  4556. // tangents
  4557. prev = this._getLastNonNullVector(i);
  4558. if (i < l - 1) {
  4559. cur = this._getFirstNonNullVector(i);
  4560. this._tangents[i] = prev.add(cur);
  4561. this._tangents[i].normalize();
  4562. }
  4563. this._distances[i] = this._distances[i - 1] + prev.length();
  4564. // normals and binormals
  4565. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4566. curTang = this._tangents[i];
  4567. prevBinor = this._binormals[i - 1];
  4568. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4569. if (!this._raw) {
  4570. this._normals[i].normalize();
  4571. }
  4572. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4573. if (!this._raw) {
  4574. this._binormals[i].normalize();
  4575. }
  4576. }
  4577. };
  4578. // private function getFirstNonNullVector(index)
  4579. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4580. Path3D.prototype._getFirstNonNullVector = function (index) {
  4581. var i = 1;
  4582. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4583. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4584. i++;
  4585. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4586. }
  4587. return nNVector;
  4588. };
  4589. // private function getLastNonNullVector(index)
  4590. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4591. Path3D.prototype._getLastNonNullVector = function (index) {
  4592. var i = 1;
  4593. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4594. while (nLVector.length() === 0 && index > i + 1) {
  4595. i++;
  4596. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4597. }
  4598. return nLVector;
  4599. };
  4600. // private function normalVector(v0, vt, va) :
  4601. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4602. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4603. Path3D.prototype._normalVector = function (v0, vt, va) {
  4604. var normal0;
  4605. var tgl = vt.length();
  4606. if (tgl === 0.0) {
  4607. tgl = 1.0;
  4608. }
  4609. if (va === undefined || va === null) {
  4610. var point;
  4611. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4612. point = new Vector3(0.0, -1.0, 0.0);
  4613. }
  4614. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4615. point = new Vector3(1.0, 0.0, 0.0);
  4616. }
  4617. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4618. point = new Vector3(0.0, 0.0, 1.0);
  4619. }
  4620. normal0 = Vector3.Cross(vt, point);
  4621. }
  4622. else {
  4623. normal0 = Vector3.Cross(vt, va);
  4624. Vector3.CrossToRef(normal0, vt, normal0);
  4625. }
  4626. normal0.normalize();
  4627. return normal0;
  4628. };
  4629. return Path3D;
  4630. }());
  4631. BABYLON.Path3D = Path3D;
  4632. var Curve3 = (function () {
  4633. /**
  4634. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4635. * A Curve3 is designed from a series of successive Vector3.
  4636. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4637. */
  4638. function Curve3(points) {
  4639. this._length = 0.0;
  4640. this._points = points;
  4641. this._length = this._computeLength(points);
  4642. }
  4643. /**
  4644. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4645. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4646. * @param v1 (Vector3) the control point
  4647. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4648. * @param nbPoints (integer) the wanted number of points in the curve
  4649. */
  4650. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4651. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4652. var bez = new Array();
  4653. var equation = function (t, val0, val1, val2) {
  4654. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4655. return res;
  4656. };
  4657. for (var i = 0; i <= nbPoints; i++) {
  4658. 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)));
  4659. }
  4660. return new Curve3(bez);
  4661. };
  4662. /**
  4663. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4664. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4665. * @param v1 (Vector3) the first control point
  4666. * @param v2 (Vector3) the second control point
  4667. * @param v3 (Vector3) the end point of the Cubic Bezier
  4668. * @param nbPoints (integer) the wanted number of points in the curve
  4669. */
  4670. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4671. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4672. var bez = new Array();
  4673. var equation = function (t, val0, val1, val2, val3) {
  4674. 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;
  4675. return res;
  4676. };
  4677. for (var i = 0; i <= nbPoints; i++) {
  4678. 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)));
  4679. }
  4680. return new Curve3(bez);
  4681. };
  4682. /**
  4683. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4684. * @param p1 (Vector3) the origin point of the Hermite Spline
  4685. * @param t1 (Vector3) the tangent vector at the origin point
  4686. * @param p2 (Vector3) the end point of the Hermite Spline
  4687. * @param t2 (Vector3) the tangent vector at the end point
  4688. * @param nbPoints (integer) the wanted number of points in the curve
  4689. */
  4690. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4691. var hermite = new Array();
  4692. var step = 1.0 / nbPoints;
  4693. for (var i = 0; i <= nbPoints; i++) {
  4694. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4695. }
  4696. return new Curve3(hermite);
  4697. };
  4698. /**
  4699. * Returns a Curve3 object along a CatmullRom Spline curve :
  4700. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4701. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4702. */
  4703. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4704. var totalPoints = new Array();
  4705. totalPoints.push(points[0].clone());
  4706. Array.prototype.push.apply(totalPoints, points);
  4707. totalPoints.push(points[points.length - 1].clone());
  4708. var catmullRom = new Array();
  4709. var step = 1.0 / nbPoints;
  4710. for (var i = 0; i < totalPoints.length - 3; i++) {
  4711. var amount = 0.0;
  4712. for (var c = 0; c < nbPoints; c++) {
  4713. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4714. amount += step;
  4715. }
  4716. }
  4717. i--;
  4718. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4719. return new Curve3(catmullRom);
  4720. };
  4721. /**
  4722. * Returns the Curve3 stored array of successive Vector3
  4723. */
  4724. Curve3.prototype.getPoints = function () {
  4725. return this._points;
  4726. };
  4727. /**
  4728. * Returns the computed length (float) of the curve.
  4729. */
  4730. Curve3.prototype.length = function () {
  4731. return this._length;
  4732. };
  4733. /**
  4734. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4735. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4736. * curveA and curveB keep unchanged.
  4737. */
  4738. Curve3.prototype.continue = function (curve) {
  4739. var lastPoint = this._points[this._points.length - 1];
  4740. var continuedPoints = this._points.slice();
  4741. var curvePoints = curve.getPoints();
  4742. for (var i = 1; i < curvePoints.length; i++) {
  4743. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4744. }
  4745. var continuedCurve = new Curve3(continuedPoints);
  4746. return continuedCurve;
  4747. };
  4748. Curve3.prototype._computeLength = function (path) {
  4749. var l = 0;
  4750. for (var i = 1; i < path.length; i++) {
  4751. l += (path[i].subtract(path[i - 1])).length();
  4752. }
  4753. return l;
  4754. };
  4755. return Curve3;
  4756. }());
  4757. BABYLON.Curve3 = Curve3;
  4758. // Vertex formats
  4759. var PositionNormalVertex = (function () {
  4760. function PositionNormalVertex(position, normal) {
  4761. if (position === void 0) { position = Vector3.Zero(); }
  4762. if (normal === void 0) { normal = Vector3.Up(); }
  4763. this.position = position;
  4764. this.normal = normal;
  4765. }
  4766. PositionNormalVertex.prototype.clone = function () {
  4767. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4768. };
  4769. return PositionNormalVertex;
  4770. }());
  4771. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4772. var PositionNormalTextureVertex = (function () {
  4773. function PositionNormalTextureVertex(position, normal, uv) {
  4774. if (position === void 0) { position = Vector3.Zero(); }
  4775. if (normal === void 0) { normal = Vector3.Up(); }
  4776. if (uv === void 0) { uv = Vector2.Zero(); }
  4777. this.position = position;
  4778. this.normal = normal;
  4779. this.uv = uv;
  4780. }
  4781. PositionNormalTextureVertex.prototype.clone = function () {
  4782. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4783. };
  4784. return PositionNormalTextureVertex;
  4785. }());
  4786. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4787. // Temporary pre-allocated objects for engine internal use
  4788. // usage in any internal function :
  4789. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4790. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4791. var Tmp = (function () {
  4792. function Tmp() {
  4793. }
  4794. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4795. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4796. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4797. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4798. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4799. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4800. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4801. Matrix.Zero(), Matrix.Zero(),
  4802. Matrix.Zero(), Matrix.Zero(),
  4803. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4804. return Tmp;
  4805. }());
  4806. BABYLON.Tmp = Tmp;
  4807. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4808. var MathTmp = (function () {
  4809. function MathTmp() {
  4810. }
  4811. MathTmp.Vector3 = [Vector3.Zero()];
  4812. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4813. MathTmp.Quaternion = [Quaternion.Zero()];
  4814. return MathTmp;
  4815. }());
  4816. })(BABYLON || (BABYLON = {}));
  4817. //# sourceMappingURL=babylon.math.js.map
  4818. var BABYLON;
  4819. (function (BABYLON) {
  4820. var Scalar = (function () {
  4821. function Scalar() {
  4822. }
  4823. /**
  4824. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4825. */
  4826. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4827. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4828. var num = a - b;
  4829. return -epsilon <= num && num <= epsilon;
  4830. };
  4831. /**
  4832. * Returns a string : the upper case translation of the number i to hexadecimal.
  4833. */
  4834. Scalar.ToHex = function (i) {
  4835. var str = i.toString(16);
  4836. if (i <= 15) {
  4837. return ("0" + str).toUpperCase();
  4838. }
  4839. return str.toUpperCase();
  4840. };
  4841. /**
  4842. * Returns -1 if value is negative and +1 is value is positive.
  4843. * Returns the value itself if it's equal to zero.
  4844. */
  4845. Scalar.Sign = function (value) {
  4846. value = +value; // convert to a number
  4847. if (value === 0 || isNaN(value))
  4848. return value;
  4849. return value > 0 ? 1 : -1;
  4850. };
  4851. /**
  4852. * Returns the value itself if it's between min and max.
  4853. * Returns min if the value is lower than min.
  4854. * Returns max if the value is greater than max.
  4855. */
  4856. Scalar.Clamp = function (value, min, max) {
  4857. if (min === void 0) { min = 0; }
  4858. if (max === void 0) { max = 1; }
  4859. return Math.min(max, Math.max(min, value));
  4860. };
  4861. /**
  4862. * Returns the log2 of value.
  4863. */
  4864. Scalar.Log2 = function (value) {
  4865. return Math.log(value) * Math.LOG2E;
  4866. };
  4867. /**
  4868. * Loops the value, so that it is never larger than length and never smaller than 0.
  4869. *
  4870. * This is similar to the modulo operator but it works with floating point numbers.
  4871. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4872. * With t = 5 and length = 2.5, the result would be 0.0.
  4873. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4874. */
  4875. Scalar.Repeat = function (value, length) {
  4876. return value - Math.floor(value / length) * length;
  4877. };
  4878. /**
  4879. * Normalize the value between 0.0 and 1.0 using min and max values
  4880. */
  4881. Scalar.Normalize = function (value, min, max) {
  4882. return (value - min) / (max - min);
  4883. };
  4884. /**
  4885. * Denormalize the value from 0.0 and 1.0 using min and max values
  4886. */
  4887. Scalar.Denormalize = function (normalized, min, max) {
  4888. return (normalized * (max - min) + min);
  4889. };
  4890. /**
  4891. * Calculates the shortest difference between two given angles given in degrees.
  4892. */
  4893. Scalar.DeltaAngle = function (current, target) {
  4894. var num = Scalar.Repeat(target - current, 360.0);
  4895. if (num > 180.0) {
  4896. num -= 360.0;
  4897. }
  4898. return num;
  4899. };
  4900. /**
  4901. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4902. *
  4903. * The returned value will move back and forth between 0 and length
  4904. */
  4905. Scalar.PingPong = function (tx, length) {
  4906. var t = Scalar.Repeat(tx, length * 2.0);
  4907. return length - Math.abs(t - length);
  4908. };
  4909. /**
  4910. * Interpolates between min and max with smoothing at the limits.
  4911. *
  4912. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4913. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4914. */
  4915. Scalar.SmoothStep = function (from, to, tx) {
  4916. var t = Scalar.Clamp(tx);
  4917. t = -2.0 * t * t * t + 3.0 * t * t;
  4918. return to * t + from * (1.0 - t);
  4919. };
  4920. /**
  4921. * Moves a value current towards target.
  4922. *
  4923. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4924. * Negative values of maxDelta pushes the value away from target.
  4925. */
  4926. Scalar.MoveTowards = function (current, target, maxDelta) {
  4927. var result = 0;
  4928. if (Math.abs(target - current) <= maxDelta) {
  4929. result = target;
  4930. }
  4931. else {
  4932. result = current + Scalar.Sign(target - current) * maxDelta;
  4933. }
  4934. return result;
  4935. };
  4936. /**
  4937. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4938. *
  4939. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4940. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4941. */
  4942. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4943. var num = Scalar.DeltaAngle(current, target);
  4944. var result = 0;
  4945. if (-maxDelta < num && num < maxDelta) {
  4946. result = target;
  4947. }
  4948. else {
  4949. target = current + num;
  4950. result = Scalar.MoveTowards(current, target, maxDelta);
  4951. }
  4952. return result;
  4953. };
  4954. /**
  4955. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4956. */
  4957. Scalar.Lerp = function (start, end, amount) {
  4958. return start + ((end - start) * amount);
  4959. };
  4960. /**
  4961. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4962. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4963. */
  4964. Scalar.LerpAngle = function (start, end, amount) {
  4965. var num = Scalar.Repeat(end - start, 360.0);
  4966. if (num > 180.0) {
  4967. num -= 360.0;
  4968. }
  4969. return start + num * Scalar.Clamp(amount);
  4970. };
  4971. /**
  4972. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4973. */
  4974. Scalar.InverseLerp = function (a, b, value) {
  4975. var result = 0;
  4976. if (a != b) {
  4977. result = Scalar.Clamp((value - a) / (b - a));
  4978. }
  4979. else {
  4980. result = 0.0;
  4981. }
  4982. return result;
  4983. };
  4984. /**
  4985. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4986. */
  4987. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4988. var squared = amount * amount;
  4989. var cubed = amount * squared;
  4990. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4991. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4992. var part3 = (cubed - (2.0 * squared)) + amount;
  4993. var part4 = cubed - squared;
  4994. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4995. };
  4996. /**
  4997. * Returns a random float number between and min and max values
  4998. */
  4999. Scalar.RandomRange = function (min, max) {
  5000. if (min === max)
  5001. return min;
  5002. return ((Math.random() * (max - min)) + min);
  5003. };
  5004. /**
  5005. * This function returns percentage of a number in a given range.
  5006. *
  5007. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5008. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5009. */
  5010. Scalar.RangeToPercent = function (number, min, max) {
  5011. return ((number - min) / (max - min));
  5012. };
  5013. /**
  5014. * This function returns number that corresponds to the percentage in a given range.
  5015. *
  5016. * PercentToRange(0.34,0,100) will return 34.
  5017. */
  5018. Scalar.PercentToRange = function (percent, min, max) {
  5019. return ((max - min) * percent + min);
  5020. };
  5021. return Scalar;
  5022. }());
  5023. BABYLON.Scalar = Scalar;
  5024. })(BABYLON || (BABYLON = {}));
  5025. //# sourceMappingURL=babylon.math.scalar.js.map
  5026. //# sourceMappingURL=babylon.mixins.js.map
  5027. var BABYLON;
  5028. (function (BABYLON) {
  5029. var __decoratorInitialStore = {};
  5030. var __mergedStore = {};
  5031. var _copySource = function (creationFunction, source, instanciate) {
  5032. var destination = creationFunction();
  5033. // Tags
  5034. if (BABYLON.Tags) {
  5035. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5036. }
  5037. var classStore = getMergedStore(destination);
  5038. // Properties
  5039. for (var property in classStore) {
  5040. var propertyDescriptor = classStore[property];
  5041. var sourceProperty = source[property];
  5042. var propertyType = propertyDescriptor.type;
  5043. if (sourceProperty !== undefined && sourceProperty !== null) {
  5044. switch (propertyType) {
  5045. case 0: // Value
  5046. case 6:// Mesh reference
  5047. destination[property] = sourceProperty;
  5048. break;
  5049. case 1: // Texture
  5050. case 2: // Color3
  5051. case 3: // FresnelParameters
  5052. case 4: // Vector2
  5053. case 5: // Vector3
  5054. case 7:// Color Curves
  5055. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5056. break;
  5057. }
  5058. }
  5059. }
  5060. return destination;
  5061. };
  5062. function getDirectStore(target) {
  5063. var classKey = target.getClassName();
  5064. if (!__decoratorInitialStore[classKey]) {
  5065. __decoratorInitialStore[classKey] = {};
  5066. }
  5067. return __decoratorInitialStore[classKey];
  5068. }
  5069. /**
  5070. * Return the list of properties flagged as serializable
  5071. * @param target: host object
  5072. */
  5073. function getMergedStore(target) {
  5074. var classKey = target.getClassName();
  5075. if (__mergedStore[classKey]) {
  5076. return __mergedStore[classKey];
  5077. }
  5078. __mergedStore[classKey] = {};
  5079. var store = __mergedStore[classKey];
  5080. var currentTarget = target;
  5081. var currentKey = classKey;
  5082. while (currentKey) {
  5083. var initialStore = __decoratorInitialStore[currentKey];
  5084. for (var property in initialStore) {
  5085. store[property] = initialStore[property];
  5086. }
  5087. var parent_1 = void 0;
  5088. var done = false;
  5089. do {
  5090. parent_1 = Object.getPrototypeOf(currentTarget);
  5091. if (!parent_1.getClassName) {
  5092. done = true;
  5093. break;
  5094. }
  5095. if (parent_1.getClassName() !== currentKey) {
  5096. break;
  5097. }
  5098. currentTarget = parent_1;
  5099. } while (parent_1);
  5100. if (done) {
  5101. break;
  5102. }
  5103. currentKey = parent_1.getClassName();
  5104. currentTarget = parent_1;
  5105. }
  5106. return store;
  5107. }
  5108. function generateSerializableMember(type, sourceName) {
  5109. return function (target, propertyKey) {
  5110. var classStore = getDirectStore(target);
  5111. if (!classStore[propertyKey]) {
  5112. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5113. }
  5114. };
  5115. }
  5116. function generateExpandMember(setCallback, targetKey) {
  5117. return function (target, propertyKey) {
  5118. var key = targetKey || ("_" + propertyKey);
  5119. Object.defineProperty(target, propertyKey, {
  5120. get: function () {
  5121. return this[key];
  5122. },
  5123. set: function (value) {
  5124. if (this[key] === value) {
  5125. return;
  5126. }
  5127. this[key] = value;
  5128. target[setCallback].apply(this);
  5129. },
  5130. enumerable: true,
  5131. configurable: true
  5132. });
  5133. };
  5134. }
  5135. function expandToProperty(callback, targetKey) {
  5136. return generateExpandMember(callback, targetKey);
  5137. }
  5138. BABYLON.expandToProperty = expandToProperty;
  5139. function serialize(sourceName) {
  5140. return generateSerializableMember(0, sourceName); // value member
  5141. }
  5142. BABYLON.serialize = serialize;
  5143. function serializeAsTexture(sourceName) {
  5144. return generateSerializableMember(1, sourceName); // texture member
  5145. }
  5146. BABYLON.serializeAsTexture = serializeAsTexture;
  5147. function serializeAsColor3(sourceName) {
  5148. return generateSerializableMember(2, sourceName); // color3 member
  5149. }
  5150. BABYLON.serializeAsColor3 = serializeAsColor3;
  5151. function serializeAsFresnelParameters(sourceName) {
  5152. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5153. }
  5154. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5155. function serializeAsVector2(sourceName) {
  5156. return generateSerializableMember(4, sourceName); // vector2 member
  5157. }
  5158. BABYLON.serializeAsVector2 = serializeAsVector2;
  5159. function serializeAsVector3(sourceName) {
  5160. return generateSerializableMember(5, sourceName); // vector3 member
  5161. }
  5162. BABYLON.serializeAsVector3 = serializeAsVector3;
  5163. function serializeAsMeshReference(sourceName) {
  5164. return generateSerializableMember(6, sourceName); // mesh reference member
  5165. }
  5166. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5167. function serializeAsColorCurves(sourceName) {
  5168. return generateSerializableMember(7, sourceName); // color curves
  5169. }
  5170. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5171. function serializeAsColor4(sourceName) {
  5172. return generateSerializableMember(8, sourceName); // color 4
  5173. }
  5174. BABYLON.serializeAsColor4 = serializeAsColor4;
  5175. function serializeAsImageProcessingConfiguration(sourceName) {
  5176. return generateSerializableMember(9, sourceName); // image processing
  5177. }
  5178. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5179. var SerializationHelper = (function () {
  5180. function SerializationHelper() {
  5181. }
  5182. SerializationHelper.Serialize = function (entity, serializationObject) {
  5183. if (!serializationObject) {
  5184. serializationObject = {};
  5185. }
  5186. // Tags
  5187. if (BABYLON.Tags) {
  5188. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5189. }
  5190. var serializedProperties = getMergedStore(entity);
  5191. // Properties
  5192. for (var property in serializedProperties) {
  5193. var propertyDescriptor = serializedProperties[property];
  5194. var targetPropertyName = propertyDescriptor.sourceName || property;
  5195. var propertyType = propertyDescriptor.type;
  5196. var sourceProperty = entity[property];
  5197. if (sourceProperty !== undefined && sourceProperty !== null) {
  5198. switch (propertyType) {
  5199. case 0:// Value
  5200. serializationObject[targetPropertyName] = sourceProperty;
  5201. break;
  5202. case 1:// Texture
  5203. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5204. break;
  5205. case 2:// Color3
  5206. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5207. break;
  5208. case 3:// FresnelParameters
  5209. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5210. break;
  5211. case 4:// Vector2
  5212. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5213. break;
  5214. case 5:// Vector3
  5215. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5216. break;
  5217. case 6:// Mesh reference
  5218. serializationObject[targetPropertyName] = sourceProperty.id;
  5219. break;
  5220. case 7:// Color Curves
  5221. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5222. break;
  5223. case 8:// Color 4
  5224. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5225. break;
  5226. case 9:// Image Processing
  5227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5228. break;
  5229. }
  5230. }
  5231. }
  5232. return serializationObject;
  5233. };
  5234. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5235. var destination = creationFunction();
  5236. // Tags
  5237. if (BABYLON.Tags) {
  5238. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5239. }
  5240. var classStore = getMergedStore(destination);
  5241. // Properties
  5242. for (var property in classStore) {
  5243. var propertyDescriptor = classStore[property];
  5244. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5245. var propertyType = propertyDescriptor.type;
  5246. if (sourceProperty !== undefined && sourceProperty !== null) {
  5247. switch (propertyType) {
  5248. case 0:// Value
  5249. destination[property] = sourceProperty;
  5250. break;
  5251. case 1:// Texture
  5252. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5253. break;
  5254. case 2:// Color3
  5255. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5256. break;
  5257. case 3:// FresnelParameters
  5258. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5259. break;
  5260. case 4:// Vector2
  5261. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5262. break;
  5263. case 5:// Vector3
  5264. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5265. break;
  5266. case 6:// Mesh reference
  5267. destination[property] = scene.getLastMeshByID(sourceProperty);
  5268. break;
  5269. case 7:// Color Curves
  5270. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5271. break;
  5272. case 8:// Color 4
  5273. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5274. break;
  5275. case 9:// Image Processing
  5276. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5277. break;
  5278. }
  5279. }
  5280. }
  5281. return destination;
  5282. };
  5283. SerializationHelper.Clone = function (creationFunction, source) {
  5284. return _copySource(creationFunction, source, false);
  5285. };
  5286. SerializationHelper.Instanciate = function (creationFunction, source) {
  5287. return _copySource(creationFunction, source, true);
  5288. };
  5289. return SerializationHelper;
  5290. }());
  5291. BABYLON.SerializationHelper = SerializationHelper;
  5292. })(BABYLON || (BABYLON = {}));
  5293. //# sourceMappingURL=babylon.decorators.js.map
  5294. var BABYLON;
  5295. (function (BABYLON) {
  5296. /**
  5297. * A class serves as a medium between the observable and its observers
  5298. */
  5299. var EventState = (function () {
  5300. /**
  5301. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5302. */
  5303. function EventState(mask, skipNextObservers) {
  5304. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5305. this.initalize(mask, skipNextObservers);
  5306. }
  5307. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5308. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5309. this.mask = mask;
  5310. this.skipNextObservers = skipNextObservers;
  5311. return this;
  5312. };
  5313. return EventState;
  5314. }());
  5315. BABYLON.EventState = EventState;
  5316. /**
  5317. * Represent an Observer registered to a given Observable object.
  5318. */
  5319. var Observer = (function () {
  5320. function Observer(callback, mask) {
  5321. this.callback = callback;
  5322. this.mask = mask;
  5323. }
  5324. return Observer;
  5325. }());
  5326. BABYLON.Observer = Observer;
  5327. /**
  5328. * The Observable class is a simple implementation of the Observable pattern.
  5329. * 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.
  5330. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5331. * 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).
  5332. * 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.
  5333. */
  5334. var Observable = (function () {
  5335. function Observable() {
  5336. this._observers = new Array();
  5337. this._eventState = new EventState(0);
  5338. }
  5339. /**
  5340. * Create a new Observer with the specified callback
  5341. * @param callback the callback that will be executed for that Observer
  5342. * @param mask the mask used to filter observers
  5343. * @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.
  5344. */
  5345. Observable.prototype.add = function (callback, mask, insertFirst) {
  5346. if (mask === void 0) { mask = -1; }
  5347. if (insertFirst === void 0) { insertFirst = false; }
  5348. if (!callback) {
  5349. return null;
  5350. }
  5351. var observer = new Observer(callback, mask);
  5352. if (insertFirst) {
  5353. this._observers.unshift(observer);
  5354. }
  5355. else {
  5356. this._observers.push(observer);
  5357. }
  5358. return observer;
  5359. };
  5360. /**
  5361. * Remove an Observer from the Observable object
  5362. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5363. */
  5364. Observable.prototype.remove = function (observer) {
  5365. var index = this._observers.indexOf(observer);
  5366. if (index !== -1) {
  5367. this._observers.splice(index, 1);
  5368. return true;
  5369. }
  5370. return false;
  5371. };
  5372. /**
  5373. * Remove a callback from the Observable object
  5374. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5375. */
  5376. Observable.prototype.removeCallback = function (callback) {
  5377. for (var index = 0; index < this._observers.length; index++) {
  5378. if (this._observers[index].callback === callback) {
  5379. this._observers.splice(index, 1);
  5380. return true;
  5381. }
  5382. }
  5383. return false;
  5384. };
  5385. /**
  5386. * Notify all Observers by calling their respective callback with the given data
  5387. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5388. * @param eventData
  5389. * @param mask
  5390. */
  5391. Observable.prototype.notifyObservers = function (eventData, mask) {
  5392. if (mask === void 0) { mask = -1; }
  5393. var state = this._eventState;
  5394. state.mask = mask;
  5395. state.skipNextObservers = false;
  5396. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5397. var obs = _a[_i];
  5398. if (obs.mask & mask) {
  5399. obs.callback(eventData, state);
  5400. }
  5401. if (state.skipNextObservers) {
  5402. return false;
  5403. }
  5404. }
  5405. return true;
  5406. };
  5407. /**
  5408. * return true is the Observable has at least one Observer registered
  5409. */
  5410. Observable.prototype.hasObservers = function () {
  5411. return this._observers.length > 0;
  5412. };
  5413. /**
  5414. * Clear the list of observers
  5415. */
  5416. Observable.prototype.clear = function () {
  5417. this._observers = new Array();
  5418. };
  5419. /**
  5420. * Clone the current observable
  5421. */
  5422. Observable.prototype.clone = function () {
  5423. var result = new Observable();
  5424. result._observers = this._observers.slice(0);
  5425. return result;
  5426. };
  5427. /**
  5428. * Does this observable handles observer registered with a given mask
  5429. * @param {number} trigger - the mask to be tested
  5430. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5431. **/
  5432. Observable.prototype.hasSpecificMask = function (mask) {
  5433. if (mask === void 0) { mask = -1; }
  5434. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5435. var obs = _a[_i];
  5436. if (obs.mask & mask || obs.mask === mask) {
  5437. return true;
  5438. }
  5439. }
  5440. return false;
  5441. };
  5442. return Observable;
  5443. }());
  5444. BABYLON.Observable = Observable;
  5445. })(BABYLON || (BABYLON = {}));
  5446. //# sourceMappingURL=babylon.observable.js.map
  5447. var BABYLON;
  5448. (function (BABYLON) {
  5449. var SmartArray = (function () {
  5450. function SmartArray(capacity) {
  5451. this.length = 0;
  5452. this._duplicateId = 0;
  5453. this.data = new Array(capacity);
  5454. this._id = SmartArray._GlobalId++;
  5455. }
  5456. SmartArray.prototype.push = function (value) {
  5457. this.data[this.length++] = value;
  5458. if (this.length > this.data.length) {
  5459. this.data.length *= 2;
  5460. }
  5461. if (!value.__smartArrayFlags) {
  5462. value.__smartArrayFlags = {};
  5463. }
  5464. value.__smartArrayFlags[this._id] = this._duplicateId;
  5465. };
  5466. SmartArray.prototype.forEach = function (func) {
  5467. for (var index = 0; index < this.length; index++) {
  5468. func(this.data[index]);
  5469. }
  5470. };
  5471. SmartArray.prototype.pushNoDuplicate = function (value) {
  5472. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5473. return false;
  5474. }
  5475. this.push(value);
  5476. return true;
  5477. };
  5478. SmartArray.prototype.sort = function (compareFn) {
  5479. this.data.sort(compareFn);
  5480. };
  5481. SmartArray.prototype.reset = function () {
  5482. this.length = 0;
  5483. this._duplicateId++;
  5484. };
  5485. SmartArray.prototype.dispose = function () {
  5486. this.reset();
  5487. if (this.data) {
  5488. this.data.length = 0;
  5489. this.data = null;
  5490. }
  5491. };
  5492. SmartArray.prototype.concat = function (array) {
  5493. if (array.length === 0) {
  5494. return;
  5495. }
  5496. if (this.length + array.length > this.data.length) {
  5497. this.data.length = (this.length + array.length) * 2;
  5498. }
  5499. for (var index = 0; index < array.length; index++) {
  5500. this.data[this.length++] = (array.data || array)[index];
  5501. }
  5502. };
  5503. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5504. if (array.length === 0) {
  5505. return;
  5506. }
  5507. if (this.length + array.length > this.data.length) {
  5508. this.data.length = (this.length + array.length) * 2;
  5509. }
  5510. for (var index = 0; index < array.length; index++) {
  5511. var item = (array.data || array)[index];
  5512. this.pushNoDuplicate(item);
  5513. }
  5514. };
  5515. SmartArray.prototype.indexOf = function (value) {
  5516. var position = this.data.indexOf(value);
  5517. if (position >= this.length) {
  5518. return -1;
  5519. }
  5520. return position;
  5521. };
  5522. SmartArray.prototype.contains = function (value) {
  5523. return this.data.indexOf(value) !== -1;
  5524. };
  5525. // Statics
  5526. SmartArray._GlobalId = 0;
  5527. return SmartArray;
  5528. }());
  5529. BABYLON.SmartArray = SmartArray;
  5530. })(BABYLON || (BABYLON = {}));
  5531. //# sourceMappingURL=babylon.smartArray.js.map
  5532. var BABYLON;
  5533. (function (BABYLON) {
  5534. // Screenshots
  5535. var screenshotCanvas;
  5536. var cloneValue = function (source, destinationObject) {
  5537. if (!source)
  5538. return null;
  5539. if (source instanceof BABYLON.Mesh) {
  5540. return null;
  5541. }
  5542. if (source instanceof BABYLON.SubMesh) {
  5543. return source.clone(destinationObject);
  5544. }
  5545. else if (source.clone) {
  5546. return source.clone();
  5547. }
  5548. return null;
  5549. };
  5550. var Tools = (function () {
  5551. function Tools() {
  5552. }
  5553. ;
  5554. /**
  5555. * Interpolates between a and b via alpha
  5556. * @param a The lower value (returned when alpha = 0)
  5557. * @param b The upper value (returned when alpha = 1)
  5558. * @param alpha The interpolation-factor
  5559. * @return The mixed value
  5560. */
  5561. Tools.Mix = function (a, b, alpha) {
  5562. return a * (1 - alpha) + b * alpha;
  5563. };
  5564. Tools.Instantiate = function (className) {
  5565. var arr = className.split(".");
  5566. var fn = (window || this);
  5567. for (var i = 0, len = arr.length; i < len; i++) {
  5568. fn = fn[arr[i]];
  5569. }
  5570. if (typeof fn !== "function") {
  5571. return null;
  5572. }
  5573. return fn;
  5574. };
  5575. Tools.SetImmediate = function (action) {
  5576. if (window.setImmediate) {
  5577. window.setImmediate(action);
  5578. }
  5579. else {
  5580. setTimeout(action, 1);
  5581. }
  5582. };
  5583. Tools.IsExponentOfTwo = function (value) {
  5584. var count = 1;
  5585. do {
  5586. count *= 2;
  5587. } while (count < value);
  5588. return count === value;
  5589. };
  5590. /**
  5591. * Find the next highest power of two.
  5592. * @param x Number to start search from.
  5593. * @return Next highest power of two.
  5594. */
  5595. Tools.CeilingPOT = function (x) {
  5596. x--;
  5597. x |= x >> 1;
  5598. x |= x >> 2;
  5599. x |= x >> 4;
  5600. x |= x >> 8;
  5601. x |= x >> 16;
  5602. x++;
  5603. return x;
  5604. };
  5605. /**
  5606. * Find the next lowest power of two.
  5607. * @param x Number to start search from.
  5608. * @return Next lowest power of two.
  5609. */
  5610. Tools.FloorPOT = function (x) {
  5611. x = x | (x >> 1);
  5612. x = x | (x >> 2);
  5613. x = x | (x >> 4);
  5614. x = x | (x >> 8);
  5615. x = x | (x >> 16);
  5616. return x - (x >> 1);
  5617. };
  5618. /**
  5619. * Find the nearest power of two.
  5620. * @param x Number to start search from.
  5621. * @return Next nearest power of two.
  5622. */
  5623. Tools.NearestPOT = function (x) {
  5624. var c = Tools.CeilingPOT(x);
  5625. var f = Tools.FloorPOT(x);
  5626. return (c - x) > (x - f) ? f : c;
  5627. };
  5628. Tools.GetExponentOfTwo = function (value, max, mode) {
  5629. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5630. var pot;
  5631. switch (mode) {
  5632. case BABYLON.Engine.SCALEMODE_FLOOR:
  5633. pot = Tools.FloorPOT(value);
  5634. break;
  5635. case BABYLON.Engine.SCALEMODE_NEAREST:
  5636. pot = Tools.NearestPOT(value);
  5637. break;
  5638. case BABYLON.Engine.SCALEMODE_CEILING:
  5639. pot = Tools.CeilingPOT(value);
  5640. break;
  5641. }
  5642. return Math.min(pot, max);
  5643. };
  5644. Tools.GetFilename = function (path) {
  5645. var index = path.lastIndexOf("/");
  5646. if (index < 0)
  5647. return path;
  5648. return path.substring(index + 1);
  5649. };
  5650. Tools.GetDOMTextContent = function (element) {
  5651. var result = "";
  5652. var child = element.firstChild;
  5653. while (child) {
  5654. if (child.nodeType === 3) {
  5655. result += child.textContent;
  5656. }
  5657. child = child.nextSibling;
  5658. }
  5659. return result;
  5660. };
  5661. Tools.ToDegrees = function (angle) {
  5662. return angle * 180 / Math.PI;
  5663. };
  5664. Tools.ToRadians = function (angle) {
  5665. return angle * Math.PI / 180;
  5666. };
  5667. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5668. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5669. var output = "";
  5670. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5671. var i = 0;
  5672. var bytes = new Uint8Array(buffer);
  5673. while (i < bytes.length) {
  5674. chr1 = bytes[i++];
  5675. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5676. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5677. enc1 = chr1 >> 2;
  5678. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5679. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5680. enc4 = chr3 & 63;
  5681. if (isNaN(chr2)) {
  5682. enc3 = enc4 = 64;
  5683. }
  5684. else if (isNaN(chr3)) {
  5685. enc4 = 64;
  5686. }
  5687. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5688. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5689. }
  5690. return "data:image/png;base64," + output;
  5691. };
  5692. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5693. if (bias === void 0) { bias = null; }
  5694. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5695. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5696. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5697. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5698. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5699. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5700. }
  5701. if (bias) {
  5702. minimum.x -= minimum.x * bias.x + bias.y;
  5703. minimum.y -= minimum.y * bias.x + bias.y;
  5704. minimum.z -= minimum.z * bias.x + bias.y;
  5705. maximum.x += maximum.x * bias.x + bias.y;
  5706. maximum.y += maximum.y * bias.x + bias.y;
  5707. maximum.z += maximum.z * bias.x + bias.y;
  5708. }
  5709. return {
  5710. minimum: minimum,
  5711. maximum: maximum
  5712. };
  5713. };
  5714. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5715. if (bias === void 0) { bias = null; }
  5716. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5717. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5718. if (!stride) {
  5719. stride = 3;
  5720. }
  5721. for (var index = start; index < start + count; index++) {
  5722. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5723. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5724. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5725. }
  5726. if (bias) {
  5727. minimum.x -= minimum.x * bias.x + bias.y;
  5728. minimum.y -= minimum.y * bias.x + bias.y;
  5729. minimum.z -= minimum.z * bias.x + bias.y;
  5730. maximum.x += maximum.x * bias.x + bias.y;
  5731. maximum.y += maximum.y * bias.x + bias.y;
  5732. maximum.z += maximum.z * bias.x + bias.y;
  5733. }
  5734. return {
  5735. minimum: minimum,
  5736. maximum: maximum
  5737. };
  5738. };
  5739. Tools.Vector2ArrayFeeder = function (array) {
  5740. return function (index) {
  5741. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5742. var length = isFloatArray ? array.length / 2 : array.length;
  5743. if (index >= length) {
  5744. return null;
  5745. }
  5746. if (isFloatArray) {
  5747. var fa = array;
  5748. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5749. }
  5750. var a = array;
  5751. return a[index];
  5752. };
  5753. };
  5754. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5755. if (bias === void 0) { bias = null; }
  5756. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5757. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5758. var i = 0;
  5759. var cur = feeder(i++);
  5760. while (cur) {
  5761. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5762. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5763. cur = feeder(i++);
  5764. }
  5765. if (bias) {
  5766. minimum.x -= minimum.x * bias.x + bias.y;
  5767. minimum.y -= minimum.y * bias.x + bias.y;
  5768. maximum.x += maximum.x * bias.x + bias.y;
  5769. maximum.y += maximum.y * bias.x + bias.y;
  5770. }
  5771. return {
  5772. minimum: minimum,
  5773. maximum: maximum
  5774. };
  5775. };
  5776. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5777. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5778. return undefined;
  5779. return Array.isArray(obj) ? obj : [obj];
  5780. };
  5781. // Misc.
  5782. Tools.GetPointerPrefix = function () {
  5783. var eventPrefix = "pointer";
  5784. // Check if pointer events are supported
  5785. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5786. eventPrefix = "mouse";
  5787. }
  5788. return eventPrefix;
  5789. };
  5790. /**
  5791. * @param func - the function to be called
  5792. * @param requester - the object that will request the next frame. Falls back to window.
  5793. */
  5794. Tools.QueueNewFrame = function (func, requester) {
  5795. if (requester === void 0) { requester = window; }
  5796. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5797. /*if(requester.isPresenting) {
  5798. return;
  5799. } else*/ if (requester.requestAnimationFrame)
  5800. requester.requestAnimationFrame(func);
  5801. else if (requester.msRequestAnimationFrame)
  5802. requester.msRequestAnimationFrame(func);
  5803. else if (requester.webkitRequestAnimationFrame)
  5804. requester.webkitRequestAnimationFrame(func);
  5805. else if (requester.mozRequestAnimationFrame)
  5806. requester.mozRequestAnimationFrame(func);
  5807. else if (requester.oRequestAnimationFrame)
  5808. requester.oRequestAnimationFrame(func);
  5809. else {
  5810. window.setTimeout(func, 16);
  5811. }
  5812. };
  5813. Tools.RequestFullscreen = function (element) {
  5814. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5815. if (!requestFunction)
  5816. return;
  5817. requestFunction.call(element);
  5818. };
  5819. Tools.ExitFullscreen = function () {
  5820. if (document.exitFullscreen) {
  5821. document.exitFullscreen();
  5822. }
  5823. else if (document.mozCancelFullScreen) {
  5824. document.mozCancelFullScreen();
  5825. }
  5826. else if (document.webkitCancelFullScreen) {
  5827. document.webkitCancelFullScreen();
  5828. }
  5829. else if (document.msCancelFullScreen) {
  5830. document.msCancelFullScreen();
  5831. }
  5832. };
  5833. Tools.SetCorsBehavior = function (url, img) {
  5834. if (Tools.CorsBehavior) {
  5835. switch (typeof (Tools.CorsBehavior)) {
  5836. case "function":
  5837. var result = Tools.CorsBehavior(url);
  5838. if (result) {
  5839. img.crossOrigin = result;
  5840. }
  5841. break;
  5842. case "string":
  5843. default:
  5844. img.crossOrigin = Tools.CorsBehavior;
  5845. break;
  5846. }
  5847. }
  5848. };
  5849. // External files
  5850. Tools.CleanUrl = function (url) {
  5851. url = url.replace(/#/mg, "%23");
  5852. return url;
  5853. };
  5854. Tools.LoadImage = function (url, onload, onerror, database) {
  5855. if (url instanceof ArrayBuffer) {
  5856. url = Tools.EncodeArrayBufferTobase64(url);
  5857. }
  5858. url = Tools.CleanUrl(url);
  5859. url = Tools.PreprocessUrl(url);
  5860. var img = new Image();
  5861. if (url.substr(0, 5) !== "data:") {
  5862. Tools.SetCorsBehavior(url, img);
  5863. }
  5864. img.onload = function () {
  5865. onload(img);
  5866. };
  5867. img.onerror = function (err) {
  5868. Tools.Error("Error while trying to load image: " + url);
  5869. if (Tools.UseFallbackTexture) {
  5870. img.src = Tools.fallbackTexture;
  5871. onload(img);
  5872. }
  5873. else {
  5874. onerror();
  5875. }
  5876. };
  5877. var noIndexedDB = function () {
  5878. img.src = url;
  5879. };
  5880. var loadFromIndexedDB = function () {
  5881. database.loadImageFromDB(url, img);
  5882. };
  5883. //ANY database to do!
  5884. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5885. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5886. }
  5887. else {
  5888. if (url.indexOf("file:") !== 0) {
  5889. noIndexedDB();
  5890. }
  5891. else {
  5892. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5893. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5894. try {
  5895. var blobURL;
  5896. try {
  5897. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5898. }
  5899. catch (ex) {
  5900. // Chrome doesn't support oneTimeOnly parameter
  5901. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5902. }
  5903. img.src = blobURL;
  5904. }
  5905. catch (e) {
  5906. img.src = null;
  5907. }
  5908. }
  5909. else {
  5910. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5911. img.src = Tools.fallbackTexture;
  5912. }
  5913. }
  5914. }
  5915. return img;
  5916. };
  5917. //ANY
  5918. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5919. url = Tools.CleanUrl(url);
  5920. url = Tools.PreprocessUrl(url);
  5921. var noIndexedDB = function () {
  5922. var request = new XMLHttpRequest();
  5923. var loadUrl = Tools.BaseUrl + url;
  5924. request.open('GET', loadUrl, true);
  5925. if (useArrayBuffer) {
  5926. request.responseType = "arraybuffer";
  5927. }
  5928. request.onprogress = progressCallBack;
  5929. request.onreadystatechange = function () {
  5930. // In case of undefined state in some browsers.
  5931. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5932. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5933. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5934. callback(!useArrayBuffer ? request.responseText : request.response);
  5935. }
  5936. else {
  5937. if (onError) {
  5938. onError(request);
  5939. }
  5940. else {
  5941. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5942. }
  5943. }
  5944. }
  5945. };
  5946. request.send(null);
  5947. };
  5948. var loadFromIndexedDB = function () {
  5949. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5950. };
  5951. if (url.indexOf("file:") !== -1) {
  5952. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5953. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5954. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5955. }
  5956. else {
  5957. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5958. }
  5959. }
  5960. else {
  5961. // Caching all files
  5962. if (database && database.enableSceneOffline) {
  5963. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5964. }
  5965. else {
  5966. noIndexedDB();
  5967. }
  5968. }
  5969. };
  5970. /**
  5971. * Load a script (identified by an url). When the url returns, the
  5972. * content of this file is added into a new script element, attached to the DOM (body element)
  5973. */
  5974. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5975. var head = document.getElementsByTagName('head')[0];
  5976. var script = document.createElement('script');
  5977. script.type = 'text/javascript';
  5978. script.src = scriptUrl;
  5979. var self = this;
  5980. script.onload = function () {
  5981. if (onSuccess) {
  5982. onSuccess();
  5983. }
  5984. };
  5985. script.onerror = function () {
  5986. if (onError) {
  5987. onError();
  5988. }
  5989. };
  5990. head.appendChild(script);
  5991. };
  5992. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5993. var reader = new FileReader();
  5994. reader.onload = function (e) {
  5995. //target doesn't have result from ts 1.3
  5996. callback(e.target['result']);
  5997. };
  5998. reader.onprogress = progressCallback;
  5999. reader.readAsDataURL(fileToLoad);
  6000. };
  6001. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6002. var reader = new FileReader();
  6003. reader.onerror = function (e) {
  6004. Tools.Log("Error while reading file: " + fileToLoad.name);
  6005. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6006. };
  6007. reader.onload = function (e) {
  6008. //target doesn't have result from ts 1.3
  6009. callback(e.target['result']);
  6010. };
  6011. reader.onprogress = progressCallBack;
  6012. if (!useArrayBuffer) {
  6013. // Asynchronous read
  6014. reader.readAsText(fileToLoad);
  6015. }
  6016. else {
  6017. reader.readAsArrayBuffer(fileToLoad);
  6018. }
  6019. };
  6020. //returns a downloadable url to a file content.
  6021. Tools.FileAsURL = function (content) {
  6022. var fileBlob = new Blob([content]);
  6023. var url = window.URL || window.webkitURL;
  6024. var link = url.createObjectURL(fileBlob);
  6025. return link;
  6026. };
  6027. // Misc.
  6028. Tools.Format = function (value, decimals) {
  6029. if (decimals === void 0) { decimals = 2; }
  6030. return value.toFixed(decimals);
  6031. };
  6032. Tools.CheckExtends = function (v, min, max) {
  6033. if (v.x < min.x)
  6034. min.x = v.x;
  6035. if (v.y < min.y)
  6036. min.y = v.y;
  6037. if (v.z < min.z)
  6038. min.z = v.z;
  6039. if (v.x > max.x)
  6040. max.x = v.x;
  6041. if (v.y > max.y)
  6042. max.y = v.y;
  6043. if (v.z > max.z)
  6044. max.z = v.z;
  6045. };
  6046. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6047. for (var prop in source) {
  6048. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6049. continue;
  6050. }
  6051. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6052. continue;
  6053. }
  6054. var sourceValue = source[prop];
  6055. var typeOfSourceValue = typeof sourceValue;
  6056. if (typeOfSourceValue === "function") {
  6057. continue;
  6058. }
  6059. if (typeOfSourceValue === "object") {
  6060. if (sourceValue instanceof Array) {
  6061. destination[prop] = [];
  6062. if (sourceValue.length > 0) {
  6063. if (typeof sourceValue[0] == "object") {
  6064. for (var index = 0; index < sourceValue.length; index++) {
  6065. var clonedValue = cloneValue(sourceValue[index], destination);
  6066. if (destination[prop].indexOf(clonedValue) === -1) {
  6067. destination[prop].push(clonedValue);
  6068. }
  6069. }
  6070. }
  6071. else {
  6072. destination[prop] = sourceValue.slice(0);
  6073. }
  6074. }
  6075. }
  6076. else {
  6077. destination[prop] = cloneValue(sourceValue, destination);
  6078. }
  6079. }
  6080. else {
  6081. destination[prop] = sourceValue;
  6082. }
  6083. }
  6084. };
  6085. Tools.IsEmpty = function (obj) {
  6086. for (var i in obj) {
  6087. return false;
  6088. }
  6089. return true;
  6090. };
  6091. Tools.RegisterTopRootEvents = function (events) {
  6092. for (var index = 0; index < events.length; index++) {
  6093. var event = events[index];
  6094. window.addEventListener(event.name, event.handler, false);
  6095. try {
  6096. if (window.parent) {
  6097. window.parent.addEventListener(event.name, event.handler, false);
  6098. }
  6099. }
  6100. catch (e) {
  6101. // Silently fails...
  6102. }
  6103. }
  6104. };
  6105. Tools.UnregisterTopRootEvents = function (events) {
  6106. for (var index = 0; index < events.length; index++) {
  6107. var event = events[index];
  6108. window.removeEventListener(event.name, event.handler);
  6109. try {
  6110. if (window.parent) {
  6111. window.parent.removeEventListener(event.name, event.handler);
  6112. }
  6113. }
  6114. catch (e) {
  6115. // Silently fails...
  6116. }
  6117. }
  6118. };
  6119. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6120. if (mimeType === void 0) { mimeType = "image/png"; }
  6121. // Read the contents of the framebuffer
  6122. var numberOfChannelsByLine = width * 4;
  6123. var halfHeight = height / 2;
  6124. //Reading datas from WebGL
  6125. var data = engine.readPixels(0, 0, width, height);
  6126. //To flip image on Y axis.
  6127. for (var i = 0; i < halfHeight; i++) {
  6128. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6129. var currentCell = j + i * numberOfChannelsByLine;
  6130. var targetLine = height - i - 1;
  6131. var targetCell = j + targetLine * numberOfChannelsByLine;
  6132. var temp = data[currentCell];
  6133. data[currentCell] = data[targetCell];
  6134. data[targetCell] = temp;
  6135. }
  6136. }
  6137. // Create a 2D canvas to store the result
  6138. if (!screenshotCanvas) {
  6139. screenshotCanvas = document.createElement('canvas');
  6140. }
  6141. screenshotCanvas.width = width;
  6142. screenshotCanvas.height = height;
  6143. var context = screenshotCanvas.getContext('2d');
  6144. // Copy the pixels to a 2D canvas
  6145. var imageData = context.createImageData(width, height);
  6146. var castData = (imageData.data);
  6147. castData.set(data);
  6148. context.putImageData(imageData, 0, 0);
  6149. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6150. };
  6151. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6152. if (mimeType === void 0) { mimeType = "image/png"; }
  6153. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6154. if (successCallback) {
  6155. successCallback(base64Image);
  6156. }
  6157. else {
  6158. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6159. if (("download" in document.createElement("a"))) {
  6160. var a = window.document.createElement("a");
  6161. a.href = base64Image;
  6162. var date = new Date();
  6163. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6164. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6165. window.document.body.appendChild(a);
  6166. a.addEventListener("click", function () {
  6167. a.parentElement.removeChild(a);
  6168. });
  6169. a.click();
  6170. //Or opening a new tab with the image if it is not possible to automatically start download.
  6171. }
  6172. else {
  6173. var newWindow = window.open("");
  6174. var img = newWindow.document.createElement("img");
  6175. img.src = base64Image;
  6176. newWindow.document.body.appendChild(img);
  6177. }
  6178. }
  6179. };
  6180. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6181. if (mimeType === void 0) { mimeType = "image/png"; }
  6182. var width;
  6183. var height;
  6184. // If a precision value is specified
  6185. if (size.precision) {
  6186. width = Math.round(engine.getRenderWidth() * size.precision);
  6187. height = Math.round(width / engine.getAspectRatio(camera));
  6188. }
  6189. else if (size.width && size.height) {
  6190. width = size.width;
  6191. height = size.height;
  6192. }
  6193. else if (size.width && !size.height) {
  6194. width = size.width;
  6195. height = Math.round(width / engine.getAspectRatio(camera));
  6196. }
  6197. else if (size.height && !size.width) {
  6198. height = size.height;
  6199. width = Math.round(height * engine.getAspectRatio(camera));
  6200. }
  6201. else if (!isNaN(size)) {
  6202. height = size;
  6203. width = size;
  6204. }
  6205. else {
  6206. Tools.Error("Invalid 'size' parameter !");
  6207. return;
  6208. }
  6209. if (!screenshotCanvas) {
  6210. screenshotCanvas = document.createElement('canvas');
  6211. }
  6212. screenshotCanvas.width = width;
  6213. screenshotCanvas.height = height;
  6214. var renderContext = screenshotCanvas.getContext("2d");
  6215. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6216. var newWidth = width;
  6217. var newHeight = newWidth / ratio;
  6218. if (newHeight > height) {
  6219. newHeight = height;
  6220. newWidth = newHeight * ratio;
  6221. }
  6222. var offsetX = Math.max(0, width - newWidth) / 2;
  6223. var offsetY = Math.max(0, height - newHeight) / 2;
  6224. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6225. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6226. };
  6227. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6228. if (mimeType === void 0) { mimeType = "image/png"; }
  6229. if (samples === void 0) { samples = 1; }
  6230. var width;
  6231. var height;
  6232. //If a precision value is specified
  6233. if (size.precision) {
  6234. width = Math.round(engine.getRenderWidth() * size.precision);
  6235. height = Math.round(width / engine.getAspectRatio(camera));
  6236. size = { width: width, height: height };
  6237. }
  6238. else if (size.width && size.height) {
  6239. width = size.width;
  6240. height = size.height;
  6241. }
  6242. else if (size.width && !size.height) {
  6243. width = size.width;
  6244. height = Math.round(width / engine.getAspectRatio(camera));
  6245. size = { width: width, height: height };
  6246. }
  6247. else if (size.height && !size.width) {
  6248. height = size.height;
  6249. width = Math.round(height * engine.getAspectRatio(camera));
  6250. size = { width: width, height: height };
  6251. }
  6252. else if (!isNaN(size)) {
  6253. height = size;
  6254. width = size;
  6255. }
  6256. else {
  6257. Tools.Error("Invalid 'size' parameter !");
  6258. return;
  6259. }
  6260. var scene = camera.getScene();
  6261. var previousCamera = null;
  6262. if (scene.activeCamera !== camera) {
  6263. previousCamera = scene.activeCamera;
  6264. scene.activeCamera = camera;
  6265. }
  6266. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6267. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6268. texture.renderList = null;
  6269. texture.samples = samples;
  6270. texture.onAfterRenderObservable.add(function () {
  6271. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6272. });
  6273. scene.incrementRenderId();
  6274. scene.resetCachedMaterial();
  6275. texture.render(true);
  6276. texture.dispose();
  6277. if (previousCamera) {
  6278. scene.activeCamera = previousCamera;
  6279. }
  6280. camera.getProjectionMatrix(true); // Force cache refresh;
  6281. };
  6282. // XHR response validator for local file scenario
  6283. Tools.ValidateXHRData = function (xhr, dataType) {
  6284. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6285. if (dataType === void 0) { dataType = 7; }
  6286. try {
  6287. if (dataType & 1) {
  6288. if (xhr.responseText && xhr.responseText.length > 0) {
  6289. return true;
  6290. }
  6291. else if (dataType === 1) {
  6292. return false;
  6293. }
  6294. }
  6295. if (dataType & 2) {
  6296. // Check header width and height since there is no "TGA" magic number
  6297. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6298. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6299. return true;
  6300. }
  6301. else if (dataType === 2) {
  6302. return false;
  6303. }
  6304. }
  6305. if (dataType & 4) {
  6306. // Check for the "DDS" magic number
  6307. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6308. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6309. return true;
  6310. }
  6311. else {
  6312. return false;
  6313. }
  6314. }
  6315. }
  6316. catch (e) {
  6317. // Global protection
  6318. }
  6319. return false;
  6320. };
  6321. /**
  6322. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6323. * Be aware Math.random() could cause collisions, but:
  6324. * "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"
  6325. */
  6326. Tools.RandomId = function () {
  6327. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6328. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6329. return v.toString(16);
  6330. });
  6331. };
  6332. Object.defineProperty(Tools, "NoneLogLevel", {
  6333. get: function () {
  6334. return Tools._NoneLogLevel;
  6335. },
  6336. enumerable: true,
  6337. configurable: true
  6338. });
  6339. Object.defineProperty(Tools, "MessageLogLevel", {
  6340. get: function () {
  6341. return Tools._MessageLogLevel;
  6342. },
  6343. enumerable: true,
  6344. configurable: true
  6345. });
  6346. Object.defineProperty(Tools, "WarningLogLevel", {
  6347. get: function () {
  6348. return Tools._WarningLogLevel;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(Tools, "ErrorLogLevel", {
  6354. get: function () {
  6355. return Tools._ErrorLogLevel;
  6356. },
  6357. enumerable: true,
  6358. configurable: true
  6359. });
  6360. Object.defineProperty(Tools, "AllLogLevel", {
  6361. get: function () {
  6362. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6363. },
  6364. enumerable: true,
  6365. configurable: true
  6366. });
  6367. Tools._AddLogEntry = function (entry) {
  6368. Tools._LogCache = entry + Tools._LogCache;
  6369. if (Tools.OnNewCacheEntry) {
  6370. Tools.OnNewCacheEntry(entry);
  6371. }
  6372. };
  6373. Tools._FormatMessage = function (message) {
  6374. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6375. var date = new Date();
  6376. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6377. };
  6378. Tools._LogDisabled = function (message) {
  6379. // nothing to do
  6380. };
  6381. Tools._LogEnabled = function (message) {
  6382. var formattedMessage = Tools._FormatMessage(message);
  6383. console.log("BJS - " + formattedMessage);
  6384. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6385. Tools._AddLogEntry(entry);
  6386. };
  6387. Tools._WarnDisabled = function (message) {
  6388. // nothing to do
  6389. };
  6390. Tools._WarnEnabled = function (message) {
  6391. var formattedMessage = Tools._FormatMessage(message);
  6392. console.warn("BJS - " + formattedMessage);
  6393. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6394. Tools._AddLogEntry(entry);
  6395. };
  6396. Tools._ErrorDisabled = function (message) {
  6397. // nothing to do
  6398. };
  6399. Tools._ErrorEnabled = function (message) {
  6400. Tools.errorsCount++;
  6401. var formattedMessage = Tools._FormatMessage(message);
  6402. console.error("BJS - " + formattedMessage);
  6403. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6404. Tools._AddLogEntry(entry);
  6405. };
  6406. Object.defineProperty(Tools, "LogCache", {
  6407. get: function () {
  6408. return Tools._LogCache;
  6409. },
  6410. enumerable: true,
  6411. configurable: true
  6412. });
  6413. Tools.ClearLogCache = function () {
  6414. Tools._LogCache = "";
  6415. Tools.errorsCount = 0;
  6416. };
  6417. Object.defineProperty(Tools, "LogLevels", {
  6418. set: function (level) {
  6419. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6420. Tools.Log = Tools._LogEnabled;
  6421. }
  6422. else {
  6423. Tools.Log = Tools._LogDisabled;
  6424. }
  6425. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6426. Tools.Warn = Tools._WarnEnabled;
  6427. }
  6428. else {
  6429. Tools.Warn = Tools._WarnDisabled;
  6430. }
  6431. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6432. Tools.Error = Tools._ErrorEnabled;
  6433. }
  6434. else {
  6435. Tools.Error = Tools._ErrorDisabled;
  6436. }
  6437. },
  6438. enumerable: true,
  6439. configurable: true
  6440. });
  6441. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6442. get: function () {
  6443. return Tools._PerformanceNoneLogLevel;
  6444. },
  6445. enumerable: true,
  6446. configurable: true
  6447. });
  6448. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6449. get: function () {
  6450. return Tools._PerformanceUserMarkLogLevel;
  6451. },
  6452. enumerable: true,
  6453. configurable: true
  6454. });
  6455. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6456. get: function () {
  6457. return Tools._PerformanceConsoleLogLevel;
  6458. },
  6459. enumerable: true,
  6460. configurable: true
  6461. });
  6462. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6463. set: function (level) {
  6464. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6465. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6466. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6467. return;
  6468. }
  6469. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6470. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6471. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6472. return;
  6473. }
  6474. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6475. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6476. },
  6477. enumerable: true,
  6478. configurable: true
  6479. });
  6480. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6481. };
  6482. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6483. };
  6484. Tools._StartUserMark = function (counterName, condition) {
  6485. if (condition === void 0) { condition = true; }
  6486. if (!condition || !Tools._performance.mark) {
  6487. return;
  6488. }
  6489. Tools._performance.mark(counterName + "-Begin");
  6490. };
  6491. Tools._EndUserMark = function (counterName, condition) {
  6492. if (condition === void 0) { condition = true; }
  6493. if (!condition || !Tools._performance.mark) {
  6494. return;
  6495. }
  6496. Tools._performance.mark(counterName + "-End");
  6497. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6498. };
  6499. Tools._StartPerformanceConsole = function (counterName, condition) {
  6500. if (condition === void 0) { condition = true; }
  6501. if (!condition) {
  6502. return;
  6503. }
  6504. Tools._StartUserMark(counterName, condition);
  6505. if (console.time) {
  6506. console.time(counterName);
  6507. }
  6508. };
  6509. Tools._EndPerformanceConsole = function (counterName, condition) {
  6510. if (condition === void 0) { condition = true; }
  6511. if (!condition) {
  6512. return;
  6513. }
  6514. Tools._EndUserMark(counterName, condition);
  6515. if (console.time) {
  6516. console.timeEnd(counterName);
  6517. }
  6518. };
  6519. Object.defineProperty(Tools, "Now", {
  6520. get: function () {
  6521. if (window.performance && window.performance.now) {
  6522. return window.performance.now();
  6523. }
  6524. return new Date().getTime();
  6525. },
  6526. enumerable: true,
  6527. configurable: true
  6528. });
  6529. /**
  6530. * This method will return the name of the class used to create the instance of the given object.
  6531. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6532. * @param object the object to get the class name from
  6533. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6534. */
  6535. Tools.GetClassName = function (object, isType) {
  6536. if (isType === void 0) { isType = false; }
  6537. var name = null;
  6538. if (!isType && object.getClassName) {
  6539. name = object.getClassName();
  6540. }
  6541. else {
  6542. if (object instanceof Object) {
  6543. var classObj = isType ? object : Object.getPrototypeOf(object);
  6544. name = classObj.constructor["__bjsclassName__"];
  6545. }
  6546. if (!name) {
  6547. name = typeof object;
  6548. }
  6549. }
  6550. return name;
  6551. };
  6552. Tools.first = function (array, predicate) {
  6553. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6554. var el = array_1[_i];
  6555. if (predicate(el)) {
  6556. return el;
  6557. }
  6558. }
  6559. };
  6560. /**
  6561. * This method will return the name of the full name of the class, including its owning module (if any).
  6562. * 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).
  6563. * @param object the object to get the class name from
  6564. * @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.
  6565. */
  6566. Tools.getFullClassName = function (object, isType) {
  6567. if (isType === void 0) { isType = false; }
  6568. var className = null;
  6569. var moduleName = null;
  6570. if (!isType && object.getClassName) {
  6571. className = object.getClassName();
  6572. }
  6573. else {
  6574. if (object instanceof Object) {
  6575. var classObj = isType ? object : Object.getPrototypeOf(object);
  6576. className = classObj.constructor["__bjsclassName__"];
  6577. moduleName = classObj.constructor["__bjsmoduleName__"];
  6578. }
  6579. if (!className) {
  6580. className = typeof object;
  6581. }
  6582. }
  6583. if (!className) {
  6584. return null;
  6585. }
  6586. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6587. };
  6588. /**
  6589. * 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.
  6590. * @param array
  6591. */
  6592. Tools.arrayOrStringFeeder = function (array) {
  6593. return function (index) {
  6594. if (index >= array.length) {
  6595. return null;
  6596. }
  6597. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6598. if (val && val.getHashCode) {
  6599. val = val.getHashCode();
  6600. }
  6601. if (typeof val === "string") {
  6602. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6603. }
  6604. return val;
  6605. };
  6606. };
  6607. /**
  6608. * Compute the hashCode of a stream of number
  6609. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6610. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6611. * @return the hash code computed
  6612. */
  6613. Tools.hashCodeFromStream = function (feeder) {
  6614. // Based from here: http://stackoverflow.com/a/7616484/802124
  6615. var hash = 0;
  6616. var index = 0;
  6617. var chr = feeder(index++);
  6618. while (chr != null) {
  6619. hash = ((hash << 5) - hash) + chr;
  6620. hash |= 0; // Convert to 32bit integer
  6621. chr = feeder(index++);
  6622. }
  6623. return hash;
  6624. };
  6625. Tools.BaseUrl = "";
  6626. Tools.CorsBehavior = "anonymous";
  6627. Tools.UseFallbackTexture = true;
  6628. // Used in case of a texture loading problem
  6629. 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";
  6630. Tools.PreprocessUrl = function (url) {
  6631. return url;
  6632. };
  6633. // Logs
  6634. Tools._NoneLogLevel = 0;
  6635. Tools._MessageLogLevel = 1;
  6636. Tools._WarningLogLevel = 2;
  6637. Tools._ErrorLogLevel = 4;
  6638. Tools._LogCache = "";
  6639. Tools.errorsCount = 0;
  6640. Tools.Log = Tools._LogEnabled;
  6641. Tools.Warn = Tools._WarnEnabled;
  6642. Tools.Error = Tools._ErrorEnabled;
  6643. // Performances
  6644. Tools._PerformanceNoneLogLevel = 0;
  6645. Tools._PerformanceUserMarkLogLevel = 1;
  6646. Tools._PerformanceConsoleLogLevel = 2;
  6647. Tools._performance = window.performance;
  6648. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6649. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6650. return Tools;
  6651. }());
  6652. BABYLON.Tools = Tools;
  6653. /**
  6654. * This class is used to track a performance counter which is number based.
  6655. * The user has access to many properties which give statistics of different nature
  6656. *
  6657. * The implementer can track two kinds of Performance Counter: time and count
  6658. * 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.
  6659. * 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.
  6660. */
  6661. var PerfCounter = (function () {
  6662. function PerfCounter() {
  6663. this._startMonitoringTime = 0;
  6664. this._min = 0;
  6665. this._max = 0;
  6666. this._average = 0;
  6667. this._lastSecAverage = 0;
  6668. this._current = 0;
  6669. this._totalValueCount = 0;
  6670. this._totalAccumulated = 0;
  6671. this._lastSecAccumulated = 0;
  6672. this._lastSecTime = 0;
  6673. this._lastSecValueCount = 0;
  6674. }
  6675. Object.defineProperty(PerfCounter.prototype, "min", {
  6676. /**
  6677. * Returns the smallest value ever
  6678. */
  6679. get: function () {
  6680. return this._min;
  6681. },
  6682. enumerable: true,
  6683. configurable: true
  6684. });
  6685. Object.defineProperty(PerfCounter.prototype, "max", {
  6686. /**
  6687. * Returns the biggest value ever
  6688. */
  6689. get: function () {
  6690. return this._max;
  6691. },
  6692. enumerable: true,
  6693. configurable: true
  6694. });
  6695. Object.defineProperty(PerfCounter.prototype, "average", {
  6696. /**
  6697. * Returns the average value since the performance counter is running
  6698. */
  6699. get: function () {
  6700. return this._average;
  6701. },
  6702. enumerable: true,
  6703. configurable: true
  6704. });
  6705. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6706. /**
  6707. * Returns the average value of the last second the counter was monitored
  6708. */
  6709. get: function () {
  6710. return this._lastSecAverage;
  6711. },
  6712. enumerable: true,
  6713. configurable: true
  6714. });
  6715. Object.defineProperty(PerfCounter.prototype, "current", {
  6716. /**
  6717. * Returns the current value
  6718. */
  6719. get: function () {
  6720. return this._current;
  6721. },
  6722. enumerable: true,
  6723. configurable: true
  6724. });
  6725. Object.defineProperty(PerfCounter.prototype, "total", {
  6726. get: function () {
  6727. return this._totalAccumulated;
  6728. },
  6729. enumerable: true,
  6730. configurable: true
  6731. });
  6732. /**
  6733. * Call this method to start monitoring a new frame.
  6734. * 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.
  6735. */
  6736. PerfCounter.prototype.fetchNewFrame = function () {
  6737. this._totalValueCount++;
  6738. this._current = 0;
  6739. this._lastSecValueCount++;
  6740. };
  6741. /**
  6742. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6743. * @param newCount the count value to add to the monitored count
  6744. * @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.
  6745. */
  6746. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6747. if (!PerfCounter.Enabled) {
  6748. return;
  6749. }
  6750. this._current += newCount;
  6751. if (fetchResult) {
  6752. this._fetchResult();
  6753. }
  6754. };
  6755. /**
  6756. * Start monitoring this performance counter
  6757. */
  6758. PerfCounter.prototype.beginMonitoring = function () {
  6759. if (!PerfCounter.Enabled) {
  6760. return;
  6761. }
  6762. this._startMonitoringTime = Tools.Now;
  6763. };
  6764. /**
  6765. * Compute the time lapsed since the previous beginMonitoring() call.
  6766. * @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
  6767. */
  6768. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6769. if (newFrame === void 0) { newFrame = true; }
  6770. if (!PerfCounter.Enabled) {
  6771. return;
  6772. }
  6773. if (newFrame) {
  6774. this.fetchNewFrame();
  6775. }
  6776. var currentTime = Tools.Now;
  6777. this._current = currentTime - this._startMonitoringTime;
  6778. if (newFrame) {
  6779. this._fetchResult();
  6780. }
  6781. };
  6782. PerfCounter.prototype._fetchResult = function () {
  6783. this._totalAccumulated += this._current;
  6784. this._lastSecAccumulated += this._current;
  6785. // Min/Max update
  6786. this._min = Math.min(this._min, this._current);
  6787. this._max = Math.max(this._max, this._current);
  6788. this._average = this._totalAccumulated / this._totalValueCount;
  6789. // Reset last sec?
  6790. var now = Tools.Now;
  6791. if ((now - this._lastSecTime) > 1000) {
  6792. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6793. this._lastSecTime = now;
  6794. this._lastSecAccumulated = 0;
  6795. this._lastSecValueCount = 0;
  6796. }
  6797. };
  6798. PerfCounter.Enabled = true;
  6799. return PerfCounter;
  6800. }());
  6801. BABYLON.PerfCounter = PerfCounter;
  6802. /**
  6803. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6804. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6805. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6806. * @param name The name of the class, case should be preserved
  6807. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6808. */
  6809. function className(name, module) {
  6810. return function (target) {
  6811. target["__bjsclassName__"] = name;
  6812. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6813. };
  6814. }
  6815. BABYLON.className = className;
  6816. /**
  6817. * An implementation of a loop for asynchronous functions.
  6818. */
  6819. var AsyncLoop = (function () {
  6820. /**
  6821. * Constroctor.
  6822. * @param iterations the number of iterations.
  6823. * @param _fn the function to run each iteration
  6824. * @param _successCallback the callback that will be called upon succesful execution
  6825. * @param offset starting offset.
  6826. */
  6827. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6828. if (offset === void 0) { offset = 0; }
  6829. this.iterations = iterations;
  6830. this._fn = _fn;
  6831. this._successCallback = _successCallback;
  6832. this.index = offset - 1;
  6833. this._done = false;
  6834. }
  6835. /**
  6836. * Execute the next iteration. Must be called after the last iteration was finished.
  6837. */
  6838. AsyncLoop.prototype.executeNext = function () {
  6839. if (!this._done) {
  6840. if (this.index + 1 < this.iterations) {
  6841. ++this.index;
  6842. this._fn(this);
  6843. }
  6844. else {
  6845. this.breakLoop();
  6846. }
  6847. }
  6848. };
  6849. /**
  6850. * Break the loop and run the success callback.
  6851. */
  6852. AsyncLoop.prototype.breakLoop = function () {
  6853. this._done = true;
  6854. this._successCallback();
  6855. };
  6856. /**
  6857. * Helper function
  6858. */
  6859. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6860. if (offset === void 0) { offset = 0; }
  6861. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6862. loop.executeNext();
  6863. return loop;
  6864. };
  6865. /**
  6866. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6867. * @param iterations total number of iterations
  6868. * @param syncedIterations number of synchronous iterations in each async iteration.
  6869. * @param fn the function to call each iteration.
  6870. * @param callback a success call back that will be called when iterating stops.
  6871. * @param breakFunction a break condition (optional)
  6872. * @param timeout timeout settings for the setTimeout function. default - 0.
  6873. * @constructor
  6874. */
  6875. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6876. if (timeout === void 0) { timeout = 0; }
  6877. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6878. if (breakFunction && breakFunction())
  6879. loop.breakLoop();
  6880. else {
  6881. setTimeout(function () {
  6882. for (var i = 0; i < syncedIterations; ++i) {
  6883. var iteration = (loop.index * syncedIterations) + i;
  6884. if (iteration >= iterations)
  6885. break;
  6886. fn(iteration);
  6887. if (breakFunction && breakFunction()) {
  6888. loop.breakLoop();
  6889. break;
  6890. }
  6891. }
  6892. loop.executeNext();
  6893. }, timeout);
  6894. }
  6895. }, callback);
  6896. };
  6897. return AsyncLoop;
  6898. }());
  6899. BABYLON.AsyncLoop = AsyncLoop;
  6900. })(BABYLON || (BABYLON = {}));
  6901. //# sourceMappingURL=babylon.tools.js.map
  6902. var BABYLON;
  6903. (function (BABYLON) {
  6904. var Internals;
  6905. (function (Internals) {
  6906. var _AlphaState = (function () {
  6907. /**
  6908. * Initializes the state.
  6909. */
  6910. function _AlphaState() {
  6911. this._isAlphaBlendDirty = false;
  6912. this._isBlendFunctionParametersDirty = false;
  6913. this._isBlendEquationParametersDirty = false;
  6914. this._isBlendConstantsDirty = false;
  6915. this._alphaBlend = false;
  6916. this._blendFunctionParameters = new Array(4);
  6917. this._blendEquationParameters = new Array(2);
  6918. this._blendConstants = new Array(4);
  6919. this.reset();
  6920. }
  6921. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6922. get: function () {
  6923. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6924. },
  6925. enumerable: true,
  6926. configurable: true
  6927. });
  6928. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6929. get: function () {
  6930. return this._alphaBlend;
  6931. },
  6932. set: function (value) {
  6933. if (this._alphaBlend === value) {
  6934. return;
  6935. }
  6936. this._alphaBlend = value;
  6937. this._isAlphaBlendDirty = true;
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6943. if (this._blendConstants[0] === r &&
  6944. this._blendConstants[1] === g &&
  6945. this._blendConstants[2] === b &&
  6946. this._blendConstants[3] === a) {
  6947. return;
  6948. }
  6949. this._blendConstants[0] = r;
  6950. this._blendConstants[1] = g;
  6951. this._blendConstants[2] = b;
  6952. this._blendConstants[3] = a;
  6953. this._isBlendConstantsDirty = true;
  6954. };
  6955. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6956. if (this._blendFunctionParameters[0] === value0 &&
  6957. this._blendFunctionParameters[1] === value1 &&
  6958. this._blendFunctionParameters[2] === value2 &&
  6959. this._blendFunctionParameters[3] === value3) {
  6960. return;
  6961. }
  6962. this._blendFunctionParameters[0] = value0;
  6963. this._blendFunctionParameters[1] = value1;
  6964. this._blendFunctionParameters[2] = value2;
  6965. this._blendFunctionParameters[3] = value3;
  6966. this._isBlendFunctionParametersDirty = true;
  6967. };
  6968. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6969. if (this._blendEquationParameters[0] === rgb &&
  6970. this._blendEquationParameters[1] === alpha) {
  6971. return;
  6972. }
  6973. this._blendEquationParameters[0] = rgb;
  6974. this._blendEquationParameters[1] = alpha;
  6975. this._isBlendEquationParametersDirty = true;
  6976. };
  6977. _AlphaState.prototype.reset = function () {
  6978. this._alphaBlend = false;
  6979. this._blendFunctionParameters[0] = null;
  6980. this._blendFunctionParameters[1] = null;
  6981. this._blendFunctionParameters[2] = null;
  6982. this._blendFunctionParameters[3] = null;
  6983. this._blendEquationParameters[0] = null;
  6984. this._blendEquationParameters[1] = null;
  6985. this._blendConstants[0] = null;
  6986. this._blendConstants[1] = null;
  6987. this._blendConstants[2] = null;
  6988. this._blendConstants[3] = null;
  6989. this._isAlphaBlendDirty = true;
  6990. this._isBlendFunctionParametersDirty = false;
  6991. this._isBlendEquationParametersDirty = false;
  6992. this._isBlendConstantsDirty = false;
  6993. };
  6994. _AlphaState.prototype.apply = function (gl) {
  6995. if (!this.isDirty) {
  6996. return;
  6997. }
  6998. // Alpha blend
  6999. if (this._isAlphaBlendDirty) {
  7000. if (this._alphaBlend) {
  7001. gl.enable(gl.BLEND);
  7002. }
  7003. else {
  7004. gl.disable(gl.BLEND);
  7005. }
  7006. this._isAlphaBlendDirty = false;
  7007. }
  7008. // Alpha function
  7009. if (this._isBlendFunctionParametersDirty) {
  7010. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7011. this._isBlendFunctionParametersDirty = false;
  7012. }
  7013. // Alpha equation
  7014. if (this._isBlendEquationParametersDirty) {
  7015. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7016. this._isBlendEquationParametersDirty = false;
  7017. }
  7018. // Constants
  7019. if (this._isBlendConstantsDirty) {
  7020. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7021. this._isBlendConstantsDirty = false;
  7022. }
  7023. };
  7024. return _AlphaState;
  7025. }());
  7026. Internals._AlphaState = _AlphaState;
  7027. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7028. })(BABYLON || (BABYLON = {}));
  7029. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7030. var BABYLON;
  7031. (function (BABYLON) {
  7032. var Internals;
  7033. (function (Internals) {
  7034. var _DepthCullingState = (function () {
  7035. /**
  7036. * Initializes the state.
  7037. */
  7038. function _DepthCullingState() {
  7039. this._isDepthTestDirty = false;
  7040. this._isDepthMaskDirty = false;
  7041. this._isDepthFuncDirty = false;
  7042. this._isCullFaceDirty = false;
  7043. this._isCullDirty = false;
  7044. this._isZOffsetDirty = false;
  7045. this.reset();
  7046. }
  7047. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7048. get: function () {
  7049. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7050. },
  7051. enumerable: true,
  7052. configurable: true
  7053. });
  7054. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7055. get: function () {
  7056. return this._zOffset;
  7057. },
  7058. set: function (value) {
  7059. if (this._zOffset === value) {
  7060. return;
  7061. }
  7062. this._zOffset = value;
  7063. this._isZOffsetDirty = true;
  7064. },
  7065. enumerable: true,
  7066. configurable: true
  7067. });
  7068. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7069. get: function () {
  7070. return this._cullFace;
  7071. },
  7072. set: function (value) {
  7073. if (this._cullFace === value) {
  7074. return;
  7075. }
  7076. this._cullFace = value;
  7077. this._isCullFaceDirty = true;
  7078. },
  7079. enumerable: true,
  7080. configurable: true
  7081. });
  7082. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7083. get: function () {
  7084. return this._cull;
  7085. },
  7086. set: function (value) {
  7087. if (this._cull === value) {
  7088. return;
  7089. }
  7090. this._cull = value;
  7091. this._isCullDirty = true;
  7092. },
  7093. enumerable: true,
  7094. configurable: true
  7095. });
  7096. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7097. get: function () {
  7098. return this._depthFunc;
  7099. },
  7100. set: function (value) {
  7101. if (this._depthFunc === value) {
  7102. return;
  7103. }
  7104. this._depthFunc = value;
  7105. this._isDepthFuncDirty = true;
  7106. },
  7107. enumerable: true,
  7108. configurable: true
  7109. });
  7110. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7111. get: function () {
  7112. return this._depthMask;
  7113. },
  7114. set: function (value) {
  7115. if (this._depthMask === value) {
  7116. return;
  7117. }
  7118. this._depthMask = value;
  7119. this._isDepthMaskDirty = true;
  7120. },
  7121. enumerable: true,
  7122. configurable: true
  7123. });
  7124. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7125. get: function () {
  7126. return this._depthTest;
  7127. },
  7128. set: function (value) {
  7129. if (this._depthTest === value) {
  7130. return;
  7131. }
  7132. this._depthTest = value;
  7133. this._isDepthTestDirty = true;
  7134. },
  7135. enumerable: true,
  7136. configurable: true
  7137. });
  7138. _DepthCullingState.prototype.reset = function () {
  7139. this._depthMask = true;
  7140. this._depthTest = true;
  7141. this._depthFunc = null;
  7142. this._cullFace = null;
  7143. this._cull = null;
  7144. this._zOffset = 0;
  7145. this._isDepthTestDirty = true;
  7146. this._isDepthMaskDirty = true;
  7147. this._isDepthFuncDirty = false;
  7148. this._isCullFaceDirty = false;
  7149. this._isCullDirty = false;
  7150. this._isZOffsetDirty = false;
  7151. };
  7152. _DepthCullingState.prototype.apply = function (gl) {
  7153. if (!this.isDirty) {
  7154. return;
  7155. }
  7156. // Cull
  7157. if (this._isCullDirty) {
  7158. if (this.cull) {
  7159. gl.enable(gl.CULL_FACE);
  7160. }
  7161. else {
  7162. gl.disable(gl.CULL_FACE);
  7163. }
  7164. this._isCullDirty = false;
  7165. }
  7166. // Cull face
  7167. if (this._isCullFaceDirty) {
  7168. gl.cullFace(this.cullFace);
  7169. this._isCullFaceDirty = false;
  7170. }
  7171. // Depth mask
  7172. if (this._isDepthMaskDirty) {
  7173. gl.depthMask(this.depthMask);
  7174. this._isDepthMaskDirty = false;
  7175. }
  7176. // Depth test
  7177. if (this._isDepthTestDirty) {
  7178. if (this.depthTest) {
  7179. gl.enable(gl.DEPTH_TEST);
  7180. }
  7181. else {
  7182. gl.disable(gl.DEPTH_TEST);
  7183. }
  7184. this._isDepthTestDirty = false;
  7185. }
  7186. // Depth func
  7187. if (this._isDepthFuncDirty) {
  7188. gl.depthFunc(this.depthFunc);
  7189. this._isDepthFuncDirty = false;
  7190. }
  7191. // zOffset
  7192. if (this._isZOffsetDirty) {
  7193. if (this.zOffset) {
  7194. gl.enable(gl.POLYGON_OFFSET_FILL);
  7195. gl.polygonOffset(this.zOffset, 0);
  7196. }
  7197. else {
  7198. gl.disable(gl.POLYGON_OFFSET_FILL);
  7199. }
  7200. this._isZOffsetDirty = false;
  7201. }
  7202. };
  7203. return _DepthCullingState;
  7204. }());
  7205. Internals._DepthCullingState = _DepthCullingState;
  7206. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7207. })(BABYLON || (BABYLON = {}));
  7208. //# sourceMappingURL=babylon.depthCullingState.js.map
  7209. var BABYLON;
  7210. (function (BABYLON) {
  7211. var Internals;
  7212. (function (Internals) {
  7213. var _StencilState = (function () {
  7214. function _StencilState() {
  7215. this._isStencilTestDirty = false;
  7216. this._isStencilMaskDirty = false;
  7217. this._isStencilFuncDirty = false;
  7218. this._isStencilOpDirty = false;
  7219. this.reset();
  7220. }
  7221. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7222. get: function () {
  7223. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7224. },
  7225. enumerable: true,
  7226. configurable: true
  7227. });
  7228. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7229. get: function () {
  7230. return this._stencilFunc;
  7231. },
  7232. set: function (value) {
  7233. if (this._stencilFunc === value) {
  7234. return;
  7235. }
  7236. this._stencilFunc = value;
  7237. this._isStencilFuncDirty = true;
  7238. },
  7239. enumerable: true,
  7240. configurable: true
  7241. });
  7242. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7243. get: function () {
  7244. return this._stencilFuncRef;
  7245. },
  7246. set: function (value) {
  7247. if (this._stencilFuncRef === value) {
  7248. return;
  7249. }
  7250. this._stencilFuncRef = value;
  7251. this._isStencilFuncDirty = true;
  7252. },
  7253. enumerable: true,
  7254. configurable: true
  7255. });
  7256. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7257. get: function () {
  7258. return this._stencilFuncMask;
  7259. },
  7260. set: function (value) {
  7261. if (this._stencilFuncMask === value) {
  7262. return;
  7263. }
  7264. this._stencilFuncMask = value;
  7265. this._isStencilFuncDirty = true;
  7266. },
  7267. enumerable: true,
  7268. configurable: true
  7269. });
  7270. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7271. get: function () {
  7272. return this._stencilOpStencilFail;
  7273. },
  7274. set: function (value) {
  7275. if (this._stencilOpStencilFail === value) {
  7276. return;
  7277. }
  7278. this._stencilOpStencilFail = value;
  7279. this._isStencilOpDirty = true;
  7280. },
  7281. enumerable: true,
  7282. configurable: true
  7283. });
  7284. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7285. get: function () {
  7286. return this._stencilOpDepthFail;
  7287. },
  7288. set: function (value) {
  7289. if (this._stencilOpDepthFail === value) {
  7290. return;
  7291. }
  7292. this._stencilOpDepthFail = value;
  7293. this._isStencilOpDirty = true;
  7294. },
  7295. enumerable: true,
  7296. configurable: true
  7297. });
  7298. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7299. get: function () {
  7300. return this._stencilOpStencilDepthPass;
  7301. },
  7302. set: function (value) {
  7303. if (this._stencilOpStencilDepthPass === value) {
  7304. return;
  7305. }
  7306. this._stencilOpStencilDepthPass = value;
  7307. this._isStencilOpDirty = true;
  7308. },
  7309. enumerable: true,
  7310. configurable: true
  7311. });
  7312. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7313. get: function () {
  7314. return this._stencilMask;
  7315. },
  7316. set: function (value) {
  7317. if (this._stencilMask === value) {
  7318. return;
  7319. }
  7320. this._stencilMask = value;
  7321. this._isStencilMaskDirty = true;
  7322. },
  7323. enumerable: true,
  7324. configurable: true
  7325. });
  7326. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7327. get: function () {
  7328. return this._stencilTest;
  7329. },
  7330. set: function (value) {
  7331. if (this._stencilTest === value) {
  7332. return;
  7333. }
  7334. this._stencilTest = value;
  7335. this._isStencilTestDirty = true;
  7336. },
  7337. enumerable: true,
  7338. configurable: true
  7339. });
  7340. _StencilState.prototype.reset = function () {
  7341. this._stencilTest = false;
  7342. this._stencilMask = 0xFF;
  7343. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7344. this._stencilFuncRef = 1;
  7345. this._stencilFuncMask = 0xFF;
  7346. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7347. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7348. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7349. this._isStencilTestDirty = true;
  7350. this._isStencilMaskDirty = true;
  7351. this._isStencilFuncDirty = true;
  7352. this._isStencilOpDirty = true;
  7353. };
  7354. _StencilState.prototype.apply = function (gl) {
  7355. if (!this.isDirty) {
  7356. return;
  7357. }
  7358. // Stencil test
  7359. if (this._isStencilTestDirty) {
  7360. if (this.stencilTest) {
  7361. gl.enable(gl.STENCIL_TEST);
  7362. }
  7363. else {
  7364. gl.disable(gl.STENCIL_TEST);
  7365. }
  7366. this._isStencilTestDirty = false;
  7367. }
  7368. // Stencil mask
  7369. if (this._isStencilMaskDirty) {
  7370. gl.stencilMask(this.stencilMask);
  7371. this._isStencilMaskDirty = false;
  7372. }
  7373. // Stencil func
  7374. if (this._isStencilFuncDirty) {
  7375. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7376. this._isStencilFuncDirty = false;
  7377. }
  7378. // Stencil op
  7379. if (this._isStencilOpDirty) {
  7380. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7381. this._isStencilOpDirty = false;
  7382. }
  7383. };
  7384. return _StencilState;
  7385. }());
  7386. Internals._StencilState = _StencilState;
  7387. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7388. })(BABYLON || (BABYLON = {}));
  7389. //# sourceMappingURL=babylon.stencilState.js.map
  7390. var BABYLON;
  7391. (function (BABYLON) {
  7392. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7393. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7394. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7395. gl.compileShader(shader);
  7396. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7397. throw new Error(gl.getShaderInfoLog(shader));
  7398. }
  7399. return shader;
  7400. };
  7401. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7402. var magFilter = gl.NEAREST;
  7403. var minFilter = gl.NEAREST;
  7404. switch (samplingMode) {
  7405. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7406. magFilter = gl.LINEAR;
  7407. if (generateMipMaps) {
  7408. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7409. }
  7410. else {
  7411. minFilter = gl.LINEAR;
  7412. }
  7413. break;
  7414. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7415. magFilter = gl.LINEAR;
  7416. if (generateMipMaps) {
  7417. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7418. }
  7419. else {
  7420. minFilter = gl.LINEAR;
  7421. }
  7422. break;
  7423. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7424. magFilter = gl.NEAREST;
  7425. if (generateMipMaps) {
  7426. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7427. }
  7428. else {
  7429. minFilter = gl.NEAREST;
  7430. }
  7431. break;
  7432. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7433. magFilter = gl.NEAREST;
  7434. if (generateMipMaps) {
  7435. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7436. }
  7437. else {
  7438. minFilter = gl.NEAREST;
  7439. }
  7440. break;
  7441. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7442. magFilter = gl.NEAREST;
  7443. if (generateMipMaps) {
  7444. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7445. }
  7446. else {
  7447. minFilter = gl.LINEAR;
  7448. }
  7449. break;
  7450. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7451. magFilter = gl.NEAREST;
  7452. if (generateMipMaps) {
  7453. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7454. }
  7455. else {
  7456. minFilter = gl.LINEAR;
  7457. }
  7458. break;
  7459. case BABYLON.Texture.NEAREST_LINEAR:
  7460. magFilter = gl.NEAREST;
  7461. minFilter = gl.LINEAR;
  7462. break;
  7463. case BABYLON.Texture.NEAREST_NEAREST:
  7464. magFilter = gl.NEAREST;
  7465. minFilter = gl.NEAREST;
  7466. break;
  7467. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7468. magFilter = gl.LINEAR;
  7469. if (generateMipMaps) {
  7470. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7471. }
  7472. else {
  7473. minFilter = gl.NEAREST;
  7474. }
  7475. break;
  7476. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7477. magFilter = gl.LINEAR;
  7478. if (generateMipMaps) {
  7479. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7480. }
  7481. else {
  7482. minFilter = gl.NEAREST;
  7483. }
  7484. break;
  7485. case BABYLON.Texture.LINEAR_LINEAR:
  7486. magFilter = gl.LINEAR;
  7487. minFilter = gl.LINEAR;
  7488. break;
  7489. case BABYLON.Texture.LINEAR_NEAREST:
  7490. magFilter = gl.LINEAR;
  7491. minFilter = gl.NEAREST;
  7492. break;
  7493. }
  7494. return {
  7495. min: minFilter,
  7496. mag: magFilter
  7497. };
  7498. };
  7499. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7500. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7501. var img;
  7502. var onload = function () {
  7503. loadedImages[index] = img;
  7504. loadedImages._internalCount++;
  7505. if (scene) {
  7506. scene._removePendingData(img);
  7507. }
  7508. if (loadedImages._internalCount === 6) {
  7509. onfinish(loadedImages);
  7510. }
  7511. };
  7512. var onerror = function () {
  7513. if (scene) {
  7514. scene._removePendingData(img);
  7515. }
  7516. if (onErrorCallBack) {
  7517. onErrorCallBack();
  7518. }
  7519. };
  7520. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7521. if (scene) {
  7522. scene._addPendingData(img);
  7523. }
  7524. };
  7525. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7526. if (onError === void 0) { onError = null; }
  7527. var loadedImages = [];
  7528. loadedImages._internalCount = 0;
  7529. for (var index = 0; index < 6; index++) {
  7530. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7531. }
  7532. };
  7533. var BufferPointer = (function () {
  7534. function BufferPointer() {
  7535. }
  7536. return BufferPointer;
  7537. }());
  7538. var InstancingAttributeInfo = (function () {
  7539. function InstancingAttributeInfo() {
  7540. }
  7541. return InstancingAttributeInfo;
  7542. }());
  7543. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7544. /**
  7545. * Define options used to create a render target texture
  7546. */
  7547. var RenderTargetCreationOptions = (function () {
  7548. function RenderTargetCreationOptions() {
  7549. }
  7550. return RenderTargetCreationOptions;
  7551. }());
  7552. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7553. /**
  7554. * Regroup several parameters relative to the browser in use
  7555. */
  7556. var EngineCapabilities = (function () {
  7557. function EngineCapabilities() {
  7558. }
  7559. return EngineCapabilities;
  7560. }());
  7561. BABYLON.EngineCapabilities = EngineCapabilities;
  7562. /**
  7563. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7564. */
  7565. var Engine = (function () {
  7566. /**
  7567. * @constructor
  7568. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7569. * @param {boolean} [antialias] - enable antialias
  7570. * @param options - further options to be sent to the getContext function
  7571. */
  7572. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7573. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7574. var _this = this;
  7575. // Public members
  7576. this.forcePOTTextures = false;
  7577. this.isFullscreen = false;
  7578. this.isPointerLock = false;
  7579. this.cullBackFaces = true;
  7580. this.renderEvenInBackground = true;
  7581. this.preventCacheWipeBetweenFrames = false;
  7582. // To enable/disable IDB support and avoid XHR on .manifest
  7583. this.enableOfflineSupport = false;
  7584. this.scenes = new Array();
  7585. this.postProcesses = new Array();
  7586. // Observables
  7587. /**
  7588. * Observable event triggered each time the rendering canvas is resized
  7589. */
  7590. this.onResizeObservable = new BABYLON.Observable();
  7591. /**
  7592. * Observable event triggered each time the canvas loses focus
  7593. */
  7594. this.onCanvasBlurObservable = new BABYLON.Observable();
  7595. /**
  7596. * Observable event triggered each time the canvas gains focus
  7597. */
  7598. this.onCanvasFocusObservable = new BABYLON.Observable();
  7599. /**
  7600. * Observable event triggered each time the canvas receives pointerout event
  7601. */
  7602. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7603. // Uniform buffers list
  7604. this.disableUniformBuffers = false;
  7605. this._uniformBuffers = new Array();
  7606. this._windowIsBackground = false;
  7607. this._webGLVersion = 1.0;
  7608. this._badOS = false;
  7609. this._badDesktopOS = false;
  7610. this._drawCalls = new BABYLON.PerfCounter();
  7611. this._renderingQueueLaunched = false;
  7612. this._activeRenderLoops = [];
  7613. // Deterministic lockstepMaxSteps
  7614. this._deterministicLockstep = false;
  7615. this._lockstepMaxSteps = 4;
  7616. // Lost context
  7617. this.onContextLostObservable = new BABYLON.Observable();
  7618. this.onContextRestoredObservable = new BABYLON.Observable();
  7619. this._contextWasLost = false;
  7620. this._doNotHandleContextLost = false;
  7621. // FPS
  7622. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7623. this._fps = 60;
  7624. this._deltaTime = 0;
  7625. /**
  7626. * Turn this value on if you want to pause FPS computation when in background
  7627. */
  7628. this.disablePerformanceMonitorInBackground = false;
  7629. // States
  7630. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7631. this._stencilState = new BABYLON.Internals._StencilState();
  7632. this._alphaState = new BABYLON.Internals._AlphaState();
  7633. this._alphaMode = Engine.ALPHA_DISABLE;
  7634. // Cache
  7635. this._internalTexturesCache = new Array();
  7636. this._maxTextureChannels = 16;
  7637. this._activeTexturesCache = {};
  7638. this._compiledEffects = {};
  7639. this._vertexAttribArraysEnabled = [];
  7640. this._uintIndicesCurrentlySet = false;
  7641. this._currentBoundBuffer = new Array();
  7642. this._currentBufferPointers = new Array();
  7643. this._currentInstanceLocations = new Array();
  7644. this._currentInstanceBuffers = new Array();
  7645. this._vaoRecordInProgress = false;
  7646. this._mustWipeVertexAttributes = false;
  7647. // Hardware supported Compressed Textures
  7648. this._texturesSupported = new Array();
  7649. this._onVRFullScreenTriggered = function () {
  7650. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7651. //get the old size before we change
  7652. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7653. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7654. //get the width and height, change the render size
  7655. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7656. var width, height;
  7657. _this.setHardwareScalingLevel(1);
  7658. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7659. }
  7660. else {
  7661. //When the specs are implemented, need to uncomment this.
  7662. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7663. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7664. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7665. _this._vrDisplayEnabled = undefined;
  7666. }
  7667. };
  7668. var canvas;
  7669. Engine.Instances.push(this);
  7670. options = options || {};
  7671. if (canvasOrContext.getContext) {
  7672. canvas = canvasOrContext;
  7673. this._renderingCanvas = canvas;
  7674. if (antialias != null) {
  7675. options.antialias = antialias;
  7676. }
  7677. if (options.deterministicLockstep === undefined) {
  7678. options.deterministicLockstep = false;
  7679. }
  7680. if (options.lockstepMaxSteps === undefined) {
  7681. options.lockstepMaxSteps = 4;
  7682. }
  7683. if (options.preserveDrawingBuffer === undefined) {
  7684. options.preserveDrawingBuffer = false;
  7685. }
  7686. if (options.audioEngine === undefined) {
  7687. options.audioEngine = true;
  7688. }
  7689. if (options.stencil === undefined) {
  7690. options.stencil = true;
  7691. }
  7692. this._deterministicLockstep = options.deterministicLockstep;
  7693. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7694. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7695. // GL
  7696. if (!options.disableWebGL2Support) {
  7697. try {
  7698. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7699. if (this._gl) {
  7700. this._webGLVersion = 2.0;
  7701. }
  7702. }
  7703. catch (e) {
  7704. // Do nothing
  7705. }
  7706. }
  7707. if (!this._gl) {
  7708. if (!canvas) {
  7709. throw new Error("The provided canvas is null or undefined.");
  7710. }
  7711. try {
  7712. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7713. }
  7714. catch (e) {
  7715. throw new Error("WebGL not supported");
  7716. }
  7717. }
  7718. if (!this._gl) {
  7719. throw new Error("WebGL not supported");
  7720. }
  7721. this._onCanvasFocus = function () {
  7722. _this.onCanvasFocusObservable.notifyObservers(_this);
  7723. };
  7724. this._onCanvasBlur = function () {
  7725. _this.onCanvasBlurObservable.notifyObservers(_this);
  7726. };
  7727. canvas.addEventListener("focus", this._onCanvasFocus);
  7728. canvas.addEventListener("blur", this._onCanvasBlur);
  7729. this._onBlur = function () {
  7730. if (_this.disablePerformanceMonitorInBackground) {
  7731. _this._performanceMonitor.disable();
  7732. }
  7733. _this._windowIsBackground = true;
  7734. };
  7735. this._onFocus = function () {
  7736. if (_this.disablePerformanceMonitorInBackground) {
  7737. _this._performanceMonitor.enable();
  7738. }
  7739. _this._windowIsBackground = false;
  7740. };
  7741. this._onCanvasPointerOut = function () {
  7742. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7743. };
  7744. window.addEventListener("blur", this._onBlur);
  7745. window.addEventListener("focus", this._onFocus);
  7746. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7747. }
  7748. else {
  7749. this._gl = canvasOrContext;
  7750. this._renderingCanvas = this._gl.canvas;
  7751. if (this._gl.renderbufferStorageMultisample) {
  7752. this._webGLVersion = 2.0;
  7753. }
  7754. options.stencil = this._gl.getContextAttributes().stencil;
  7755. }
  7756. // Context lost
  7757. if (!this._doNotHandleContextLost) {
  7758. this._onContextLost = function (evt) {
  7759. evt.preventDefault();
  7760. _this._contextWasLost = true;
  7761. BABYLON.Tools.Warn("WebGL context lost.");
  7762. _this.onContextLostObservable.notifyObservers(_this);
  7763. };
  7764. this._onContextRestored = function (evt) {
  7765. // Rebuild gl context
  7766. _this._initGLContext();
  7767. // Rebuild effects
  7768. _this._rebuildEffects();
  7769. // Rebuild textures
  7770. _this._rebuildInternalTextures();
  7771. // Rebuild buffers
  7772. _this._rebuildBuffers();
  7773. // Cache
  7774. _this.wipeCaches(true);
  7775. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7776. _this.onContextRestoredObservable.notifyObservers(_this);
  7777. _this._contextWasLost = false;
  7778. };
  7779. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7780. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7781. }
  7782. // Viewport
  7783. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7784. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7785. this.resize();
  7786. this._isStencilEnable = options.stencil;
  7787. this._initGLContext();
  7788. if (canvas) {
  7789. // Fullscreen
  7790. this._onFullscreenChange = function () {
  7791. if (document.fullscreen !== undefined) {
  7792. _this.isFullscreen = document.fullscreen;
  7793. }
  7794. else if (document.mozFullScreen !== undefined) {
  7795. _this.isFullscreen = document.mozFullScreen;
  7796. }
  7797. else if (document.webkitIsFullScreen !== undefined) {
  7798. _this.isFullscreen = document.webkitIsFullScreen;
  7799. }
  7800. else if (document.msIsFullScreen !== undefined) {
  7801. _this.isFullscreen = document.msIsFullScreen;
  7802. }
  7803. // Pointer lock
  7804. if (_this.isFullscreen && _this._pointerLockRequested) {
  7805. canvas.requestPointerLock = canvas.requestPointerLock ||
  7806. canvas.msRequestPointerLock ||
  7807. canvas.mozRequestPointerLock ||
  7808. canvas.webkitRequestPointerLock;
  7809. if (canvas.requestPointerLock) {
  7810. canvas.requestPointerLock();
  7811. }
  7812. }
  7813. };
  7814. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7815. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7816. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7817. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7818. // Pointer lock
  7819. this._onPointerLockChange = function () {
  7820. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7821. document.webkitPointerLockElement === canvas ||
  7822. document.msPointerLockElement === canvas ||
  7823. document.pointerLockElement === canvas);
  7824. };
  7825. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7826. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7827. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7828. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7829. this._onVRDisplayPointerRestricted = function () {
  7830. canvas.requestPointerLock();
  7831. };
  7832. this._onVRDisplayPointerUnrestricted = function () {
  7833. document.exitPointerLock();
  7834. };
  7835. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7836. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7837. }
  7838. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7839. Engine.audioEngine = new BABYLON.AudioEngine();
  7840. }
  7841. // Prepare buffer pointers
  7842. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7843. this._currentBufferPointers[i] = new BufferPointer();
  7844. }
  7845. // Load WebVR Devices
  7846. if (options.autoEnableWebVR) {
  7847. this.initWebVR();
  7848. }
  7849. // Detect if we are running on a faulty buggy OS.
  7850. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7851. // Detect if we are running on a faulty buggy desktop OS.
  7852. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7853. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7854. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7855. }
  7856. Object.defineProperty(Engine, "LastCreatedEngine", {
  7857. get: function () {
  7858. if (Engine.Instances.length === 0) {
  7859. return null;
  7860. }
  7861. return Engine.Instances[Engine.Instances.length - 1];
  7862. },
  7863. enumerable: true,
  7864. configurable: true
  7865. });
  7866. Object.defineProperty(Engine, "LastCreatedScene", {
  7867. get: function () {
  7868. var lastCreatedEngine = Engine.LastCreatedEngine;
  7869. if (!lastCreatedEngine) {
  7870. return null;
  7871. }
  7872. if (lastCreatedEngine.scenes.length === 0) {
  7873. return null;
  7874. }
  7875. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7876. },
  7877. enumerable: true,
  7878. configurable: true
  7879. });
  7880. /**
  7881. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7882. */
  7883. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7884. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7885. var engine = Engine.Instances[engineIndex];
  7886. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7887. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7888. }
  7889. }
  7890. };
  7891. Object.defineProperty(Engine, "NEVER", {
  7892. get: function () {
  7893. return Engine._NEVER;
  7894. },
  7895. enumerable: true,
  7896. configurable: true
  7897. });
  7898. Object.defineProperty(Engine, "ALWAYS", {
  7899. get: function () {
  7900. return Engine._ALWAYS;
  7901. },
  7902. enumerable: true,
  7903. configurable: true
  7904. });
  7905. Object.defineProperty(Engine, "LESS", {
  7906. get: function () {
  7907. return Engine._LESS;
  7908. },
  7909. enumerable: true,
  7910. configurable: true
  7911. });
  7912. Object.defineProperty(Engine, "EQUAL", {
  7913. get: function () {
  7914. return Engine._EQUAL;
  7915. },
  7916. enumerable: true,
  7917. configurable: true
  7918. });
  7919. Object.defineProperty(Engine, "LEQUAL", {
  7920. get: function () {
  7921. return Engine._LEQUAL;
  7922. },
  7923. enumerable: true,
  7924. configurable: true
  7925. });
  7926. Object.defineProperty(Engine, "GREATER", {
  7927. get: function () {
  7928. return Engine._GREATER;
  7929. },
  7930. enumerable: true,
  7931. configurable: true
  7932. });
  7933. Object.defineProperty(Engine, "GEQUAL", {
  7934. get: function () {
  7935. return Engine._GEQUAL;
  7936. },
  7937. enumerable: true,
  7938. configurable: true
  7939. });
  7940. Object.defineProperty(Engine, "NOTEQUAL", {
  7941. get: function () {
  7942. return Engine._NOTEQUAL;
  7943. },
  7944. enumerable: true,
  7945. configurable: true
  7946. });
  7947. Object.defineProperty(Engine, "KEEP", {
  7948. get: function () {
  7949. return Engine._KEEP;
  7950. },
  7951. enumerable: true,
  7952. configurable: true
  7953. });
  7954. Object.defineProperty(Engine, "REPLACE", {
  7955. get: function () {
  7956. return Engine._REPLACE;
  7957. },
  7958. enumerable: true,
  7959. configurable: true
  7960. });
  7961. Object.defineProperty(Engine, "INCR", {
  7962. get: function () {
  7963. return Engine._INCR;
  7964. },
  7965. enumerable: true,
  7966. configurable: true
  7967. });
  7968. Object.defineProperty(Engine, "DECR", {
  7969. get: function () {
  7970. return Engine._DECR;
  7971. },
  7972. enumerable: true,
  7973. configurable: true
  7974. });
  7975. Object.defineProperty(Engine, "INVERT", {
  7976. get: function () {
  7977. return Engine._INVERT;
  7978. },
  7979. enumerable: true,
  7980. configurable: true
  7981. });
  7982. Object.defineProperty(Engine, "INCR_WRAP", {
  7983. get: function () {
  7984. return Engine._INCR_WRAP;
  7985. },
  7986. enumerable: true,
  7987. configurable: true
  7988. });
  7989. Object.defineProperty(Engine, "DECR_WRAP", {
  7990. get: function () {
  7991. return Engine._DECR_WRAP;
  7992. },
  7993. enumerable: true,
  7994. configurable: true
  7995. });
  7996. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7997. get: function () {
  7998. return Engine._ALPHA_DISABLE;
  7999. },
  8000. enumerable: true,
  8001. configurable: true
  8002. });
  8003. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8004. get: function () {
  8005. return Engine._ALPHA_ONEONE;
  8006. },
  8007. enumerable: true,
  8008. configurable: true
  8009. });
  8010. Object.defineProperty(Engine, "ALPHA_ADD", {
  8011. get: function () {
  8012. return Engine._ALPHA_ADD;
  8013. },
  8014. enumerable: true,
  8015. configurable: true
  8016. });
  8017. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8018. get: function () {
  8019. return Engine._ALPHA_COMBINE;
  8020. },
  8021. enumerable: true,
  8022. configurable: true
  8023. });
  8024. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8025. get: function () {
  8026. return Engine._ALPHA_SUBTRACT;
  8027. },
  8028. enumerable: true,
  8029. configurable: true
  8030. });
  8031. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8032. get: function () {
  8033. return Engine._ALPHA_MULTIPLY;
  8034. },
  8035. enumerable: true,
  8036. configurable: true
  8037. });
  8038. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8039. get: function () {
  8040. return Engine._ALPHA_MAXIMIZED;
  8041. },
  8042. enumerable: true,
  8043. configurable: true
  8044. });
  8045. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8046. get: function () {
  8047. return Engine._ALPHA_PREMULTIPLIED;
  8048. },
  8049. enumerable: true,
  8050. configurable: true
  8051. });
  8052. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8053. get: function () {
  8054. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8055. },
  8056. enumerable: true,
  8057. configurable: true
  8058. });
  8059. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8060. get: function () {
  8061. return Engine._ALPHA_INTERPOLATE;
  8062. },
  8063. enumerable: true,
  8064. configurable: true
  8065. });
  8066. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8067. get: function () {
  8068. return Engine._ALPHA_SCREENMODE;
  8069. },
  8070. enumerable: true,
  8071. configurable: true
  8072. });
  8073. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8074. get: function () {
  8075. return Engine._DELAYLOADSTATE_NONE;
  8076. },
  8077. enumerable: true,
  8078. configurable: true
  8079. });
  8080. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8081. get: function () {
  8082. return Engine._DELAYLOADSTATE_LOADED;
  8083. },
  8084. enumerable: true,
  8085. configurable: true
  8086. });
  8087. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8088. get: function () {
  8089. return Engine._DELAYLOADSTATE_LOADING;
  8090. },
  8091. enumerable: true,
  8092. configurable: true
  8093. });
  8094. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8095. get: function () {
  8096. return Engine._DELAYLOADSTATE_NOTLOADED;
  8097. },
  8098. enumerable: true,
  8099. configurable: true
  8100. });
  8101. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8102. get: function () {
  8103. return Engine._TEXTUREFORMAT_ALPHA;
  8104. },
  8105. enumerable: true,
  8106. configurable: true
  8107. });
  8108. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8109. get: function () {
  8110. return Engine._TEXTUREFORMAT_LUMINANCE;
  8111. },
  8112. enumerable: true,
  8113. configurable: true
  8114. });
  8115. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8116. get: function () {
  8117. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8118. },
  8119. enumerable: true,
  8120. configurable: true
  8121. });
  8122. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8123. get: function () {
  8124. return Engine._TEXTUREFORMAT_RGB;
  8125. },
  8126. enumerable: true,
  8127. configurable: true
  8128. });
  8129. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8130. get: function () {
  8131. return Engine._TEXTUREFORMAT_RGBA;
  8132. },
  8133. enumerable: true,
  8134. configurable: true
  8135. });
  8136. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8137. get: function () {
  8138. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8139. },
  8140. enumerable: true,
  8141. configurable: true
  8142. });
  8143. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8144. get: function () {
  8145. return Engine._TEXTURETYPE_FLOAT;
  8146. },
  8147. enumerable: true,
  8148. configurable: true
  8149. });
  8150. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8151. get: function () {
  8152. return Engine._TEXTURETYPE_HALF_FLOAT;
  8153. },
  8154. enumerable: true,
  8155. configurable: true
  8156. });
  8157. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8158. get: function () {
  8159. return Engine._SCALEMODE_FLOOR;
  8160. },
  8161. enumerable: true,
  8162. configurable: true
  8163. });
  8164. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8165. get: function () {
  8166. return Engine._SCALEMODE_NEAREST;
  8167. },
  8168. enumerable: true,
  8169. configurable: true
  8170. });
  8171. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8172. get: function () {
  8173. return Engine._SCALEMODE_CEILING;
  8174. },
  8175. enumerable: true,
  8176. configurable: true
  8177. });
  8178. Object.defineProperty(Engine, "Version", {
  8179. get: function () {
  8180. return "3.1-alpha";
  8181. },
  8182. enumerable: true,
  8183. configurable: true
  8184. });
  8185. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8186. get: function () {
  8187. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8188. },
  8189. enumerable: true,
  8190. configurable: true
  8191. });
  8192. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8193. get: function () {
  8194. return this._webGLVersion < 2 || this.forcePOTTextures;
  8195. },
  8196. enumerable: true,
  8197. configurable: true
  8198. });
  8199. Object.defineProperty(Engine.prototype, "badOS", {
  8200. get: function () {
  8201. return this._badOS;
  8202. },
  8203. enumerable: true,
  8204. configurable: true
  8205. });
  8206. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8207. get: function () {
  8208. return this._badDesktopOS;
  8209. },
  8210. enumerable: true,
  8211. configurable: true
  8212. });
  8213. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8214. get: function () {
  8215. return this._performanceMonitor;
  8216. },
  8217. enumerable: true,
  8218. configurable: true
  8219. });
  8220. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8221. get: function () {
  8222. return this._texturesSupported;
  8223. },
  8224. enumerable: true,
  8225. configurable: true
  8226. });
  8227. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8228. get: function () {
  8229. return this._textureFormatInUse;
  8230. },
  8231. enumerable: true,
  8232. configurable: true
  8233. });
  8234. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8235. // Empty texture
  8236. get: function () {
  8237. if (!this._emptyTexture) {
  8238. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8239. }
  8240. return this._emptyTexture;
  8241. },
  8242. enumerable: true,
  8243. configurable: true
  8244. });
  8245. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8246. get: function () {
  8247. if (!this._emptyCubeTexture) {
  8248. var faceData = new Uint8Array(4);
  8249. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8250. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8251. }
  8252. return this._emptyCubeTexture;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. Engine.prototype._rebuildInternalTextures = function () {
  8258. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8259. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8260. var internalTexture = currentState_1[_i];
  8261. internalTexture._rebuild();
  8262. }
  8263. };
  8264. Engine.prototype._rebuildEffects = function () {
  8265. for (var key in this._compiledEffects) {
  8266. var effect = this._compiledEffects[key];
  8267. effect._prepareEffect();
  8268. }
  8269. BABYLON.Effect.ResetCache();
  8270. };
  8271. Engine.prototype._rebuildBuffers = function () {
  8272. // Index / Vertex
  8273. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8274. var scene = _a[_i];
  8275. scene.resetCachedMaterial();
  8276. scene._rebuildGeometries();
  8277. scene._rebuildTextures();
  8278. }
  8279. // Uniforms
  8280. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8281. var uniformBuffer = _c[_b];
  8282. uniformBuffer._rebuild();
  8283. }
  8284. };
  8285. Engine.prototype._initGLContext = function () {
  8286. // Caps
  8287. this._caps = new EngineCapabilities();
  8288. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8289. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8290. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8291. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8292. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8293. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8294. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8295. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8296. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8297. // Infos
  8298. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8299. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8300. if (rendererInfo != null) {
  8301. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8302. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8303. }
  8304. if (!this._glVendor) {
  8305. this._glVendor = "Unknown vendor";
  8306. }
  8307. if (!this._glRenderer) {
  8308. this._glRenderer = "Unknown renderer";
  8309. }
  8310. // Constants
  8311. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8312. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8313. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8314. this._gl.DEPTH24_STENCIL8 = 35056;
  8315. // Extensions
  8316. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8317. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8318. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8319. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8320. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8321. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8322. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8323. 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');
  8324. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8325. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8326. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8327. this._caps.highPrecisionShaderSupported = true;
  8328. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8329. // Checks if some of the format renders first to allow the use of webgl inspector.
  8330. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8331. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8332. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8333. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8334. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8335. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8336. if (this._webGLVersion > 1) {
  8337. this._gl.HALF_FLOAT_OES = 0x140B;
  8338. }
  8339. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8340. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8341. // Vertex array object
  8342. if (this._webGLVersion > 1) {
  8343. this._caps.vertexArrayObject = true;
  8344. }
  8345. else {
  8346. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8347. if (vertexArrayObjectExtension != null) {
  8348. this._caps.vertexArrayObject = true;
  8349. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8350. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8351. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8352. }
  8353. else {
  8354. this._caps.vertexArrayObject = false;
  8355. }
  8356. }
  8357. // Instances count
  8358. if (this._webGLVersion > 1) {
  8359. this._caps.instancedArrays = true;
  8360. }
  8361. else {
  8362. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8363. if (instanceExtension != null) {
  8364. this._caps.instancedArrays = true;
  8365. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8366. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8367. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8368. }
  8369. else {
  8370. this._caps.instancedArrays = false;
  8371. }
  8372. }
  8373. // Intelligently add supported compressed formats in order to check for.
  8374. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8375. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8376. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8377. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8378. if (this._caps.astc)
  8379. this.texturesSupported.push('-astc.ktx');
  8380. if (this._caps.s3tc)
  8381. this.texturesSupported.push('-dxt.ktx');
  8382. if (this._caps.pvrtc)
  8383. this.texturesSupported.push('-pvrtc.ktx');
  8384. if (this._caps.etc2)
  8385. this.texturesSupported.push('-etc2.ktx');
  8386. if (this._caps.etc1)
  8387. this.texturesSupported.push('-etc1.ktx');
  8388. if (this._gl.getShaderPrecisionFormat) {
  8389. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8390. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8391. }
  8392. // Depth buffer
  8393. this.setDepthBuffer(true);
  8394. this.setDepthFunctionToLessOrEqual();
  8395. this.setDepthWrite(true);
  8396. };
  8397. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8398. get: function () {
  8399. return this._webGLVersion;
  8400. },
  8401. enumerable: true,
  8402. configurable: true
  8403. });
  8404. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8405. /**
  8406. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8407. */
  8408. get: function () {
  8409. return this._isStencilEnable;
  8410. },
  8411. enumerable: true,
  8412. configurable: true
  8413. });
  8414. Engine.prototype._prepareWorkingCanvas = function () {
  8415. if (this._workingCanvas) {
  8416. return;
  8417. }
  8418. this._workingCanvas = document.createElement("canvas");
  8419. this._workingContext = this._workingCanvas.getContext("2d");
  8420. };
  8421. Engine.prototype.resetTextureCache = function () {
  8422. for (var key in this._activeTexturesCache) {
  8423. this._activeTexturesCache[key] = null;
  8424. }
  8425. };
  8426. Engine.prototype.isDeterministicLockStep = function () {
  8427. return this._deterministicLockstep;
  8428. };
  8429. Engine.prototype.getLockstepMaxSteps = function () {
  8430. return this._lockstepMaxSteps;
  8431. };
  8432. Engine.prototype.getGlInfo = function () {
  8433. return {
  8434. vendor: this._glVendor,
  8435. renderer: this._glRenderer,
  8436. version: this._glVersion
  8437. };
  8438. };
  8439. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8440. if (useScreen === void 0) { useScreen = false; }
  8441. var viewport = camera.viewport;
  8442. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8443. };
  8444. Engine.prototype.getRenderWidth = function (useScreen) {
  8445. if (useScreen === void 0) { useScreen = false; }
  8446. if (!useScreen && this._currentRenderTarget) {
  8447. return this._currentRenderTarget.width;
  8448. }
  8449. return this._gl.drawingBufferWidth;
  8450. };
  8451. Engine.prototype.getRenderHeight = function (useScreen) {
  8452. if (useScreen === void 0) { useScreen = false; }
  8453. if (!useScreen && this._currentRenderTarget) {
  8454. return this._currentRenderTarget.height;
  8455. }
  8456. return this._gl.drawingBufferHeight;
  8457. };
  8458. Engine.prototype.getRenderingCanvas = function () {
  8459. return this._renderingCanvas;
  8460. };
  8461. Engine.prototype.getRenderingCanvasClientRect = function () {
  8462. return this._renderingCanvas.getBoundingClientRect();
  8463. };
  8464. Engine.prototype.setHardwareScalingLevel = function (level) {
  8465. this._hardwareScalingLevel = level;
  8466. this.resize();
  8467. };
  8468. Engine.prototype.getHardwareScalingLevel = function () {
  8469. return this._hardwareScalingLevel;
  8470. };
  8471. Engine.prototype.getLoadedTexturesCache = function () {
  8472. return this._internalTexturesCache;
  8473. };
  8474. Engine.prototype.getCaps = function () {
  8475. return this._caps;
  8476. };
  8477. Object.defineProperty(Engine.prototype, "drawCalls", {
  8478. /** The number of draw calls submitted last frame */
  8479. get: function () {
  8480. return this._drawCalls.current;
  8481. },
  8482. enumerable: true,
  8483. configurable: true
  8484. });
  8485. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8486. get: function () {
  8487. return this._drawCalls;
  8488. },
  8489. enumerable: true,
  8490. configurable: true
  8491. });
  8492. Engine.prototype.getDepthFunction = function () {
  8493. return this._depthCullingState.depthFunc;
  8494. };
  8495. Engine.prototype.setDepthFunction = function (depthFunc) {
  8496. this._depthCullingState.depthFunc = depthFunc;
  8497. };
  8498. Engine.prototype.setDepthFunctionToGreater = function () {
  8499. this._depthCullingState.depthFunc = this._gl.GREATER;
  8500. };
  8501. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8502. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8503. };
  8504. Engine.prototype.setDepthFunctionToLess = function () {
  8505. this._depthCullingState.depthFunc = this._gl.LESS;
  8506. };
  8507. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8508. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8509. };
  8510. Engine.prototype.getStencilBuffer = function () {
  8511. return this._stencilState.stencilTest;
  8512. };
  8513. Engine.prototype.setStencilBuffer = function (enable) {
  8514. this._stencilState.stencilTest = enable;
  8515. };
  8516. Engine.prototype.getStencilMask = function () {
  8517. return this._stencilState.stencilMask;
  8518. };
  8519. Engine.prototype.setStencilMask = function (mask) {
  8520. this._stencilState.stencilMask = mask;
  8521. };
  8522. Engine.prototype.getStencilFunction = function () {
  8523. return this._stencilState.stencilFunc;
  8524. };
  8525. Engine.prototype.getStencilFunctionReference = function () {
  8526. return this._stencilState.stencilFuncRef;
  8527. };
  8528. Engine.prototype.getStencilFunctionMask = function () {
  8529. return this._stencilState.stencilFuncMask;
  8530. };
  8531. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8532. this._stencilState.stencilFunc = stencilFunc;
  8533. };
  8534. Engine.prototype.setStencilFunctionReference = function (reference) {
  8535. this._stencilState.stencilFuncRef = reference;
  8536. };
  8537. Engine.prototype.setStencilFunctionMask = function (mask) {
  8538. this._stencilState.stencilFuncMask = mask;
  8539. };
  8540. Engine.prototype.getStencilOperationFail = function () {
  8541. return this._stencilState.stencilOpStencilFail;
  8542. };
  8543. Engine.prototype.getStencilOperationDepthFail = function () {
  8544. return this._stencilState.stencilOpDepthFail;
  8545. };
  8546. Engine.prototype.getStencilOperationPass = function () {
  8547. return this._stencilState.stencilOpStencilDepthPass;
  8548. };
  8549. Engine.prototype.setStencilOperationFail = function (operation) {
  8550. this._stencilState.stencilOpStencilFail = operation;
  8551. };
  8552. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8553. this._stencilState.stencilOpDepthFail = operation;
  8554. };
  8555. Engine.prototype.setStencilOperationPass = function (operation) {
  8556. this._stencilState.stencilOpStencilDepthPass = operation;
  8557. };
  8558. Engine.prototype.setDitheringState = function (value) {
  8559. if (value) {
  8560. this._gl.enable(this._gl.DITHER);
  8561. }
  8562. else {
  8563. this._gl.disable(this._gl.DITHER);
  8564. }
  8565. };
  8566. /**
  8567. * stop executing a render loop function and remove it from the execution array
  8568. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8569. */
  8570. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8571. if (!renderFunction) {
  8572. this._activeRenderLoops = [];
  8573. return;
  8574. }
  8575. var index = this._activeRenderLoops.indexOf(renderFunction);
  8576. if (index >= 0) {
  8577. this._activeRenderLoops.splice(index, 1);
  8578. }
  8579. };
  8580. Engine.prototype._renderLoop = function () {
  8581. if (!this._contextWasLost) {
  8582. var shouldRender = true;
  8583. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8584. shouldRender = false;
  8585. }
  8586. if (shouldRender) {
  8587. // Start new frame
  8588. this.beginFrame();
  8589. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8590. var renderFunction = this._activeRenderLoops[index];
  8591. renderFunction();
  8592. }
  8593. // Present
  8594. this.endFrame();
  8595. }
  8596. }
  8597. if (this._activeRenderLoops.length > 0) {
  8598. // Register new frame
  8599. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8600. }
  8601. else {
  8602. this._renderingQueueLaunched = false;
  8603. }
  8604. };
  8605. /**
  8606. * Register and execute a render loop. The engine can have more than one render function.
  8607. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8608. * @example
  8609. * engine.runRenderLoop(function () {
  8610. * scene.render()
  8611. * })
  8612. */
  8613. Engine.prototype.runRenderLoop = function (renderFunction) {
  8614. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8615. return;
  8616. }
  8617. this._activeRenderLoops.push(renderFunction);
  8618. if (!this._renderingQueueLaunched) {
  8619. this._renderingQueueLaunched = true;
  8620. this._bindedRenderFunction = this._renderLoop.bind(this);
  8621. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8622. }
  8623. };
  8624. /**
  8625. * Toggle full screen mode.
  8626. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8627. * @param {any} options - an options object to be sent to the requestFullscreen function
  8628. */
  8629. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8630. if (this.isFullscreen) {
  8631. BABYLON.Tools.ExitFullscreen();
  8632. }
  8633. else {
  8634. this._pointerLockRequested = requestPointerLock;
  8635. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8636. }
  8637. };
  8638. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8639. if (stencil === void 0) { stencil = false; }
  8640. this.applyStates();
  8641. var mode = 0;
  8642. if (backBuffer && color) {
  8643. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8644. mode |= this._gl.COLOR_BUFFER_BIT;
  8645. }
  8646. if (depth) {
  8647. this._gl.clearDepth(1.0);
  8648. mode |= this._gl.DEPTH_BUFFER_BIT;
  8649. }
  8650. if (stencil) {
  8651. this._gl.clearStencil(0);
  8652. mode |= this._gl.STENCIL_BUFFER_BIT;
  8653. }
  8654. this._gl.clear(mode);
  8655. };
  8656. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8657. var gl = this._gl;
  8658. // Save state
  8659. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8660. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8661. // Change state
  8662. gl.enable(gl.SCISSOR_TEST);
  8663. gl.scissor(x, y, width, height);
  8664. // Clear
  8665. this.clear(clearColor, true, true, true);
  8666. // Restore state
  8667. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8668. if (curScissor === true) {
  8669. gl.enable(gl.SCISSOR_TEST);
  8670. }
  8671. else {
  8672. gl.disable(gl.SCISSOR_TEST);
  8673. }
  8674. };
  8675. /**
  8676. * Set the WebGL's viewport
  8677. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8678. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8679. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8680. */
  8681. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8682. var width = requiredWidth || this.getRenderWidth();
  8683. var height = requiredHeight || this.getRenderHeight();
  8684. var x = viewport.x || 0;
  8685. var y = viewport.y || 0;
  8686. this._cachedViewport = viewport;
  8687. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8688. };
  8689. /**
  8690. * Directly set the WebGL Viewport
  8691. * The x, y, width & height are directly passed to the WebGL call
  8692. * @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.
  8693. */
  8694. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8695. var currentViewport = this._cachedViewport;
  8696. this._cachedViewport = null;
  8697. this._gl.viewport(x, y, width, height);
  8698. return currentViewport;
  8699. };
  8700. Engine.prototype.beginFrame = function () {
  8701. this._measureFps();
  8702. };
  8703. Engine.prototype.endFrame = function () {
  8704. //force a flush in case we are using a bad OS.
  8705. if (this._badOS) {
  8706. this.flushFramebuffer();
  8707. }
  8708. //submit frame to the vr device, if enabled
  8709. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8710. this._vrDisplayEnabled.submitFrame();
  8711. }
  8712. };
  8713. /**
  8714. * resize the view according to the canvas' size.
  8715. * @example
  8716. * window.addEventListener("resize", function () {
  8717. * engine.resize();
  8718. * });
  8719. */
  8720. Engine.prototype.resize = function () {
  8721. // We're not resizing the size of the canvas while in VR mode & presenting
  8722. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8723. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8724. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8725. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8726. }
  8727. };
  8728. /**
  8729. * force a specific size of the canvas
  8730. * @param {number} width - the new canvas' width
  8731. * @param {number} height - the new canvas' height
  8732. */
  8733. Engine.prototype.setSize = function (width, height) {
  8734. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8735. return;
  8736. }
  8737. this._renderingCanvas.width = width;
  8738. this._renderingCanvas.height = height;
  8739. for (var index = 0; index < this.scenes.length; index++) {
  8740. var scene = this.scenes[index];
  8741. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8742. var cam = scene.cameras[camIndex];
  8743. cam._currentRenderId = 0;
  8744. }
  8745. }
  8746. if (this.onResizeObservable.hasObservers) {
  8747. this.onResizeObservable.notifyObservers(this);
  8748. }
  8749. };
  8750. //WebVR functions
  8751. Engine.prototype.isVRDevicePresent = function (callback) {
  8752. this.getVRDevice(null, function (device) {
  8753. callback(device !== null);
  8754. });
  8755. };
  8756. Engine.prototype.getVRDevice = function (name, callback) {
  8757. if (!this.vrDisplaysPromise) {
  8758. callback(null);
  8759. return;
  8760. }
  8761. this.vrDisplaysPromise.then(function (devices) {
  8762. if (devices.length > 0) {
  8763. if (name) {
  8764. var found = devices.some(function (device) {
  8765. if (device.displayName === name) {
  8766. callback(device);
  8767. return true;
  8768. }
  8769. else {
  8770. return false;
  8771. }
  8772. });
  8773. if (!found) {
  8774. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8775. callback(devices[0]);
  8776. }
  8777. }
  8778. else {
  8779. //choose the first one
  8780. callback(devices[0]);
  8781. }
  8782. }
  8783. else {
  8784. BABYLON.Tools.Error("No WebVR devices found!");
  8785. callback(null);
  8786. }
  8787. });
  8788. };
  8789. Engine.prototype.initWebVR = function () {
  8790. if (!this.vrDisplaysPromise) {
  8791. this._getVRDisplays();
  8792. }
  8793. };
  8794. Engine.prototype.enableVR = function (vrDevice) {
  8795. this._vrDisplayEnabled = vrDevice;
  8796. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8797. };
  8798. Engine.prototype.disableVR = function () {
  8799. if (this._vrDisplayEnabled) {
  8800. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8801. }
  8802. };
  8803. Engine.prototype._getVRDisplays = function () {
  8804. var _this = this;
  8805. var getWebVRDevices = function (devices) {
  8806. _this._vrDisplays = devices.filter(function (device) {
  8807. return device instanceof VRDisplay;
  8808. });
  8809. return _this._vrDisplays;
  8810. };
  8811. if (navigator.getVRDisplays) {
  8812. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8813. }
  8814. };
  8815. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8816. if (this._currentRenderTarget) {
  8817. this.unBindFramebuffer(this._currentRenderTarget);
  8818. }
  8819. this._currentRenderTarget = texture;
  8820. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8821. var gl = this._gl;
  8822. if (texture.isCube) {
  8823. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8824. }
  8825. if (this._cachedViewport && !forceFullscreenViewport) {
  8826. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8827. }
  8828. else {
  8829. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8830. }
  8831. this.wipeCaches();
  8832. };
  8833. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8834. if (this._currentFramebuffer !== framebuffer) {
  8835. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8836. this._currentFramebuffer = framebuffer;
  8837. }
  8838. };
  8839. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8840. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8841. this._currentRenderTarget = null;
  8842. // If MSAA, we need to bitblt back to main texture
  8843. var gl = this._gl;
  8844. if (texture._MSAAFramebuffer) {
  8845. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8846. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8847. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8848. }
  8849. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8850. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8851. gl.generateMipmap(gl.TEXTURE_2D);
  8852. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8853. }
  8854. if (onBeforeUnbind) {
  8855. if (texture._MSAAFramebuffer) {
  8856. // Bind the correct framebuffer
  8857. this.bindUnboundFramebuffer(texture._framebuffer);
  8858. }
  8859. onBeforeUnbind();
  8860. }
  8861. this.bindUnboundFramebuffer(null);
  8862. };
  8863. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8864. if (texture.generateMipMaps) {
  8865. var gl = this._gl;
  8866. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8867. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8868. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8869. }
  8870. };
  8871. Engine.prototype.flushFramebuffer = function () {
  8872. this._gl.flush();
  8873. };
  8874. Engine.prototype.restoreDefaultFramebuffer = function () {
  8875. if (this._currentRenderTarget) {
  8876. this.unBindFramebuffer(this._currentRenderTarget);
  8877. }
  8878. else {
  8879. this.bindUnboundFramebuffer(null);
  8880. }
  8881. if (this._cachedViewport) {
  8882. this.setViewport(this._cachedViewport);
  8883. }
  8884. this.wipeCaches();
  8885. };
  8886. // UBOs
  8887. Engine.prototype.createUniformBuffer = function (elements) {
  8888. var ubo = this._gl.createBuffer();
  8889. this.bindUniformBuffer(ubo);
  8890. if (elements instanceof Float32Array) {
  8891. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8892. }
  8893. else {
  8894. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8895. }
  8896. this.bindUniformBuffer(null);
  8897. ubo.references = 1;
  8898. return ubo;
  8899. };
  8900. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8901. var ubo = this._gl.createBuffer();
  8902. this.bindUniformBuffer(ubo);
  8903. if (elements instanceof Float32Array) {
  8904. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8905. }
  8906. else {
  8907. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8908. }
  8909. this.bindUniformBuffer(null);
  8910. ubo.references = 1;
  8911. return ubo;
  8912. };
  8913. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8914. this.bindUniformBuffer(uniformBuffer);
  8915. if (offset === undefined) {
  8916. offset = 0;
  8917. }
  8918. if (count === undefined) {
  8919. if (elements instanceof Float32Array) {
  8920. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8921. }
  8922. else {
  8923. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8924. }
  8925. }
  8926. else {
  8927. if (elements instanceof Float32Array) {
  8928. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8929. }
  8930. else {
  8931. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8932. }
  8933. }
  8934. this.bindUniformBuffer(null);
  8935. };
  8936. // VBOs
  8937. Engine.prototype._resetVertexBufferBinding = function () {
  8938. this.bindArrayBuffer(null);
  8939. this._cachedVertexBuffers = null;
  8940. };
  8941. Engine.prototype.createVertexBuffer = function (vertices) {
  8942. var vbo = this._gl.createBuffer();
  8943. this.bindArrayBuffer(vbo);
  8944. if (vertices instanceof Float32Array) {
  8945. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8946. }
  8947. else {
  8948. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8949. }
  8950. this._resetVertexBufferBinding();
  8951. vbo.references = 1;
  8952. return vbo;
  8953. };
  8954. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8955. var vbo = this._gl.createBuffer();
  8956. this.bindArrayBuffer(vbo);
  8957. if (vertices instanceof Float32Array) {
  8958. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8959. }
  8960. else {
  8961. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8962. }
  8963. this._resetVertexBufferBinding();
  8964. vbo.references = 1;
  8965. return vbo;
  8966. };
  8967. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8968. this.bindArrayBuffer(vertexBuffer);
  8969. if (offset === undefined) {
  8970. offset = 0;
  8971. }
  8972. if (count === undefined) {
  8973. if (vertices instanceof Float32Array) {
  8974. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8975. }
  8976. else {
  8977. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8978. }
  8979. }
  8980. else {
  8981. if (vertices instanceof Float32Array) {
  8982. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8983. }
  8984. else {
  8985. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8986. }
  8987. }
  8988. this._resetVertexBufferBinding();
  8989. };
  8990. Engine.prototype._resetIndexBufferBinding = function () {
  8991. this.bindIndexBuffer(null);
  8992. this._cachedIndexBuffer = null;
  8993. };
  8994. Engine.prototype.createIndexBuffer = function (indices) {
  8995. var vbo = this._gl.createBuffer();
  8996. this.bindIndexBuffer(vbo);
  8997. // Check for 32 bits indices
  8998. var arrayBuffer;
  8999. var need32Bits = false;
  9000. if (indices instanceof Uint16Array) {
  9001. arrayBuffer = indices;
  9002. }
  9003. else {
  9004. //check 32 bit support
  9005. if (this._caps.uintIndices) {
  9006. if (indices instanceof Uint32Array) {
  9007. arrayBuffer = indices;
  9008. need32Bits = true;
  9009. }
  9010. else {
  9011. //number[] or Int32Array, check if 32 bit is necessary
  9012. for (var index = 0; index < indices.length; index++) {
  9013. if (indices[index] > 65535) {
  9014. need32Bits = true;
  9015. break;
  9016. }
  9017. }
  9018. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9019. }
  9020. }
  9021. else {
  9022. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9023. arrayBuffer = new Uint16Array(indices);
  9024. }
  9025. }
  9026. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9027. this._resetIndexBufferBinding();
  9028. vbo.references = 1;
  9029. vbo.is32Bits = need32Bits;
  9030. return vbo;
  9031. };
  9032. Engine.prototype.bindArrayBuffer = function (buffer) {
  9033. if (!this._vaoRecordInProgress) {
  9034. this._unbindVertexArrayObject();
  9035. }
  9036. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9037. };
  9038. Engine.prototype.bindUniformBuffer = function (buffer) {
  9039. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9040. };
  9041. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9042. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9043. };
  9044. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9045. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9046. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9047. };
  9048. ;
  9049. Engine.prototype.bindIndexBuffer = function (buffer) {
  9050. if (!this._vaoRecordInProgress) {
  9051. this._unbindVertexArrayObject();
  9052. }
  9053. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9054. };
  9055. Engine.prototype.bindBuffer = function (buffer, target) {
  9056. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9057. this._gl.bindBuffer(target, buffer);
  9058. this._currentBoundBuffer[target] = buffer;
  9059. }
  9060. };
  9061. Engine.prototype.updateArrayBuffer = function (data) {
  9062. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9063. };
  9064. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9065. var pointer = this._currentBufferPointers[indx];
  9066. var changed = false;
  9067. if (!pointer.active) {
  9068. changed = true;
  9069. pointer.active = true;
  9070. pointer.index = indx;
  9071. pointer.size = size;
  9072. pointer.type = type;
  9073. pointer.normalized = normalized;
  9074. pointer.stride = stride;
  9075. pointer.offset = offset;
  9076. pointer.buffer = buffer;
  9077. }
  9078. else {
  9079. if (pointer.buffer !== buffer) {
  9080. pointer.buffer = buffer;
  9081. changed = true;
  9082. }
  9083. if (pointer.size !== size) {
  9084. pointer.size = size;
  9085. changed = true;
  9086. }
  9087. if (pointer.type !== type) {
  9088. pointer.type = type;
  9089. changed = true;
  9090. }
  9091. if (pointer.normalized !== normalized) {
  9092. pointer.normalized = normalized;
  9093. changed = true;
  9094. }
  9095. if (pointer.stride !== stride) {
  9096. pointer.stride = stride;
  9097. changed = true;
  9098. }
  9099. if (pointer.offset !== offset) {
  9100. pointer.offset = offset;
  9101. changed = true;
  9102. }
  9103. }
  9104. if (changed || this._vaoRecordInProgress) {
  9105. this.bindArrayBuffer(buffer);
  9106. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9107. }
  9108. };
  9109. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9110. if (indexBuffer == null) {
  9111. return;
  9112. }
  9113. if (this._cachedIndexBuffer !== indexBuffer) {
  9114. this._cachedIndexBuffer = indexBuffer;
  9115. this.bindIndexBuffer(indexBuffer);
  9116. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9117. }
  9118. };
  9119. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9120. var attributes = effect.getAttributesNames();
  9121. if (!this._vaoRecordInProgress) {
  9122. this._unbindVertexArrayObject();
  9123. }
  9124. this.unbindAllAttributes();
  9125. for (var index = 0; index < attributes.length; index++) {
  9126. var order = effect.getAttributeLocation(index);
  9127. if (order >= 0) {
  9128. var vertexBuffer = vertexBuffers[attributes[index]];
  9129. if (!vertexBuffer) {
  9130. continue;
  9131. }
  9132. this._gl.enableVertexAttribArray(order);
  9133. if (!this._vaoRecordInProgress) {
  9134. this._vertexAttribArraysEnabled[order] = true;
  9135. }
  9136. var buffer = vertexBuffer.getBuffer();
  9137. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9138. if (vertexBuffer.getIsInstanced()) {
  9139. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9140. if (!this._vaoRecordInProgress) {
  9141. this._currentInstanceLocations.push(order);
  9142. this._currentInstanceBuffers.push(buffer);
  9143. }
  9144. }
  9145. }
  9146. }
  9147. };
  9148. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9149. var vao = this._gl.createVertexArray();
  9150. this._vaoRecordInProgress = true;
  9151. this._gl.bindVertexArray(vao);
  9152. this._mustWipeVertexAttributes = true;
  9153. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9154. this.bindIndexBuffer(indexBuffer);
  9155. this._vaoRecordInProgress = false;
  9156. this._gl.bindVertexArray(null);
  9157. return vao;
  9158. };
  9159. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9160. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9161. this._cachedVertexArrayObject = vertexArrayObject;
  9162. this._gl.bindVertexArray(vertexArrayObject);
  9163. this._cachedVertexBuffers = null;
  9164. this._cachedIndexBuffer = null;
  9165. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9166. this._mustWipeVertexAttributes = true;
  9167. }
  9168. };
  9169. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9170. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9171. this._cachedVertexBuffers = vertexBuffer;
  9172. this._cachedEffectForVertexBuffers = effect;
  9173. var attributesCount = effect.getAttributesCount();
  9174. this._unbindVertexArrayObject();
  9175. this.unbindAllAttributes();
  9176. var offset = 0;
  9177. for (var index = 0; index < attributesCount; index++) {
  9178. if (index < vertexDeclaration.length) {
  9179. var order = effect.getAttributeLocation(index);
  9180. if (order >= 0) {
  9181. this._gl.enableVertexAttribArray(order);
  9182. this._vertexAttribArraysEnabled[order] = true;
  9183. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9184. }
  9185. offset += vertexDeclaration[index] * 4;
  9186. }
  9187. }
  9188. }
  9189. this._bindIndexBufferWithCache(indexBuffer);
  9190. };
  9191. Engine.prototype._unbindVertexArrayObject = function () {
  9192. if (!this._cachedVertexArrayObject) {
  9193. return;
  9194. }
  9195. this._cachedVertexArrayObject = null;
  9196. this._gl.bindVertexArray(null);
  9197. };
  9198. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9199. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9200. this._cachedVertexBuffers = vertexBuffers;
  9201. this._cachedEffectForVertexBuffers = effect;
  9202. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9203. }
  9204. this._bindIndexBufferWithCache(indexBuffer);
  9205. };
  9206. Engine.prototype.unbindInstanceAttributes = function () {
  9207. var boundBuffer;
  9208. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9209. var instancesBuffer = this._currentInstanceBuffers[i];
  9210. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9211. boundBuffer = instancesBuffer;
  9212. this.bindArrayBuffer(instancesBuffer);
  9213. }
  9214. var offsetLocation = this._currentInstanceLocations[i];
  9215. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9216. }
  9217. this._currentInstanceBuffers.length = 0;
  9218. this._currentInstanceLocations.length = 0;
  9219. };
  9220. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9221. this._gl.deleteVertexArray(vao);
  9222. };
  9223. Engine.prototype._releaseBuffer = function (buffer) {
  9224. buffer.references--;
  9225. if (buffer.references === 0) {
  9226. this._gl.deleteBuffer(buffer);
  9227. return true;
  9228. }
  9229. return false;
  9230. };
  9231. Engine.prototype.createInstancesBuffer = function (capacity) {
  9232. var buffer = this._gl.createBuffer();
  9233. buffer.capacity = capacity;
  9234. this.bindArrayBuffer(buffer);
  9235. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9236. return buffer;
  9237. };
  9238. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9239. this._gl.deleteBuffer(buffer);
  9240. };
  9241. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9242. this.bindArrayBuffer(instancesBuffer);
  9243. if (data) {
  9244. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9245. }
  9246. if (offsetLocations[0].index !== undefined) {
  9247. var stride = 0;
  9248. for (var i = 0; i < offsetLocations.length; i++) {
  9249. var ai = offsetLocations[i];
  9250. stride += ai.attributeSize * 4;
  9251. }
  9252. for (var i = 0; i < offsetLocations.length; i++) {
  9253. var ai = offsetLocations[i];
  9254. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9255. this._gl.enableVertexAttribArray(ai.index);
  9256. this._vertexAttribArraysEnabled[ai.index] = true;
  9257. }
  9258. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9259. this._gl.vertexAttribDivisor(ai.index, 1);
  9260. this._currentInstanceLocations.push(ai.index);
  9261. this._currentInstanceBuffers.push(instancesBuffer);
  9262. }
  9263. }
  9264. else {
  9265. for (var index = 0; index < 4; index++) {
  9266. var offsetLocation = offsetLocations[index];
  9267. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9268. this._gl.enableVertexAttribArray(offsetLocation);
  9269. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9270. }
  9271. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9272. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9273. this._currentInstanceLocations.push(offsetLocation);
  9274. this._currentInstanceBuffers.push(instancesBuffer);
  9275. }
  9276. }
  9277. };
  9278. Engine.prototype.applyStates = function () {
  9279. this._depthCullingState.apply(this._gl);
  9280. this._stencilState.apply(this._gl);
  9281. this._alphaState.apply(this._gl);
  9282. };
  9283. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9284. // Apply states
  9285. this.applyStates();
  9286. this._drawCalls.addCount(1, false);
  9287. // Render
  9288. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9289. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9290. if (instancesCount) {
  9291. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9292. return;
  9293. }
  9294. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9295. };
  9296. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9297. // Apply states
  9298. this.applyStates();
  9299. this._drawCalls.addCount(1, false);
  9300. if (instancesCount) {
  9301. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9302. return;
  9303. }
  9304. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9305. };
  9306. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9307. // Apply states
  9308. this.applyStates();
  9309. this._drawCalls.addCount(1, false);
  9310. if (instancesCount) {
  9311. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9312. return;
  9313. }
  9314. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9315. };
  9316. // Shaders
  9317. Engine.prototype._releaseEffect = function (effect) {
  9318. if (this._compiledEffects[effect._key]) {
  9319. delete this._compiledEffects[effect._key];
  9320. if (effect.getProgram()) {
  9321. this._gl.deleteProgram(effect.getProgram());
  9322. }
  9323. }
  9324. };
  9325. /**
  9326. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9327. * @param samplers An array of string used to represent textures
  9328. */
  9329. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9330. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9331. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9332. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9333. if (this._compiledEffects[name]) {
  9334. var compiledEffect = this._compiledEffects[name];
  9335. if (onCompiled && compiledEffect.isReady()) {
  9336. onCompiled(compiledEffect);
  9337. }
  9338. return compiledEffect;
  9339. }
  9340. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9341. effect._key = name;
  9342. this._compiledEffects[name] = effect;
  9343. return effect;
  9344. };
  9345. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9346. if (uniformsNames === void 0) { uniformsNames = []; }
  9347. if (samplers === void 0) { samplers = []; }
  9348. if (defines === void 0) { defines = ""; }
  9349. return this.createEffect({
  9350. vertex: "particles",
  9351. fragmentElement: fragmentName
  9352. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9353. };
  9354. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9355. context = context || this._gl;
  9356. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9357. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9358. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9359. var shaderProgram = context.createProgram();
  9360. context.attachShader(shaderProgram, vertexShader);
  9361. context.attachShader(shaderProgram, fragmentShader);
  9362. context.linkProgram(shaderProgram);
  9363. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9364. if (!linked) {
  9365. context.validateProgram(shaderProgram);
  9366. var error = context.getProgramInfoLog(shaderProgram);
  9367. if (error) {
  9368. throw new Error(error);
  9369. }
  9370. }
  9371. context.deleteShader(vertexShader);
  9372. context.deleteShader(fragmentShader);
  9373. return shaderProgram;
  9374. };
  9375. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9376. var results = [];
  9377. for (var index = 0; index < uniformsNames.length; index++) {
  9378. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9379. }
  9380. return results;
  9381. };
  9382. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9383. var results = [];
  9384. for (var index = 0; index < attributesNames.length; index++) {
  9385. try {
  9386. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9387. }
  9388. catch (e) {
  9389. results.push(-1);
  9390. }
  9391. }
  9392. return results;
  9393. };
  9394. Engine.prototype.enableEffect = function (effect) {
  9395. // Use program
  9396. this.setProgram(effect.getProgram());
  9397. this._currentEffect = effect;
  9398. if (effect.onBind) {
  9399. effect.onBind(effect);
  9400. }
  9401. effect.onBindObservable.notifyObservers(effect);
  9402. };
  9403. Engine.prototype.setIntArray = function (uniform, array) {
  9404. if (!uniform)
  9405. return;
  9406. this._gl.uniform1iv(uniform, array);
  9407. };
  9408. Engine.prototype.setIntArray2 = function (uniform, array) {
  9409. if (!uniform || array.length % 2 !== 0)
  9410. return;
  9411. this._gl.uniform2iv(uniform, array);
  9412. };
  9413. Engine.prototype.setIntArray3 = function (uniform, array) {
  9414. if (!uniform || array.length % 3 !== 0)
  9415. return;
  9416. this._gl.uniform3iv(uniform, array);
  9417. };
  9418. Engine.prototype.setIntArray4 = function (uniform, array) {
  9419. if (!uniform || array.length % 4 !== 0)
  9420. return;
  9421. this._gl.uniform4iv(uniform, array);
  9422. };
  9423. Engine.prototype.setFloatArray = function (uniform, array) {
  9424. if (!uniform)
  9425. return;
  9426. this._gl.uniform1fv(uniform, array);
  9427. };
  9428. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9429. if (!uniform || array.length % 2 !== 0)
  9430. return;
  9431. this._gl.uniform2fv(uniform, array);
  9432. };
  9433. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9434. if (!uniform || array.length % 3 !== 0)
  9435. return;
  9436. this._gl.uniform3fv(uniform, array);
  9437. };
  9438. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9439. if (!uniform || array.length % 4 !== 0)
  9440. return;
  9441. this._gl.uniform4fv(uniform, array);
  9442. };
  9443. Engine.prototype.setArray = function (uniform, array) {
  9444. if (!uniform)
  9445. return;
  9446. this._gl.uniform1fv(uniform, array);
  9447. };
  9448. Engine.prototype.setArray2 = function (uniform, array) {
  9449. if (!uniform || array.length % 2 !== 0)
  9450. return;
  9451. this._gl.uniform2fv(uniform, array);
  9452. };
  9453. Engine.prototype.setArray3 = function (uniform, array) {
  9454. if (!uniform || array.length % 3 !== 0)
  9455. return;
  9456. this._gl.uniform3fv(uniform, array);
  9457. };
  9458. Engine.prototype.setArray4 = function (uniform, array) {
  9459. if (!uniform || array.length % 4 !== 0)
  9460. return;
  9461. this._gl.uniform4fv(uniform, array);
  9462. };
  9463. Engine.prototype.setMatrices = function (uniform, matrices) {
  9464. if (!uniform)
  9465. return;
  9466. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9467. };
  9468. Engine.prototype.setMatrix = function (uniform, matrix) {
  9469. if (!uniform)
  9470. return;
  9471. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9472. };
  9473. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9474. if (!uniform)
  9475. return;
  9476. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9477. };
  9478. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9479. if (!uniform)
  9480. return;
  9481. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9482. };
  9483. Engine.prototype.setFloat = function (uniform, value) {
  9484. if (!uniform)
  9485. return;
  9486. this._gl.uniform1f(uniform, value);
  9487. };
  9488. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9489. if (!uniform)
  9490. return;
  9491. this._gl.uniform2f(uniform, x, y);
  9492. };
  9493. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9494. if (!uniform)
  9495. return;
  9496. this._gl.uniform3f(uniform, x, y, z);
  9497. };
  9498. Engine.prototype.setBool = function (uniform, bool) {
  9499. if (!uniform)
  9500. return;
  9501. this._gl.uniform1i(uniform, bool);
  9502. };
  9503. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9504. if (!uniform)
  9505. return;
  9506. this._gl.uniform4f(uniform, x, y, z, w);
  9507. };
  9508. Engine.prototype.setColor3 = function (uniform, color3) {
  9509. if (!uniform)
  9510. return;
  9511. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9512. };
  9513. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9514. if (!uniform)
  9515. return;
  9516. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9517. };
  9518. // States
  9519. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9520. if (zOffset === void 0) { zOffset = 0; }
  9521. if (reverseSide === void 0) { reverseSide = false; }
  9522. // Culling
  9523. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9524. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9525. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9526. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9527. if (culling) {
  9528. this._depthCullingState.cullFace = cullFace;
  9529. this._depthCullingState.cull = true;
  9530. }
  9531. else {
  9532. this._depthCullingState.cull = false;
  9533. }
  9534. }
  9535. // Z offset
  9536. this.setZOffset(zOffset);
  9537. };
  9538. Engine.prototype.setZOffset = function (value) {
  9539. this._depthCullingState.zOffset = value;
  9540. };
  9541. Engine.prototype.getZOffset = function () {
  9542. return this._depthCullingState.zOffset;
  9543. };
  9544. Engine.prototype.setDepthBuffer = function (enable) {
  9545. this._depthCullingState.depthTest = enable;
  9546. };
  9547. Engine.prototype.getDepthWrite = function () {
  9548. return this._depthCullingState.depthMask;
  9549. };
  9550. Engine.prototype.setDepthWrite = function (enable) {
  9551. this._depthCullingState.depthMask = enable;
  9552. };
  9553. Engine.prototype.setColorWrite = function (enable) {
  9554. this._gl.colorMask(enable, enable, enable, enable);
  9555. };
  9556. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9557. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9558. };
  9559. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9560. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9561. if (this._alphaMode === mode) {
  9562. return;
  9563. }
  9564. switch (mode) {
  9565. case Engine.ALPHA_DISABLE:
  9566. this._alphaState.alphaBlend = false;
  9567. break;
  9568. case Engine.ALPHA_PREMULTIPLIED:
  9569. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9570. this._alphaState.alphaBlend = true;
  9571. break;
  9572. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9573. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9574. this._alphaState.alphaBlend = true;
  9575. break;
  9576. case Engine.ALPHA_COMBINE:
  9577. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9578. this._alphaState.alphaBlend = true;
  9579. break;
  9580. case Engine.ALPHA_ONEONE:
  9581. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9582. this._alphaState.alphaBlend = true;
  9583. break;
  9584. case Engine.ALPHA_ADD:
  9585. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9586. this._alphaState.alphaBlend = true;
  9587. break;
  9588. case Engine.ALPHA_SUBTRACT:
  9589. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9590. this._alphaState.alphaBlend = true;
  9591. break;
  9592. case Engine.ALPHA_MULTIPLY:
  9593. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9594. this._alphaState.alphaBlend = true;
  9595. break;
  9596. case Engine.ALPHA_MAXIMIZED:
  9597. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9598. this._alphaState.alphaBlend = true;
  9599. break;
  9600. case Engine.ALPHA_INTERPOLATE:
  9601. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9602. this._alphaState.alphaBlend = true;
  9603. break;
  9604. case Engine.ALPHA_SCREENMODE:
  9605. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9606. this._alphaState.alphaBlend = true;
  9607. break;
  9608. }
  9609. if (!noDepthWriteChange) {
  9610. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9611. }
  9612. this._alphaMode = mode;
  9613. };
  9614. Engine.prototype.getAlphaMode = function () {
  9615. return this._alphaMode;
  9616. };
  9617. Engine.prototype.setAlphaTesting = function (enable) {
  9618. this._alphaTest = enable;
  9619. };
  9620. Engine.prototype.getAlphaTesting = function () {
  9621. return !!this._alphaTest;
  9622. };
  9623. // Textures
  9624. Engine.prototype.wipeCaches = function (bruteForce) {
  9625. if (this.preventCacheWipeBetweenFrames) {
  9626. return;
  9627. }
  9628. this.resetTextureCache();
  9629. this._currentEffect = null;
  9630. // 6/8/2017: deltakosh: Should not be required anymore.
  9631. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9632. if (bruteForce) {
  9633. this._currentProgram = null;
  9634. this._stencilState.reset();
  9635. this._depthCullingState.reset();
  9636. this.setDepthFunctionToLessOrEqual();
  9637. this._alphaState.reset();
  9638. }
  9639. this._cachedVertexBuffers = null;
  9640. this._cachedIndexBuffer = null;
  9641. this._cachedEffectForVertexBuffers = null;
  9642. this._unbindVertexArrayObject();
  9643. this.bindIndexBuffer(null);
  9644. this.bindArrayBuffer(null);
  9645. };
  9646. /**
  9647. * Set the compressed texture format to use, based on the formats you have, and the formats
  9648. * supported by the hardware / browser.
  9649. *
  9650. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9651. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9652. * to API arguments needed to compressed textures. This puts the burden on the container
  9653. * generator to house the arcane code for determining these for current & future formats.
  9654. *
  9655. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9656. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9657. *
  9658. * Note: The result of this call is not taken into account when a texture is base64.
  9659. *
  9660. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9661. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9662. *
  9663. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9664. * @returns The extension selected.
  9665. */
  9666. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9667. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9668. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9669. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9670. return this._textureFormatInUse = this._texturesSupported[i];
  9671. }
  9672. }
  9673. }
  9674. // actively set format to nothing, to allow this to be called more than once
  9675. // and possibly fail the 2nd time
  9676. return this._textureFormatInUse = null;
  9677. };
  9678. Engine.prototype._createTexture = function () {
  9679. return this._gl.createTexture();
  9680. };
  9681. /**
  9682. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9683. * @param {string} urlArg- This contains one of the following:
  9684. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9685. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9686. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9687. *
  9688. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9689. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9690. * @param {Scene} scene- Needed for loading to the correct scene.
  9691. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9692. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9693. * @param {callback} onError- Optional callback to be called upon failure.
  9694. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9695. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9696. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9697. *
  9698. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9699. */
  9700. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9701. var _this = this;
  9702. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9703. if (onLoad === void 0) { onLoad = null; }
  9704. if (onError === void 0) { onError = null; }
  9705. if (buffer === void 0) { buffer = null; }
  9706. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9707. var fromData = url.substr(0, 5) === "data:";
  9708. var fromBlob = url.substr(0, 5) === "blob:";
  9709. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9710. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9711. // establish the file extension, if possible
  9712. var lastDot = url.lastIndexOf('.');
  9713. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9714. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9715. var isTGA = (extension === ".tga");
  9716. // determine if a ktx file should be substituted
  9717. var isKTX = false;
  9718. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9719. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9720. isKTX = true;
  9721. }
  9722. if (scene) {
  9723. scene._addPendingData(texture);
  9724. }
  9725. texture.url = url;
  9726. texture.generateMipMaps = !noMipmap;
  9727. texture.samplingMode = samplingMode;
  9728. texture.invertY = invertY;
  9729. if (!this._doNotHandleContextLost) {
  9730. // Keep a link to the buffer only if we plan to handle context lost
  9731. texture._buffer = buffer;
  9732. }
  9733. if (onLoad) {
  9734. texture.onLoadedObservable.add(onLoad);
  9735. }
  9736. if (!fallBack)
  9737. this._internalTexturesCache.push(texture);
  9738. var onerror = function () {
  9739. if (scene) {
  9740. scene._removePendingData(texture);
  9741. }
  9742. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9743. if (isKTX) {
  9744. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9745. }
  9746. else if (onError) {
  9747. onError();
  9748. }
  9749. };
  9750. var callback;
  9751. // processing for non-image formats
  9752. if (isKTX || isTGA || isDDS) {
  9753. if (isKTX) {
  9754. callback = function (data) {
  9755. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9756. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9757. ktx.uploadLevels(_this._gl, !noMipmap);
  9758. return false;
  9759. }, samplingMode);
  9760. };
  9761. }
  9762. else if (isTGA) {
  9763. callback = function (arrayBuffer) {
  9764. var data = new Uint8Array(arrayBuffer);
  9765. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9766. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9767. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9768. return false;
  9769. }, samplingMode);
  9770. };
  9771. }
  9772. else if (isDDS) {
  9773. callback = function (data) {
  9774. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9775. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9776. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9777. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9778. return false;
  9779. }, samplingMode);
  9780. };
  9781. }
  9782. if (!buffer) {
  9783. BABYLON.Tools.LoadFile(url, function (data) {
  9784. callback(data);
  9785. }, null, scene ? scene.database : null, true, onerror);
  9786. }
  9787. else {
  9788. callback(buffer);
  9789. }
  9790. // image format processing
  9791. }
  9792. else {
  9793. var onload = function (img) {
  9794. if (fromBlob && !_this._doNotHandleContextLost) {
  9795. // We need to store the image if we need to rebuild the texture
  9796. // in case of a webgl context lost
  9797. texture._buffer = img;
  9798. }
  9799. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9800. var gl = _this._gl;
  9801. var isPot = (img.width === potWidth && img.height === potHeight);
  9802. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9803. if (isPot) {
  9804. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9805. return false;
  9806. }
  9807. // Using shaders to rescale because canvas.drawImage is lossy
  9808. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9809. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9810. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9811. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9812. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9814. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9815. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9816. _this._releaseTexture(source);
  9817. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9818. continuationCallback();
  9819. });
  9820. return true;
  9821. }, samplingMode);
  9822. };
  9823. if (!fromData || isBase64)
  9824. if (buffer instanceof HTMLImageElement) {
  9825. onload(buffer);
  9826. }
  9827. else {
  9828. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9829. }
  9830. else if (buffer instanceof Array || typeof buffer === "string")
  9831. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9832. else
  9833. onload(buffer);
  9834. }
  9835. return texture;
  9836. };
  9837. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9838. var _this = this;
  9839. var rtt = this.createRenderTargetTexture({
  9840. width: destination.width,
  9841. height: destination.height,
  9842. }, {
  9843. generateMipMaps: false,
  9844. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9845. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9846. generateDepthBuffer: false,
  9847. generateStencilBuffer: false
  9848. });
  9849. if (!this._rescalePostProcess) {
  9850. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9851. }
  9852. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9853. _this._rescalePostProcess.onApply = function (effect) {
  9854. effect._bindTexture("textureSampler", source);
  9855. };
  9856. scene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9857. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9858. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9859. _this.unBindFramebuffer(rtt);
  9860. _this._releaseTexture(rtt);
  9861. if (onComplete) {
  9862. onComplete();
  9863. }
  9864. });
  9865. };
  9866. Engine.prototype._getInternalFormat = function (format) {
  9867. var internalFormat = this._gl.RGBA;
  9868. switch (format) {
  9869. case Engine.TEXTUREFORMAT_ALPHA:
  9870. internalFormat = this._gl.ALPHA;
  9871. break;
  9872. case Engine.TEXTUREFORMAT_LUMINANCE:
  9873. internalFormat = this._gl.LUMINANCE;
  9874. break;
  9875. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9876. internalFormat = this._gl.LUMINANCE_ALPHA;
  9877. break;
  9878. case Engine.TEXTUREFORMAT_RGB:
  9879. internalFormat = this._gl.RGB;
  9880. break;
  9881. case Engine.TEXTUREFORMAT_RGBA:
  9882. internalFormat = this._gl.RGBA;
  9883. break;
  9884. }
  9885. return internalFormat;
  9886. };
  9887. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9888. if (compression === void 0) { compression = null; }
  9889. var internalFormat = this._getInternalFormat(format);
  9890. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9891. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9892. if (!this._doNotHandleContextLost) {
  9893. texture._bufferView = data;
  9894. texture.format = format;
  9895. texture.invertY = invertY;
  9896. texture._compression = compression;
  9897. }
  9898. if (texture.width % 4 !== 0) {
  9899. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9900. }
  9901. if (compression) {
  9902. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9903. }
  9904. else {
  9905. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9906. }
  9907. if (texture.generateMipMaps) {
  9908. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9909. }
  9910. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9911. this.resetTextureCache();
  9912. texture.isReady = true;
  9913. };
  9914. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9915. if (compression === void 0) { compression = null; }
  9916. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9917. texture.baseWidth = width;
  9918. texture.baseHeight = height;
  9919. texture.width = width;
  9920. texture.height = height;
  9921. texture.format = format;
  9922. texture.generateMipMaps = generateMipMaps;
  9923. texture.samplingMode = samplingMode;
  9924. texture.invertY = invertY;
  9925. texture._compression = compression;
  9926. if (!this._doNotHandleContextLost) {
  9927. texture._bufferView = data;
  9928. }
  9929. this.updateRawTexture(texture, data, format, invertY, compression);
  9930. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9931. // Filters
  9932. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9933. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9934. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9935. if (generateMipMaps) {
  9936. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9937. }
  9938. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9939. this._internalTexturesCache.push(texture);
  9940. return texture;
  9941. };
  9942. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9943. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  9944. texture.baseWidth = width;
  9945. texture.baseHeight = height;
  9946. if (generateMipMaps) {
  9947. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9948. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9949. }
  9950. this.resetTextureCache();
  9951. texture.width = width;
  9952. texture.height = height;
  9953. texture.isReady = false;
  9954. texture.generateMipMaps = generateMipMaps;
  9955. texture.samplingMode = samplingMode;
  9956. this.updateTextureSamplingMode(samplingMode, texture);
  9957. this._internalTexturesCache.push(texture);
  9958. return texture;
  9959. };
  9960. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9961. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9962. if (texture.isCube) {
  9963. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9964. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9965. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9966. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9967. }
  9968. else {
  9969. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9970. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9971. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9972. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9973. }
  9974. texture.samplingMode = samplingMode;
  9975. };
  9976. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9977. if (premulAlpha === void 0) { premulAlpha = false; }
  9978. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9979. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9980. if (premulAlpha) {
  9981. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9982. }
  9983. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9984. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9985. if (texture.generateMipMaps) {
  9986. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9987. }
  9988. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9989. if (premulAlpha) {
  9990. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9991. }
  9992. this.resetTextureCache();
  9993. texture.isReady = true;
  9994. };
  9995. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9996. if (texture._isDisabled) {
  9997. return;
  9998. }
  9999. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10000. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10001. try {
  10002. // Testing video texture support
  10003. if (this._videoTextureSupported === undefined) {
  10004. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10005. if (this._gl.getError() !== 0) {
  10006. this._videoTextureSupported = false;
  10007. }
  10008. else {
  10009. this._videoTextureSupported = true;
  10010. }
  10011. }
  10012. // Copy video through the current working canvas if video texture is not supported
  10013. if (!this._videoTextureSupported) {
  10014. if (!texture._workingCanvas) {
  10015. texture._workingCanvas = document.createElement("canvas");
  10016. texture._workingContext = texture._workingCanvas.getContext("2d");
  10017. texture._workingCanvas.width = texture.width;
  10018. texture._workingCanvas.height = texture.height;
  10019. }
  10020. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10021. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10022. }
  10023. else {
  10024. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10025. }
  10026. if (texture.generateMipMaps) {
  10027. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10028. }
  10029. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10030. this.resetTextureCache();
  10031. texture.isReady = true;
  10032. }
  10033. catch (ex) {
  10034. // Something unexpected
  10035. // Let's disable the texture
  10036. texture._isDisabled = true;
  10037. }
  10038. };
  10039. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10040. var fullOptions = new RenderTargetCreationOptions();
  10041. if (options !== undefined && typeof options === "object") {
  10042. fullOptions.generateMipMaps = options.generateMipMaps;
  10043. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10044. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10045. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10046. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10047. }
  10048. else {
  10049. fullOptions.generateMipMaps = options;
  10050. fullOptions.generateDepthBuffer = true;
  10051. fullOptions.generateStencilBuffer = false;
  10052. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10053. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10054. }
  10055. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10056. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10057. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10058. }
  10059. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10060. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10061. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10062. }
  10063. var gl = this._gl;
  10064. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10065. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10066. var width = size.width || size;
  10067. var height = size.height || size;
  10068. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10069. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10070. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10071. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10072. }
  10073. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10074. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10077. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10078. // Create the framebuffer
  10079. var framebuffer = gl.createFramebuffer();
  10080. this.bindUnboundFramebuffer(framebuffer);
  10081. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10082. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10083. if (fullOptions.generateMipMaps) {
  10084. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10085. }
  10086. // Unbind
  10087. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10088. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10089. this.bindUnboundFramebuffer(null);
  10090. texture._framebuffer = framebuffer;
  10091. texture.baseWidth = width;
  10092. texture.baseHeight = height;
  10093. texture.width = width;
  10094. texture.height = height;
  10095. texture.isReady = true;
  10096. texture.samples = 1;
  10097. texture.generateMipMaps = fullOptions.generateMipMaps;
  10098. texture.samplingMode = fullOptions.samplingMode;
  10099. texture.type = fullOptions.type;
  10100. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10101. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10102. this.resetTextureCache();
  10103. this._internalTexturesCache.push(texture);
  10104. return texture;
  10105. };
  10106. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10107. var generateMipMaps = false;
  10108. var generateDepthBuffer = true;
  10109. var generateStencilBuffer = false;
  10110. var generateDepthTexture = false;
  10111. var textureCount = 1;
  10112. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10113. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10114. var types = [], samplingModes = [];
  10115. if (options !== undefined) {
  10116. generateMipMaps = options.generateMipMaps;
  10117. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10118. generateStencilBuffer = options.generateStencilBuffer;
  10119. generateDepthTexture = options.generateDepthTexture;
  10120. textureCount = options.textureCount || 1;
  10121. if (options.types) {
  10122. types = options.types;
  10123. }
  10124. if (options.samplingModes) {
  10125. samplingModes = options.samplingModes;
  10126. }
  10127. }
  10128. var gl = this._gl;
  10129. // Create the framebuffer
  10130. var framebuffer = gl.createFramebuffer();
  10131. this.bindUnboundFramebuffer(framebuffer);
  10132. var width = size.width || size;
  10133. var height = size.height || size;
  10134. var textures = [];
  10135. var attachments = [];
  10136. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10137. for (var i = 0; i < textureCount; i++) {
  10138. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10139. var type = types[i] || defaultType;
  10140. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10141. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10142. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10143. }
  10144. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10145. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10146. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10147. }
  10148. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10149. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10150. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10151. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10152. }
  10153. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10154. var attachment = gl["COLOR_ATTACHMENT" + i];
  10155. textures.push(texture);
  10156. attachments.push(attachment);
  10157. gl.activeTexture(gl["TEXTURE" + i]);
  10158. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10159. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10160. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10163. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10164. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10165. if (generateMipMaps) {
  10166. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10167. }
  10168. // Unbind
  10169. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10170. texture._framebuffer = framebuffer;
  10171. texture._depthStencilBuffer = depthStencilBuffer;
  10172. texture.baseWidth = width;
  10173. texture.baseHeight = height;
  10174. texture.width = width;
  10175. texture.height = height;
  10176. texture.isReady = true;
  10177. texture.samples = 1;
  10178. texture.generateMipMaps = generateMipMaps;
  10179. texture.samplingMode = samplingMode;
  10180. texture.type = type;
  10181. texture._generateDepthBuffer = generateDepthBuffer;
  10182. texture._generateStencilBuffer = generateStencilBuffer;
  10183. this._internalTexturesCache.push(texture);
  10184. }
  10185. if (generateDepthTexture) {
  10186. // Depth texture
  10187. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10188. gl.activeTexture(gl.TEXTURE0);
  10189. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10191. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10192. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10194. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10195. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10196. depthTexture._framebuffer = framebuffer;
  10197. depthTexture.baseWidth = width;
  10198. depthTexture.baseHeight = height;
  10199. depthTexture.width = width;
  10200. depthTexture.height = height;
  10201. depthTexture.isReady = true;
  10202. depthTexture.samples = 1;
  10203. depthTexture.generateMipMaps = generateMipMaps;
  10204. depthTexture.samplingMode = gl.NEAREST;
  10205. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10206. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10207. textures.push(depthTexture);
  10208. this._internalTexturesCache.push(depthTexture);
  10209. }
  10210. gl.drawBuffers(attachments);
  10211. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10212. this.bindUnboundFramebuffer(null);
  10213. this.resetTextureCache();
  10214. return textures;
  10215. };
  10216. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10217. if (samples === void 0) { samples = 1; }
  10218. var depthStencilBuffer = null;
  10219. var gl = this._gl;
  10220. // Create the depth/stencil buffer
  10221. if (generateStencilBuffer) {
  10222. depthStencilBuffer = gl.createRenderbuffer();
  10223. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10224. if (samples > 1) {
  10225. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10226. }
  10227. else {
  10228. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10229. }
  10230. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10231. }
  10232. else if (generateDepthBuffer) {
  10233. depthStencilBuffer = gl.createRenderbuffer();
  10234. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10235. if (samples > 1) {
  10236. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10237. }
  10238. else {
  10239. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10240. }
  10241. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10242. }
  10243. return depthStencilBuffer;
  10244. };
  10245. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10246. if (this.webGLVersion < 2) {
  10247. return 1;
  10248. }
  10249. if (texture.samples === samples) {
  10250. return samples;
  10251. }
  10252. var gl = this._gl;
  10253. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10254. // Dispose previous render buffers
  10255. if (texture._depthStencilBuffer) {
  10256. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10257. }
  10258. if (texture._MSAAFramebuffer) {
  10259. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10260. }
  10261. if (texture._MSAARenderBuffer) {
  10262. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10263. }
  10264. if (samples > 1) {
  10265. texture._MSAAFramebuffer = gl.createFramebuffer();
  10266. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10267. var colorRenderbuffer = gl.createRenderbuffer();
  10268. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10269. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10270. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10271. texture._MSAARenderBuffer = colorRenderbuffer;
  10272. }
  10273. else {
  10274. this.bindUnboundFramebuffer(texture._framebuffer);
  10275. }
  10276. texture.samples = samples;
  10277. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10278. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10279. this.bindUnboundFramebuffer(null);
  10280. return samples;
  10281. };
  10282. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10283. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10284. };
  10285. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10286. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10287. };
  10288. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10289. var gl = this._gl;
  10290. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10291. var generateMipMaps = true;
  10292. var generateDepthBuffer = true;
  10293. var generateStencilBuffer = false;
  10294. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10295. if (options !== undefined) {
  10296. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10297. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10298. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10299. if (options.samplingMode !== undefined) {
  10300. samplingMode = options.samplingMode;
  10301. }
  10302. }
  10303. texture.isCube = true;
  10304. texture.generateMipMaps = generateMipMaps;
  10305. texture.samples = 1;
  10306. texture.samplingMode = samplingMode;
  10307. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10308. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10309. for (var face = 0; face < 6; face++) {
  10310. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10311. }
  10312. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10313. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10314. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10315. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10316. // Create the framebuffer
  10317. var framebuffer = gl.createFramebuffer();
  10318. this.bindUnboundFramebuffer(framebuffer);
  10319. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10320. // Mipmaps
  10321. if (texture.generateMipMaps) {
  10322. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10323. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10324. }
  10325. // Unbind
  10326. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10327. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10328. this.bindUnboundFramebuffer(null);
  10329. texture._framebuffer = framebuffer;
  10330. texture.width = size;
  10331. texture.height = size;
  10332. texture.isReady = true;
  10333. this.resetTextureCache();
  10334. this._internalTexturesCache.push(texture);
  10335. return texture;
  10336. };
  10337. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10338. var _this = this;
  10339. if (onError === void 0) { onError = null; }
  10340. if (forcedExtension === void 0) { forcedExtension = null; }
  10341. var callback = function (loadData) {
  10342. if (!loadData) {
  10343. if (onLoad) {
  10344. onLoad(null);
  10345. }
  10346. return;
  10347. }
  10348. var texture = loadData.texture;
  10349. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10350. texture._lodGenerationScale = scale;
  10351. texture._lodGenerationOffset = offset;
  10352. if (_this._caps.textureLOD) {
  10353. // Do not add extra process if texture lod is supported.
  10354. if (onLoad) {
  10355. onLoad(texture);
  10356. }
  10357. return;
  10358. }
  10359. var mipSlices = 3;
  10360. var gl = _this._gl;
  10361. var width = loadData.width;
  10362. if (!width) {
  10363. return;
  10364. }
  10365. var textures = [];
  10366. for (var i = 0; i < mipSlices; i++) {
  10367. //compute LOD from even spacing in smoothness (matching shader calculation)
  10368. var smoothness = i / (mipSlices - 1);
  10369. var roughness = 1 - smoothness;
  10370. var minLODIndex = offset; // roughness = 0
  10371. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10372. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10373. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10374. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10375. glTextureFromLod.isCube = true;
  10376. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10377. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10378. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10379. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10380. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10381. if (loadData.isDDS) {
  10382. var info = loadData.info;
  10383. var data = loadData.data;
  10384. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10385. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10386. }
  10387. else {
  10388. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10389. }
  10390. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10391. // Wrap in a base texture for easy binding.
  10392. var lodTexture = new BABYLON.BaseTexture(scene);
  10393. lodTexture.isCube = true;
  10394. lodTexture._texture = glTextureFromLod;
  10395. glTextureFromLod.isReady = true;
  10396. textures.push(lodTexture);
  10397. }
  10398. texture._lodTextureHigh = textures[2];
  10399. texture._lodTextureMid = textures[1];
  10400. texture._lodTextureLow = textures[0];
  10401. if (onLoad) {
  10402. onLoad(texture);
  10403. }
  10404. };
  10405. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10406. };
  10407. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10408. var _this = this;
  10409. if (onLoad === void 0) { onLoad = null; }
  10410. if (onError === void 0) { onError = null; }
  10411. if (forcedExtension === void 0) { forcedExtension = null; }
  10412. var gl = this._gl;
  10413. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10414. texture.isCube = true;
  10415. texture.url = rootUrl;
  10416. texture.generateMipMaps = !noMipmap;
  10417. if (!this._doNotHandleContextLost) {
  10418. texture._extension = forcedExtension;
  10419. texture._files = files;
  10420. }
  10421. var isKTX = false;
  10422. var isDDS = false;
  10423. var lastDot = rootUrl.lastIndexOf('.');
  10424. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10425. if (this._textureFormatInUse) {
  10426. extension = this._textureFormatInUse;
  10427. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10428. isKTX = true;
  10429. }
  10430. else {
  10431. isDDS = (extension === ".dds");
  10432. }
  10433. if (isKTX) {
  10434. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10435. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10436. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10437. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10438. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10439. ktx.uploadLevels(_this._gl, !noMipmap);
  10440. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10441. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10442. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10443. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10444. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10445. _this.resetTextureCache();
  10446. texture.width = ktx.pixelWidth;
  10447. texture.height = ktx.pixelHeight;
  10448. texture.isReady = true;
  10449. }, null, null, true, onError);
  10450. }
  10451. else if (isDDS) {
  10452. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10453. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10454. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10455. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10456. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10457. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10458. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10459. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10460. }
  10461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10462. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10463. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10465. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10466. _this.resetTextureCache();
  10467. texture.width = info.width;
  10468. texture.height = info.height;
  10469. texture.isReady = true;
  10470. texture.type = info.textureType;
  10471. if (onLoad) {
  10472. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10473. }
  10474. }, null, null, true, onError);
  10475. }
  10476. else {
  10477. cascadeLoad(rootUrl, scene, function (imgs) {
  10478. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10479. var height = width;
  10480. _this._prepareWorkingCanvas();
  10481. _this._workingCanvas.width = width;
  10482. _this._workingCanvas.height = height;
  10483. var faces = [
  10484. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10485. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10486. ];
  10487. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10488. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10489. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10490. for (var index = 0; index < faces.length; index++) {
  10491. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10492. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10493. }
  10494. if (!noMipmap) {
  10495. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10496. }
  10497. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10498. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10499. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10500. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10501. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10502. _this.resetTextureCache();
  10503. texture.width = width;
  10504. texture.height = height;
  10505. texture.isReady = true;
  10506. texture.format = format;
  10507. texture.onLoadedObservable.notifyObservers(texture);
  10508. texture.onLoadedObservable.clear();
  10509. if (onLoad) {
  10510. onLoad();
  10511. }
  10512. }, files, onError);
  10513. }
  10514. this._internalTexturesCache.push(texture);
  10515. return texture;
  10516. };
  10517. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10518. if (compression === void 0) { compression = null; }
  10519. if (level === void 0) { level = 0; }
  10520. texture._bufferViewArray = data;
  10521. texture.format = format;
  10522. texture.type = type;
  10523. texture.invertY = invertY;
  10524. texture._compression = compression;
  10525. var gl = this._gl;
  10526. var textureType = this._getWebGLTextureType(type);
  10527. var internalFormat = this._getInternalFormat(format);
  10528. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10529. var needConversion = false;
  10530. if (internalFormat === gl.RGB) {
  10531. internalFormat = gl.RGBA;
  10532. needConversion = true;
  10533. }
  10534. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10535. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10536. if (texture.width % 4 !== 0) {
  10537. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10538. }
  10539. // Data are known to be in +X +Y +Z -X -Y -Z
  10540. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10541. var faceData = data[faceIndex];
  10542. if (compression) {
  10543. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10544. }
  10545. else {
  10546. if (needConversion) {
  10547. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10548. }
  10549. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10550. }
  10551. }
  10552. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10553. if (isPot && texture.generateMipMaps && level === 0) {
  10554. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10555. }
  10556. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10557. this.resetTextureCache();
  10558. texture.isReady = true;
  10559. };
  10560. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10561. if (compression === void 0) { compression = null; }
  10562. var gl = this._gl;
  10563. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10564. texture.isCube = true;
  10565. texture.generateMipMaps = generateMipMaps;
  10566. texture.format = format;
  10567. texture.type = type;
  10568. if (!this._doNotHandleContextLost) {
  10569. texture._bufferViewArray = data;
  10570. }
  10571. var textureType = this._getWebGLTextureType(type);
  10572. var internalFormat = this._getInternalFormat(format);
  10573. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10574. var needConversion = false;
  10575. if (internalFormat === gl.RGB) {
  10576. internalFormat = gl.RGBA;
  10577. needConversion = true;
  10578. }
  10579. var width = size;
  10580. var height = width;
  10581. texture.width = width;
  10582. texture.height = height;
  10583. // Double check on POT to generate Mips.
  10584. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10585. if (!isPot) {
  10586. generateMipMaps = false;
  10587. }
  10588. // Upload data if needed. The texture won't be ready until then.
  10589. if (data) {
  10590. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10591. }
  10592. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10593. // Filters
  10594. if (data && generateMipMaps) {
  10595. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10596. }
  10597. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10598. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10600. }
  10601. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10604. }
  10605. else {
  10606. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10609. }
  10610. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10612. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10613. return texture;
  10614. };
  10615. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10616. var _this = this;
  10617. if (onLoad === void 0) { onLoad = null; }
  10618. if (onError === void 0) { onError = null; }
  10619. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10620. if (invertY === void 0) { invertY = false; }
  10621. var gl = this._gl;
  10622. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10623. scene._addPendingData(texture);
  10624. texture.url = url;
  10625. this._internalTexturesCache.push(texture);
  10626. var onerror = function () {
  10627. scene._removePendingData(texture);
  10628. if (onError) {
  10629. onError();
  10630. }
  10631. };
  10632. var internalCallback = function (data) {
  10633. var width = texture.width;
  10634. var height = texture.height;
  10635. var faceDataArrays = callback(data);
  10636. if (mipmmapGenerator) {
  10637. var textureType = _this._getWebGLTextureType(type);
  10638. var internalFormat = _this._getInternalFormat(format);
  10639. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10640. var needConversion = false;
  10641. if (internalFormat === gl.RGB) {
  10642. internalFormat = gl.RGBA;
  10643. needConversion = true;
  10644. }
  10645. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10646. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10647. var mipData = mipmmapGenerator(faceDataArrays);
  10648. for (var level = 0; level < mipData.length; level++) {
  10649. var mipSize = width >> level;
  10650. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10651. var mipFaceData = mipData[level][faceIndex];
  10652. if (needConversion) {
  10653. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10654. }
  10655. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10656. }
  10657. }
  10658. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10659. }
  10660. else {
  10661. texture.generateMipMaps = !noMipmap;
  10662. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10663. }
  10664. texture.isReady = true;
  10665. _this.resetTextureCache();
  10666. scene._removePendingData(texture);
  10667. if (onLoad) {
  10668. onLoad();
  10669. }
  10670. };
  10671. BABYLON.Tools.LoadFile(url, function (data) {
  10672. internalCallback(data);
  10673. }, onerror, scene.database, true);
  10674. return texture;
  10675. };
  10676. ;
  10677. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10678. var gl = this._gl;
  10679. if (!gl) {
  10680. return;
  10681. }
  10682. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10683. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10684. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10685. if (!noMipmap && !isCompressed) {
  10686. gl.generateMipmap(gl.TEXTURE_2D);
  10687. }
  10688. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10689. this.resetTextureCache();
  10690. if (scene) {
  10691. scene._removePendingData(texture);
  10692. }
  10693. texture.onLoadedObservable.notifyObservers(texture);
  10694. texture.onLoadedObservable.clear();
  10695. };
  10696. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10697. var _this = this;
  10698. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10699. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10700. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10701. var gl = this._gl;
  10702. if (!gl) {
  10703. return;
  10704. }
  10705. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10706. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10707. texture.baseWidth = width;
  10708. texture.baseHeight = height;
  10709. texture.width = potWidth;
  10710. texture.height = potHeight;
  10711. texture.isReady = true;
  10712. if (processFunction(potWidth, potHeight, function () {
  10713. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10714. })) {
  10715. // Returning as texture needs extra async steps
  10716. return;
  10717. }
  10718. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10719. };
  10720. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10721. // Create new RGBA data container.
  10722. var rgbaData;
  10723. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10724. rgbaData = new Float32Array(width * height * 4);
  10725. }
  10726. else {
  10727. rgbaData = new Uint32Array(width * height * 4);
  10728. }
  10729. // Convert each pixel.
  10730. for (var x = 0; x < width; x++) {
  10731. for (var y = 0; y < height; y++) {
  10732. var index = (y * width + x) * 3;
  10733. var newIndex = (y * width + x) * 4;
  10734. // Map Old Value to new value.
  10735. rgbaData[newIndex + 0] = rgbData[index + 0];
  10736. rgbaData[newIndex + 1] = rgbData[index + 1];
  10737. rgbaData[newIndex + 2] = rgbData[index + 2];
  10738. // Add fully opaque alpha channel.
  10739. rgbaData[newIndex + 3] = 1;
  10740. }
  10741. }
  10742. return rgbaData;
  10743. };
  10744. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10745. var gl = this._gl;
  10746. if (texture._framebuffer) {
  10747. gl.deleteFramebuffer(texture._framebuffer);
  10748. texture._framebuffer = null;
  10749. }
  10750. if (texture._depthStencilBuffer) {
  10751. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10752. texture._depthStencilBuffer = null;
  10753. }
  10754. if (texture._MSAAFramebuffer) {
  10755. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10756. texture._MSAAFramebuffer = null;
  10757. }
  10758. if (texture._MSAARenderBuffer) {
  10759. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10760. texture._MSAARenderBuffer = null;
  10761. }
  10762. };
  10763. Engine.prototype._releaseTexture = function (texture) {
  10764. var gl = this._gl;
  10765. this._releaseFramebufferObjects(texture);
  10766. gl.deleteTexture(texture._webGLTexture);
  10767. // Unbind channels
  10768. this.unbindAllTextures();
  10769. var index = this._internalTexturesCache.indexOf(texture);
  10770. if (index !== -1) {
  10771. this._internalTexturesCache.splice(index, 1);
  10772. }
  10773. // Integrated fixed lod samplers.
  10774. if (texture._lodTextureHigh) {
  10775. texture._lodTextureHigh.dispose();
  10776. }
  10777. if (texture._lodTextureMid) {
  10778. texture._lodTextureMid.dispose();
  10779. }
  10780. if (texture._lodTextureLow) {
  10781. texture._lodTextureLow.dispose();
  10782. }
  10783. };
  10784. Engine.prototype.setProgram = function (program) {
  10785. if (this._currentProgram !== program) {
  10786. this._gl.useProgram(program);
  10787. this._currentProgram = program;
  10788. }
  10789. };
  10790. Engine.prototype.bindSamplers = function (effect) {
  10791. this.setProgram(effect.getProgram());
  10792. var samplers = effect.getSamplers();
  10793. for (var index = 0; index < samplers.length; index++) {
  10794. var uniform = effect.getUniform(samplers[index]);
  10795. this._gl.uniform1i(uniform, index);
  10796. }
  10797. this._currentEffect = null;
  10798. };
  10799. Engine.prototype.activateTexture = function (texture) {
  10800. if (this._activeTexture !== texture) {
  10801. this._gl.activeTexture(texture);
  10802. this._activeTexture = texture;
  10803. }
  10804. };
  10805. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10806. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10807. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10808. this._activeTexturesCache[this._activeTexture] = texture;
  10809. }
  10810. };
  10811. Engine.prototype._bindTexture = function (channel, texture) {
  10812. if (channel < 0) {
  10813. return;
  10814. }
  10815. this.activateTexture(this._gl.TEXTURE0 + channel);
  10816. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10817. };
  10818. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10819. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10820. };
  10821. Engine.prototype.unbindAllTextures = function () {
  10822. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10823. this.activateTexture(this._gl["TEXTURE" + channel]);
  10824. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10825. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10826. }
  10827. };
  10828. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10829. if (channel < 0) {
  10830. return;
  10831. }
  10832. this._gl.uniform1i(uniform, channel);
  10833. this._setTexture(channel, texture);
  10834. };
  10835. Engine.prototype._setTexture = function (channel, texture) {
  10836. // Not ready?
  10837. if (!texture) {
  10838. if (this._activeTexturesCache[channel] != null) {
  10839. this.activateTexture(this._gl["TEXTURE" + channel]);
  10840. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10841. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10842. }
  10843. return;
  10844. }
  10845. // Video
  10846. var alreadyActivated = false;
  10847. if (texture.video) {
  10848. this.activateTexture(this._gl["TEXTURE" + channel]);
  10849. alreadyActivated = true;
  10850. texture.update();
  10851. }
  10852. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10853. texture.delayLoad();
  10854. return;
  10855. }
  10856. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10857. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10858. if (this._activeTexturesCache[channel] === internalTexture) {
  10859. return;
  10860. }
  10861. if (!alreadyActivated) {
  10862. this.activateTexture(this._gl["TEXTURE" + channel]);
  10863. }
  10864. if (internalTexture.isCube) {
  10865. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10866. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10867. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10868. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10869. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10870. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10871. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10872. }
  10873. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10874. }
  10875. else {
  10876. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10877. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10878. internalTexture._cachedWrapU = texture.wrapU;
  10879. switch (texture.wrapU) {
  10880. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10881. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10882. break;
  10883. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10884. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10885. break;
  10886. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10887. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10888. break;
  10889. }
  10890. }
  10891. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10892. internalTexture._cachedWrapV = texture.wrapV;
  10893. switch (texture.wrapV) {
  10894. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10895. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10896. break;
  10897. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10898. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10899. break;
  10900. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10901. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10902. break;
  10903. }
  10904. }
  10905. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10906. }
  10907. };
  10908. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10909. if (channel < 0) {
  10910. return;
  10911. }
  10912. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10913. this._textureUnits = new Int32Array(textures.length);
  10914. }
  10915. for (var i = 0; i < textures.length; i++) {
  10916. this._textureUnits[i] = channel + i;
  10917. }
  10918. this._gl.uniform1iv(uniform, this._textureUnits);
  10919. for (var index = 0; index < textures.length; index++) {
  10920. this._setTexture(channel + index, textures[index]);
  10921. }
  10922. };
  10923. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10924. var internalTexture = texture.getInternalTexture();
  10925. if (!internalTexture) {
  10926. return;
  10927. }
  10928. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10929. var value = texture.anisotropicFilteringLevel;
  10930. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10931. value = 1;
  10932. }
  10933. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10934. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10935. internalTexture._cachedAnisotropicFilteringLevel = value;
  10936. }
  10937. };
  10938. Engine.prototype.readPixels = function (x, y, width, height) {
  10939. var data = new Uint8Array(height * width * 4);
  10940. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10941. return data;
  10942. };
  10943. /**
  10944. * Add an externaly attached data from its key.
  10945. * This method call will fail and return false, if such key already exists.
  10946. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10947. * @param key the unique key that identifies the data
  10948. * @param data the data object to associate to the key for this Engine instance
  10949. * @return true if no such key were already present and the data was added successfully, false otherwise
  10950. */
  10951. Engine.prototype.addExternalData = function (key, data) {
  10952. if (!this._externalData) {
  10953. this._externalData = new BABYLON.StringDictionary();
  10954. }
  10955. return this._externalData.add(key, data);
  10956. };
  10957. /**
  10958. * Get an externaly attached data from its key
  10959. * @param key the unique key that identifies the data
  10960. * @return the associated data, if present (can be null), or undefined if not present
  10961. */
  10962. Engine.prototype.getExternalData = function (key) {
  10963. if (!this._externalData) {
  10964. this._externalData = new BABYLON.StringDictionary();
  10965. }
  10966. return this._externalData.get(key);
  10967. };
  10968. /**
  10969. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10970. * @param key the unique key that identifies the data
  10971. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10972. * @return the associated data, can be null if the factory returned null.
  10973. */
  10974. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10975. if (!this._externalData) {
  10976. this._externalData = new BABYLON.StringDictionary();
  10977. }
  10978. return this._externalData.getOrAddWithFactory(key, factory);
  10979. };
  10980. /**
  10981. * Remove an externaly attached data from the Engine instance
  10982. * @param key the unique key that identifies the data
  10983. * @return true if the data was successfully removed, false if it doesn't exist
  10984. */
  10985. Engine.prototype.removeExternalData = function (key) {
  10986. if (!this._externalData) {
  10987. this._externalData = new BABYLON.StringDictionary();
  10988. }
  10989. return this._externalData.remove(key);
  10990. };
  10991. Engine.prototype.unbindAllAttributes = function () {
  10992. if (this._mustWipeVertexAttributes) {
  10993. this._mustWipeVertexAttributes = false;
  10994. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10995. this._gl.disableVertexAttribArray(i);
  10996. this._vertexAttribArraysEnabled[i] = false;
  10997. this._currentBufferPointers[i].active = false;
  10998. }
  10999. return;
  11000. }
  11001. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11002. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11003. continue;
  11004. }
  11005. this._gl.disableVertexAttribArray(i);
  11006. this._vertexAttribArraysEnabled[i] = false;
  11007. this._currentBufferPointers[i].active = false;
  11008. }
  11009. };
  11010. Engine.prototype.releaseEffects = function () {
  11011. for (var name in this._compiledEffects) {
  11012. this._gl.deleteProgram(this._compiledEffects[name]._program);
  11013. }
  11014. this._compiledEffects = {};
  11015. };
  11016. // Dispose
  11017. Engine.prototype.dispose = function () {
  11018. this.hideLoadingUI();
  11019. this.stopRenderLoop();
  11020. // Release postProcesses
  11021. while (this.postProcesses.length) {
  11022. this.postProcesses[0].dispose();
  11023. }
  11024. // Empty texture
  11025. if (this._emptyTexture) {
  11026. this._releaseTexture(this._emptyTexture);
  11027. this._emptyTexture = null;
  11028. }
  11029. if (this._emptyCubeTexture) {
  11030. this._releaseTexture(this._emptyCubeTexture);
  11031. this._emptyCubeTexture = null;
  11032. }
  11033. // Rescale PP
  11034. if (this._rescalePostProcess) {
  11035. this._rescalePostProcess.dispose();
  11036. }
  11037. // Release scenes
  11038. while (this.scenes.length) {
  11039. this.scenes[0].dispose();
  11040. }
  11041. // Release audio engine
  11042. if (Engine.audioEngine) {
  11043. Engine.audioEngine.dispose();
  11044. }
  11045. // Release effects
  11046. this.releaseEffects();
  11047. // Unbind
  11048. this.unbindAllAttributes();
  11049. if (this._dummyFramebuffer) {
  11050. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11051. }
  11052. this._gl = null;
  11053. //WebVR
  11054. this.disableVR();
  11055. // Events
  11056. window.removeEventListener("blur", this._onBlur);
  11057. window.removeEventListener("focus", this._onFocus);
  11058. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11059. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11060. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11061. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11062. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11063. if (!this._doNotHandleContextLost) {
  11064. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11065. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11066. }
  11067. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11068. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11069. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11070. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11071. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11072. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11073. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11074. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11075. // Remove from Instances
  11076. var index = Engine.Instances.indexOf(this);
  11077. if (index >= 0) {
  11078. Engine.Instances.splice(index, 1);
  11079. }
  11080. this._workingCanvas = null;
  11081. this._workingContext = null;
  11082. this._currentBufferPointers = null;
  11083. this._renderingCanvas = null;
  11084. this._currentProgram = null;
  11085. this.onResizeObservable.clear();
  11086. this.onCanvasBlurObservable.clear();
  11087. this.onCanvasFocusObservable.clear();
  11088. this.onCanvasPointerOutObservable.clear();
  11089. BABYLON.Effect.ResetCache();
  11090. };
  11091. // Loading screen
  11092. Engine.prototype.displayLoadingUI = function () {
  11093. var loadingScreen = this.loadingScreen;
  11094. if (loadingScreen) {
  11095. loadingScreen.displayLoadingUI();
  11096. }
  11097. };
  11098. Engine.prototype.hideLoadingUI = function () {
  11099. var loadingScreen = this.loadingScreen;
  11100. if (loadingScreen) {
  11101. loadingScreen.hideLoadingUI();
  11102. }
  11103. };
  11104. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11105. get: function () {
  11106. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11107. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11108. return this._loadingScreen;
  11109. },
  11110. set: function (loadingScreen) {
  11111. this._loadingScreen = loadingScreen;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11117. set: function (text) {
  11118. this.loadingScreen.loadingUIText = text;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11124. set: function (color) {
  11125. this.loadingScreen.loadingUIBackgroundColor = color;
  11126. },
  11127. enumerable: true,
  11128. configurable: true
  11129. });
  11130. Engine.prototype.attachContextLostEvent = function (callback) {
  11131. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11132. };
  11133. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11134. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11135. };
  11136. Engine.prototype.getVertexShaderSource = function (program) {
  11137. var shaders = this._gl.getAttachedShaders(program);
  11138. return this._gl.getShaderSource(shaders[0]);
  11139. };
  11140. Engine.prototype.getFragmentShaderSource = function (program) {
  11141. var shaders = this._gl.getAttachedShaders(program);
  11142. return this._gl.getShaderSource(shaders[1]);
  11143. };
  11144. Engine.prototype.getError = function () {
  11145. return this._gl.getError();
  11146. };
  11147. // FPS
  11148. Engine.prototype.getFps = function () {
  11149. return this._fps;
  11150. };
  11151. Engine.prototype.getDeltaTime = function () {
  11152. return this._deltaTime;
  11153. };
  11154. Engine.prototype._measureFps = function () {
  11155. this._performanceMonitor.sampleFrame();
  11156. this._fps = this._performanceMonitor.averageFPS;
  11157. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11158. };
  11159. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11160. if (faceIndex === void 0) { faceIndex = -1; }
  11161. var gl = this._gl;
  11162. if (!this._dummyFramebuffer) {
  11163. this._dummyFramebuffer = gl.createFramebuffer();
  11164. }
  11165. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11166. if (faceIndex > -1) {
  11167. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11168. }
  11169. else {
  11170. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11171. }
  11172. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11173. var buffer;
  11174. switch (readType) {
  11175. case gl.UNSIGNED_BYTE:
  11176. buffer = new Uint8Array(4 * width * height);
  11177. readType = gl.UNSIGNED_BYTE;
  11178. break;
  11179. default:
  11180. buffer = new Float32Array(4 * width * height);
  11181. readType = gl.FLOAT;
  11182. break;
  11183. }
  11184. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11185. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11186. return buffer;
  11187. };
  11188. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11189. if (this._webGLVersion > 1) {
  11190. return this._caps.colorBufferFloat;
  11191. }
  11192. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11193. };
  11194. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11195. if (this._webGLVersion > 1) {
  11196. return this._caps.colorBufferFloat;
  11197. }
  11198. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11199. };
  11200. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11201. Engine.prototype._canRenderToFramebuffer = function (type) {
  11202. var gl = this._gl;
  11203. //clear existing errors
  11204. while (gl.getError() !== gl.NO_ERROR) { }
  11205. var successful = true;
  11206. var texture = gl.createTexture();
  11207. gl.bindTexture(gl.TEXTURE_2D, texture);
  11208. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11209. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11210. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11211. var fb = gl.createFramebuffer();
  11212. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11213. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11214. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11215. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11216. successful = successful && (gl.getError() === gl.NO_ERROR);
  11217. //try render by clearing frame buffer's color buffer
  11218. if (successful) {
  11219. gl.clear(gl.COLOR_BUFFER_BIT);
  11220. successful = successful && (gl.getError() === gl.NO_ERROR);
  11221. }
  11222. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11223. if (successful) {
  11224. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11225. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11226. var readFormat = gl.RGBA;
  11227. var readType = gl.UNSIGNED_BYTE;
  11228. var buffer = new Uint8Array(4);
  11229. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11230. successful = successful && (gl.getError() === gl.NO_ERROR);
  11231. }
  11232. //clean up
  11233. gl.deleteTexture(texture);
  11234. gl.deleteFramebuffer(fb);
  11235. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11236. //clear accumulated errors
  11237. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11238. return successful;
  11239. };
  11240. Engine.prototype._getWebGLTextureType = function (type) {
  11241. if (type === Engine.TEXTURETYPE_FLOAT) {
  11242. return this._gl.FLOAT;
  11243. }
  11244. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11245. // Add Half Float Constant.
  11246. return this._gl.HALF_FLOAT_OES;
  11247. }
  11248. return this._gl.UNSIGNED_BYTE;
  11249. };
  11250. ;
  11251. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11252. if (this._webGLVersion === 1) {
  11253. return this._gl.RGBA;
  11254. }
  11255. if (type === Engine.TEXTURETYPE_FLOAT) {
  11256. return this._gl.RGBA32F;
  11257. }
  11258. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11259. return this._gl.RGBA16F;
  11260. }
  11261. return this._gl.RGBA;
  11262. };
  11263. ;
  11264. Engine.prototype.createQuery = function () {
  11265. return this._gl.createQuery();
  11266. };
  11267. Engine.prototype.deleteQuery = function (query) {
  11268. this._gl.deleteQuery(query);
  11269. return this;
  11270. };
  11271. Engine.prototype.isQueryResultAvailable = function (query) {
  11272. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11273. };
  11274. Engine.prototype.getQueryResult = function (query) {
  11275. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11276. };
  11277. Engine.prototype.beginQuery = function (algorithmType, query) {
  11278. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11279. this._gl.beginQuery(glAlgorithm, query);
  11280. };
  11281. Engine.prototype.endQuery = function (algorithmType) {
  11282. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11283. this._gl.endQuery(glAlgorithm);
  11284. return this;
  11285. };
  11286. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11287. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11288. };
  11289. // Statics
  11290. Engine.isSupported = function () {
  11291. try {
  11292. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11293. if (navigator.isCocoonJS) {
  11294. return true;
  11295. }
  11296. var tempcanvas = document.createElement("canvas");
  11297. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11298. return gl != null && !!window.WebGLRenderingContext;
  11299. }
  11300. catch (e) {
  11301. return false;
  11302. }
  11303. };
  11304. Engine.Instances = new Array();
  11305. // Const statics
  11306. Engine._ALPHA_DISABLE = 0;
  11307. Engine._ALPHA_ADD = 1;
  11308. Engine._ALPHA_COMBINE = 2;
  11309. Engine._ALPHA_SUBTRACT = 3;
  11310. Engine._ALPHA_MULTIPLY = 4;
  11311. Engine._ALPHA_MAXIMIZED = 5;
  11312. Engine._ALPHA_ONEONE = 6;
  11313. Engine._ALPHA_PREMULTIPLIED = 7;
  11314. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11315. Engine._ALPHA_INTERPOLATE = 9;
  11316. Engine._ALPHA_SCREENMODE = 10;
  11317. Engine._DELAYLOADSTATE_NONE = 0;
  11318. Engine._DELAYLOADSTATE_LOADED = 1;
  11319. Engine._DELAYLOADSTATE_LOADING = 2;
  11320. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11321. Engine._TEXTUREFORMAT_ALPHA = 0;
  11322. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11323. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11324. Engine._TEXTUREFORMAT_RGB = 4;
  11325. Engine._TEXTUREFORMAT_RGBA = 5;
  11326. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11327. Engine._TEXTURETYPE_FLOAT = 1;
  11328. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11329. // Depht or Stencil test Constants.
  11330. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11331. 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.
  11332. 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.
  11333. 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.
  11334. 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.
  11335. 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.
  11336. 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.
  11337. 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.
  11338. // Stencil Actions Constants.
  11339. Engine._KEEP = 0x1E00;
  11340. Engine._REPLACE = 0x1E01;
  11341. Engine._INCR = 0x1E02;
  11342. Engine._DECR = 0x1E03;
  11343. Engine._INVERT = 0x150A;
  11344. Engine._INCR_WRAP = 0x8507;
  11345. Engine._DECR_WRAP = 0x8508;
  11346. // Texture rescaling mode
  11347. Engine._SCALEMODE_FLOOR = 1;
  11348. Engine._SCALEMODE_NEAREST = 2;
  11349. Engine._SCALEMODE_CEILING = 3;
  11350. // Updatable statics so stick with vars here
  11351. Engine.CollisionsEpsilon = 0.001;
  11352. Engine.CodeRepository = "src/";
  11353. Engine.ShadersRepository = "src/Shaders/";
  11354. return Engine;
  11355. }());
  11356. BABYLON.Engine = Engine;
  11357. })(BABYLON || (BABYLON = {}));
  11358. //# sourceMappingURL=babylon.engine.js.map
  11359. /// <reference path="Tools\babylon.decorators.ts" />
  11360. var BABYLON;
  11361. (function (BABYLON) {
  11362. /**
  11363. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11364. */
  11365. var Node = (function () {
  11366. /**
  11367. * @constructor
  11368. * @param {string} name - the name and id to be given to this node
  11369. * @param {BABYLON.Scene} the scene this node will be added to
  11370. */
  11371. function Node(name, scene) {
  11372. this.state = "";
  11373. this.metadata = null;
  11374. this.doNotSerialize = false;
  11375. this.animations = new Array();
  11376. this._ranges = {};
  11377. this._childrenFlag = -1;
  11378. this._isEnabled = true;
  11379. this._isReady = true;
  11380. this._currentRenderId = -1;
  11381. this._parentRenderId = -1;
  11382. /**
  11383. * An event triggered when the mesh is disposed.
  11384. * @type {BABYLON.Observable}
  11385. */
  11386. this.onDisposeObservable = new BABYLON.Observable();
  11387. // Behaviors
  11388. this._behaviors = new Array();
  11389. this.name = name;
  11390. this.id = name;
  11391. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11392. this._initCache();
  11393. }
  11394. Object.defineProperty(Node.prototype, "parent", {
  11395. get: function () {
  11396. return this._parentNode;
  11397. },
  11398. set: function (parent) {
  11399. if (this._parentNode === parent) {
  11400. return;
  11401. }
  11402. if (this._parentNode) {
  11403. var index = this._parentNode._children.indexOf(this);
  11404. if (index !== -1) {
  11405. this._parentNode._children.splice(index, 1);
  11406. }
  11407. }
  11408. this._parentNode = parent;
  11409. if (this._parentNode) {
  11410. if (!this._parentNode._children) {
  11411. this._parentNode._children = new Array();
  11412. }
  11413. this._parentNode._children.push(this);
  11414. }
  11415. },
  11416. enumerable: true,
  11417. configurable: true
  11418. });
  11419. Node.prototype.getClassName = function () {
  11420. return "Node";
  11421. };
  11422. Object.defineProperty(Node.prototype, "onDispose", {
  11423. set: function (callback) {
  11424. if (this._onDisposeObserver) {
  11425. this.onDisposeObservable.remove(this._onDisposeObserver);
  11426. }
  11427. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11428. },
  11429. enumerable: true,
  11430. configurable: true
  11431. });
  11432. Node.prototype.getScene = function () {
  11433. return this._scene;
  11434. };
  11435. Node.prototype.getEngine = function () {
  11436. return this._scene.getEngine();
  11437. };
  11438. Node.prototype.addBehavior = function (behavior) {
  11439. var index = this._behaviors.indexOf(behavior);
  11440. if (index !== -1) {
  11441. return;
  11442. }
  11443. behavior.attach(this);
  11444. this._behaviors.push(behavior);
  11445. return this;
  11446. };
  11447. Node.prototype.removeBehavior = function (behavior) {
  11448. var index = this._behaviors.indexOf(behavior);
  11449. if (index === -1) {
  11450. return;
  11451. }
  11452. this._behaviors[index].detach();
  11453. this._behaviors.splice(index, 1);
  11454. return this;
  11455. };
  11456. Object.defineProperty(Node.prototype, "behaviors", {
  11457. get: function () {
  11458. return this._behaviors;
  11459. },
  11460. enumerable: true,
  11461. configurable: true
  11462. });
  11463. Node.prototype.getBehaviorByName = function (name) {
  11464. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11465. var behavior = _a[_i];
  11466. if (behavior.name === name) {
  11467. return behavior;
  11468. }
  11469. }
  11470. return null;
  11471. };
  11472. // override it in derived class
  11473. Node.prototype.getWorldMatrix = function () {
  11474. return BABYLON.Matrix.Identity();
  11475. };
  11476. // override it in derived class if you add new variables to the cache
  11477. // and call the parent class method
  11478. Node.prototype._initCache = function () {
  11479. this._cache = {};
  11480. this._cache.parent = undefined;
  11481. };
  11482. Node.prototype.updateCache = function (force) {
  11483. if (!force && this.isSynchronized())
  11484. return;
  11485. this._cache.parent = this.parent;
  11486. this._updateCache();
  11487. };
  11488. // override it in derived class if you add new variables to the cache
  11489. // and call the parent class method if !ignoreParentClass
  11490. Node.prototype._updateCache = function (ignoreParentClass) {
  11491. };
  11492. // override it in derived class if you add new variables to the cache
  11493. Node.prototype._isSynchronized = function () {
  11494. return true;
  11495. };
  11496. Node.prototype._markSyncedWithParent = function () {
  11497. this._parentRenderId = this.parent._currentRenderId;
  11498. };
  11499. Node.prototype.isSynchronizedWithParent = function () {
  11500. if (!this.parent) {
  11501. return true;
  11502. }
  11503. if (this._parentRenderId !== this.parent._currentRenderId) {
  11504. return false;
  11505. }
  11506. return this.parent.isSynchronized();
  11507. };
  11508. Node.prototype.isSynchronized = function (updateCache) {
  11509. var check = this.hasNewParent();
  11510. check = check || !this.isSynchronizedWithParent();
  11511. check = check || !this._isSynchronized();
  11512. if (updateCache)
  11513. this.updateCache(true);
  11514. return !check;
  11515. };
  11516. Node.prototype.hasNewParent = function (update) {
  11517. if (this._cache.parent === this.parent)
  11518. return false;
  11519. if (update)
  11520. this._cache.parent = this.parent;
  11521. return true;
  11522. };
  11523. /**
  11524. * Is this node ready to be used/rendered
  11525. * @return {boolean} is it ready
  11526. */
  11527. Node.prototype.isReady = function () {
  11528. return this._isReady;
  11529. };
  11530. /**
  11531. * Is this node enabled.
  11532. * If the node has a parent and is enabled, the parent will be inspected as well.
  11533. * @return {boolean} whether this node (and its parent) is enabled.
  11534. * @see setEnabled
  11535. */
  11536. Node.prototype.isEnabled = function () {
  11537. if (!this._isEnabled) {
  11538. return false;
  11539. }
  11540. if (this.parent) {
  11541. return this.parent.isEnabled();
  11542. }
  11543. return true;
  11544. };
  11545. /**
  11546. * Set the enabled state of this node.
  11547. * @param {boolean} value - the new enabled state
  11548. * @see isEnabled
  11549. */
  11550. Node.prototype.setEnabled = function (value) {
  11551. this._isEnabled = value;
  11552. };
  11553. /**
  11554. * Is this node a descendant of the given node.
  11555. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11556. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11557. * @see parent
  11558. */
  11559. Node.prototype.isDescendantOf = function (ancestor) {
  11560. if (this.parent) {
  11561. if (this.parent === ancestor) {
  11562. return true;
  11563. }
  11564. return this.parent.isDescendantOf(ancestor);
  11565. }
  11566. return false;
  11567. };
  11568. /**
  11569. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11570. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11571. * @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.
  11572. * @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.
  11573. */
  11574. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11575. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11576. if (!this._children) {
  11577. return;
  11578. }
  11579. for (var index = 0; index < this._children.length; index++) {
  11580. var item = this._children[index];
  11581. if (!predicate || predicate(item)) {
  11582. results.push(item);
  11583. }
  11584. if (!directDescendantsOnly) {
  11585. item._getDescendants(results, false, predicate);
  11586. }
  11587. }
  11588. };
  11589. /**
  11590. * Will return all nodes that have this node as ascendant.
  11591. * @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.
  11592. * @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.
  11593. * @return {BABYLON.Node[]} all children nodes of all types.
  11594. */
  11595. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11596. var results = [];
  11597. this._getDescendants(results, directDescendantsOnly, predicate);
  11598. return results;
  11599. };
  11600. /**
  11601. * Get all child-meshes of this node.
  11602. */
  11603. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11604. var results = [];
  11605. this._getDescendants(results, directDecendantsOnly, function (node) {
  11606. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11607. });
  11608. return results;
  11609. };
  11610. /**
  11611. * Get all direct children of this node.
  11612. */
  11613. Node.prototype.getChildren = function (predicate) {
  11614. return this.getDescendants(true, predicate);
  11615. };
  11616. Node.prototype._setReady = function (state) {
  11617. if (state === this._isReady) {
  11618. return;
  11619. }
  11620. if (!state) {
  11621. this._isReady = false;
  11622. return;
  11623. }
  11624. this._isReady = true;
  11625. if (this.onReady) {
  11626. this.onReady(this);
  11627. }
  11628. };
  11629. Node.prototype.getAnimationByName = function (name) {
  11630. for (var i = 0; i < this.animations.length; i++) {
  11631. var animation = this.animations[i];
  11632. if (animation.name === name) {
  11633. return animation;
  11634. }
  11635. }
  11636. return null;
  11637. };
  11638. Node.prototype.createAnimationRange = function (name, from, to) {
  11639. // check name not already in use
  11640. if (!this._ranges[name]) {
  11641. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11642. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11643. if (this.animations[i]) {
  11644. this.animations[i].createRange(name, from, to);
  11645. }
  11646. }
  11647. }
  11648. };
  11649. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11650. if (deleteFrames === void 0) { deleteFrames = true; }
  11651. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11652. if (this.animations[i]) {
  11653. this.animations[i].deleteRange(name, deleteFrames);
  11654. }
  11655. }
  11656. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11657. };
  11658. Node.prototype.getAnimationRange = function (name) {
  11659. return this._ranges[name];
  11660. };
  11661. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11662. var range = this.getAnimationRange(name);
  11663. if (!range) {
  11664. return null;
  11665. }
  11666. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11667. };
  11668. Node.prototype.serializeAnimationRanges = function () {
  11669. var serializationRanges = [];
  11670. for (var name in this._ranges) {
  11671. var range = {};
  11672. range.name = name;
  11673. range.from = this._ranges[name].from;
  11674. range.to = this._ranges[name].to;
  11675. serializationRanges.push(range);
  11676. }
  11677. return serializationRanges;
  11678. };
  11679. Node.prototype.dispose = function () {
  11680. this.parent = null;
  11681. // Callback
  11682. this.onDisposeObservable.notifyObservers(this);
  11683. this.onDisposeObservable.clear();
  11684. // Behaviors
  11685. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11686. var behavior = _a[_i];
  11687. behavior.detach();
  11688. }
  11689. this._behaviors = [];
  11690. };
  11691. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11692. if (parsedNode.ranges) {
  11693. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11694. var data = parsedNode.ranges[index];
  11695. node.createAnimationRange(data.name, data.from, data.to);
  11696. }
  11697. }
  11698. };
  11699. __decorate([
  11700. BABYLON.serialize()
  11701. ], Node.prototype, "name", void 0);
  11702. __decorate([
  11703. BABYLON.serialize()
  11704. ], Node.prototype, "id", void 0);
  11705. __decorate([
  11706. BABYLON.serialize()
  11707. ], Node.prototype, "uniqueId", void 0);
  11708. __decorate([
  11709. BABYLON.serialize()
  11710. ], Node.prototype, "state", void 0);
  11711. __decorate([
  11712. BABYLON.serialize()
  11713. ], Node.prototype, "metadata", void 0);
  11714. return Node;
  11715. }());
  11716. BABYLON.Node = Node;
  11717. })(BABYLON || (BABYLON = {}));
  11718. //# sourceMappingURL=babylon.node.js.map
  11719. var BABYLON;
  11720. (function (BABYLON) {
  11721. var BoundingSphere = (function () {
  11722. function BoundingSphere(minimum, maximum) {
  11723. this.minimum = minimum;
  11724. this.maximum = maximum;
  11725. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11726. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11727. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11728. this.radius = distance * 0.5;
  11729. this.centerWorld = BABYLON.Vector3.Zero();
  11730. this._update(BABYLON.Matrix.Identity());
  11731. }
  11732. // Methods
  11733. BoundingSphere.prototype._update = function (world) {
  11734. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11735. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11736. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11737. };
  11738. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11739. for (var i = 0; i < 6; i++) {
  11740. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11741. return false;
  11742. }
  11743. return true;
  11744. };
  11745. BoundingSphere.prototype.intersectsPoint = function (point) {
  11746. var x = this.centerWorld.x - point.x;
  11747. var y = this.centerWorld.y - point.y;
  11748. var z = this.centerWorld.z - point.z;
  11749. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11750. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11751. return false;
  11752. return true;
  11753. };
  11754. // Statics
  11755. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11756. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11757. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11758. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11759. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11760. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11761. return false;
  11762. return true;
  11763. };
  11764. return BoundingSphere;
  11765. }());
  11766. BABYLON.BoundingSphere = BoundingSphere;
  11767. })(BABYLON || (BABYLON = {}));
  11768. //# sourceMappingURL=babylon.boundingSphere.js.map
  11769. var BABYLON;
  11770. (function (BABYLON) {
  11771. var BoundingBox = (function () {
  11772. function BoundingBox(minimum, maximum) {
  11773. this.minimum = minimum;
  11774. this.maximum = maximum;
  11775. this.vectors = new Array();
  11776. this.vectorsWorld = new Array();
  11777. // Bounding vectors
  11778. this.vectors.push(this.minimum.clone());
  11779. this.vectors.push(this.maximum.clone());
  11780. this.vectors.push(this.minimum.clone());
  11781. this.vectors[2].x = this.maximum.x;
  11782. this.vectors.push(this.minimum.clone());
  11783. this.vectors[3].y = this.maximum.y;
  11784. this.vectors.push(this.minimum.clone());
  11785. this.vectors[4].z = this.maximum.z;
  11786. this.vectors.push(this.maximum.clone());
  11787. this.vectors[5].z = this.minimum.z;
  11788. this.vectors.push(this.maximum.clone());
  11789. this.vectors[6].x = this.minimum.x;
  11790. this.vectors.push(this.maximum.clone());
  11791. this.vectors[7].y = this.minimum.y;
  11792. // OBB
  11793. this.center = this.maximum.add(this.minimum).scale(0.5);
  11794. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11795. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11796. // World
  11797. for (var index = 0; index < this.vectors.length; index++) {
  11798. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11799. }
  11800. this.minimumWorld = BABYLON.Vector3.Zero();
  11801. this.maximumWorld = BABYLON.Vector3.Zero();
  11802. this.centerWorld = BABYLON.Vector3.Zero();
  11803. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11804. this._update(BABYLON.Matrix.Identity());
  11805. }
  11806. // Methods
  11807. BoundingBox.prototype.getWorldMatrix = function () {
  11808. return this._worldMatrix;
  11809. };
  11810. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11811. this._worldMatrix.copyFrom(matrix);
  11812. return this;
  11813. };
  11814. BoundingBox.prototype._update = function (world) {
  11815. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11816. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11817. for (var index = 0; index < this.vectors.length; index++) {
  11818. var v = this.vectorsWorld[index];
  11819. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11820. if (v.x < this.minimumWorld.x)
  11821. this.minimumWorld.x = v.x;
  11822. if (v.y < this.minimumWorld.y)
  11823. this.minimumWorld.y = v.y;
  11824. if (v.z < this.minimumWorld.z)
  11825. this.minimumWorld.z = v.z;
  11826. if (v.x > this.maximumWorld.x)
  11827. this.maximumWorld.x = v.x;
  11828. if (v.y > this.maximumWorld.y)
  11829. this.maximumWorld.y = v.y;
  11830. if (v.z > this.maximumWorld.z)
  11831. this.maximumWorld.z = v.z;
  11832. }
  11833. // Extend
  11834. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11835. this.extendSizeWorld.scaleInPlace(0.5);
  11836. // OBB
  11837. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11838. this.centerWorld.scaleInPlace(0.5);
  11839. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11840. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11841. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11842. this._worldMatrix = world;
  11843. };
  11844. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11845. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11846. };
  11847. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11848. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11849. };
  11850. BoundingBox.prototype.intersectsPoint = function (point) {
  11851. var delta = -BABYLON.Epsilon;
  11852. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11853. return false;
  11854. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11855. return false;
  11856. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11857. return false;
  11858. return true;
  11859. };
  11860. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11861. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11862. };
  11863. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11864. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11865. return false;
  11866. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11867. return false;
  11868. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11869. return false;
  11870. return true;
  11871. };
  11872. // Statics
  11873. BoundingBox.Intersects = function (box0, box1) {
  11874. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11875. return false;
  11876. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11877. return false;
  11878. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11879. return false;
  11880. return true;
  11881. };
  11882. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11883. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11884. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11885. return (num <= (sphereRadius * sphereRadius));
  11886. };
  11887. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11888. for (var p = 0; p < 6; p++) {
  11889. for (var i = 0; i < 8; i++) {
  11890. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11891. return false;
  11892. }
  11893. }
  11894. }
  11895. return true;
  11896. };
  11897. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11898. for (var p = 0; p < 6; p++) {
  11899. var inCount = 8;
  11900. for (var i = 0; i < 8; i++) {
  11901. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11902. --inCount;
  11903. }
  11904. else {
  11905. break;
  11906. }
  11907. }
  11908. if (inCount === 0)
  11909. return false;
  11910. }
  11911. return true;
  11912. };
  11913. return BoundingBox;
  11914. }());
  11915. BABYLON.BoundingBox = BoundingBox;
  11916. })(BABYLON || (BABYLON = {}));
  11917. //# sourceMappingURL=babylon.boundingBox.js.map
  11918. var BABYLON;
  11919. (function (BABYLON) {
  11920. var computeBoxExtents = function (axis, box) {
  11921. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11922. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11923. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11924. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11925. var r = r0 + r1 + r2;
  11926. return {
  11927. min: p - r,
  11928. max: p + r
  11929. };
  11930. };
  11931. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11932. var axisOverlap = function (axis, box0, box1) {
  11933. var result0 = computeBoxExtents(axis, box0);
  11934. var result1 = computeBoxExtents(axis, box1);
  11935. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11936. };
  11937. var BoundingInfo = (function () {
  11938. function BoundingInfo(minimum, maximum) {
  11939. this.minimum = minimum;
  11940. this.maximum = maximum;
  11941. this._isLocked = false;
  11942. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11943. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11944. }
  11945. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11946. get: function () {
  11947. return this._isLocked;
  11948. },
  11949. set: function (value) {
  11950. this._isLocked = value;
  11951. },
  11952. enumerable: true,
  11953. configurable: true
  11954. });
  11955. // Methods
  11956. BoundingInfo.prototype.update = function (world) {
  11957. if (this._isLocked) {
  11958. return;
  11959. }
  11960. this.boundingBox._update(world);
  11961. this.boundingSphere._update(world);
  11962. };
  11963. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11964. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11965. return false;
  11966. return this.boundingBox.isInFrustum(frustumPlanes);
  11967. };
  11968. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  11969. /**
  11970. * Gets the world distance between the min and max points of the bounding box
  11971. */
  11972. get: function () {
  11973. var boundingBox = this.boundingBox;
  11974. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  11975. return size.length();
  11976. },
  11977. enumerable: true,
  11978. configurable: true
  11979. });
  11980. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11981. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11982. };
  11983. BoundingInfo.prototype._checkCollision = function (collider) {
  11984. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11985. };
  11986. BoundingInfo.prototype.intersectsPoint = function (point) {
  11987. if (!this.boundingSphere.centerWorld) {
  11988. return false;
  11989. }
  11990. if (!this.boundingSphere.intersectsPoint(point)) {
  11991. return false;
  11992. }
  11993. if (!this.boundingBox.intersectsPoint(point)) {
  11994. return false;
  11995. }
  11996. return true;
  11997. };
  11998. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11999. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12000. return false;
  12001. }
  12002. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12003. return false;
  12004. }
  12005. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12006. return false;
  12007. }
  12008. if (!precise) {
  12009. return true;
  12010. }
  12011. var box0 = this.boundingBox;
  12012. var box1 = boundingInfo.boundingBox;
  12013. if (!axisOverlap(box0.directions[0], box0, box1))
  12014. return false;
  12015. if (!axisOverlap(box0.directions[1], box0, box1))
  12016. return false;
  12017. if (!axisOverlap(box0.directions[2], box0, box1))
  12018. return false;
  12019. if (!axisOverlap(box1.directions[0], box0, box1))
  12020. return false;
  12021. if (!axisOverlap(box1.directions[1], box0, box1))
  12022. return false;
  12023. if (!axisOverlap(box1.directions[2], box0, box1))
  12024. return false;
  12025. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12026. return false;
  12027. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12028. return false;
  12029. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12030. return false;
  12031. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12032. return false;
  12033. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12034. return false;
  12035. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12036. return false;
  12037. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12038. return false;
  12039. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12040. return false;
  12041. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12042. return false;
  12043. return true;
  12044. };
  12045. return BoundingInfo;
  12046. }());
  12047. BABYLON.BoundingInfo = BoundingInfo;
  12048. })(BABYLON || (BABYLON = {}));
  12049. //# sourceMappingURL=babylon.boundingInfo.js.map
  12050. var BABYLON;
  12051. (function (BABYLON) {
  12052. var AbstractMesh = (function (_super) {
  12053. __extends(AbstractMesh, _super);
  12054. // Constructor
  12055. function AbstractMesh(name, scene) {
  12056. var _this = _super.call(this, name, scene) || this;
  12057. _this._facetNb = 0; // facet number
  12058. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12059. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12060. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12061. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12062. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12063. _this._subDiv = {
  12064. max: 1,
  12065. X: 1,
  12066. Y: 1,
  12067. Z: 1
  12068. };
  12069. // Events
  12070. /**
  12071. * An event triggered when this mesh collides with another one
  12072. * @type {BABYLON.Observable}
  12073. */
  12074. _this.onCollideObservable = new BABYLON.Observable();
  12075. /**
  12076. * An event triggered when the collision's position changes
  12077. * @type {BABYLON.Observable}
  12078. */
  12079. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12080. /**
  12081. * An event triggered after the world matrix is updated
  12082. * @type {BABYLON.Observable}
  12083. */
  12084. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12085. /**
  12086. * An event triggered when material is changed
  12087. * @type {BABYLON.Observable}
  12088. */
  12089. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12090. // Properties
  12091. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12092. _this.position = BABYLON.Vector3.Zero();
  12093. /**
  12094. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12095. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12096. * or
  12097. * 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.
  12098. * for more info check WebGl documentations
  12099. */
  12100. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12101. /**
  12102. * 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:
  12103. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12104. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12105. * 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.
  12106. */
  12107. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12108. /**
  12109. * 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.
  12110. * The default value is -1 which means don't break the query and wait till the result.
  12111. */
  12112. _this.occlusionRetryCount = -1;
  12113. _this._occlusionInternalRetryCounter = 0;
  12114. _this._isOccluded = false;
  12115. _this._isOcclusionQueryInProgress = false;
  12116. _this._rotation = BABYLON.Vector3.Zero();
  12117. _this._scaling = BABYLON.Vector3.One();
  12118. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12119. _this.visibility = 1.0;
  12120. _this.alphaIndex = Number.MAX_VALUE;
  12121. _this.infiniteDistance = false;
  12122. _this.isVisible = true;
  12123. _this.isPickable = true;
  12124. _this.showBoundingBox = false;
  12125. _this.showSubMeshesBoundingBox = false;
  12126. _this.isBlocker = false;
  12127. _this.enablePointerMoveEvents = false;
  12128. _this.renderingGroupId = 0;
  12129. _this._receiveShadows = false;
  12130. _this.renderOutline = false;
  12131. _this.outlineColor = BABYLON.Color3.Red();
  12132. _this.outlineWidth = 0.02;
  12133. _this.renderOverlay = false;
  12134. _this.overlayColor = BABYLON.Color3.Red();
  12135. _this.overlayAlpha = 0.5;
  12136. _this._hasVertexAlpha = false;
  12137. _this._useVertexColors = true;
  12138. _this._computeBonesUsingShaders = true;
  12139. _this._numBoneInfluencers = 4;
  12140. _this._applyFog = true;
  12141. _this.scalingDeterminant = 1;
  12142. _this.useOctreeForRenderingSelection = true;
  12143. _this.useOctreeForPicking = true;
  12144. _this.useOctreeForCollisions = true;
  12145. _this._layerMask = 0x0FFFFFFF;
  12146. /**
  12147. * True if the mesh must be rendered in any case.
  12148. */
  12149. _this.alwaysSelectAsActiveMesh = false;
  12150. // Collisions
  12151. _this._checkCollisions = false;
  12152. _this._collisionMask = -1;
  12153. _this._collisionGroup = -1;
  12154. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12155. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12156. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12157. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12158. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12159. // Edges
  12160. _this.edgesWidth = 1;
  12161. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12162. // Cache
  12163. _this._localWorld = BABYLON.Matrix.Zero();
  12164. _this._worldMatrix = BABYLON.Matrix.Zero();
  12165. _this._absolutePosition = BABYLON.Vector3.Zero();
  12166. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12167. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12168. _this._isDirty = false;
  12169. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12170. _this._isDisposed = false;
  12171. _this._renderId = 0;
  12172. _this._intersectionsInProgress = new Array();
  12173. _this._isWorldMatrixFrozen = false;
  12174. _this._unIndexed = false;
  12175. _this._lightSources = new Array();
  12176. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12177. if (collidedMesh === void 0) { collidedMesh = null; }
  12178. //TODO move this to the collision coordinator!
  12179. if (_this.getScene().workerCollisions)
  12180. newPosition.multiplyInPlace(_this._collider.radius);
  12181. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12182. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12183. _this.position.addInPlace(_this._diffPositionForCollisions);
  12184. }
  12185. if (collidedMesh) {
  12186. _this.onCollideObservable.notifyObservers(collidedMesh);
  12187. }
  12188. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12189. };
  12190. _this.getScene().addMesh(_this);
  12191. _this._resyncLightSources();
  12192. return _this;
  12193. }
  12194. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12195. get: function () {
  12196. return AbstractMesh._BILLBOARDMODE_NONE;
  12197. },
  12198. enumerable: true,
  12199. configurable: true
  12200. });
  12201. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12202. get: function () {
  12203. return AbstractMesh._BILLBOARDMODE_X;
  12204. },
  12205. enumerable: true,
  12206. configurable: true
  12207. });
  12208. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12209. get: function () {
  12210. return AbstractMesh._BILLBOARDMODE_Y;
  12211. },
  12212. enumerable: true,
  12213. configurable: true
  12214. });
  12215. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12216. get: function () {
  12217. return AbstractMesh._BILLBOARDMODE_Z;
  12218. },
  12219. enumerable: true,
  12220. configurable: true
  12221. });
  12222. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12223. get: function () {
  12224. return AbstractMesh._BILLBOARDMODE_ALL;
  12225. },
  12226. enumerable: true,
  12227. configurable: true
  12228. });
  12229. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12230. /**
  12231. * Read-only : the number of facets in the mesh
  12232. */
  12233. get: function () {
  12234. return this._facetNb;
  12235. },
  12236. enumerable: true,
  12237. configurable: true
  12238. });
  12239. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12240. /**
  12241. * The number (integer) of subdivisions per axis in the partioning space
  12242. */
  12243. get: function () {
  12244. return this._partitioningSubdivisions;
  12245. },
  12246. set: function (nb) {
  12247. this._partitioningSubdivisions = nb;
  12248. },
  12249. enumerable: true,
  12250. configurable: true
  12251. });
  12252. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12253. /**
  12254. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12255. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12256. */
  12257. get: function () {
  12258. return this._partitioningBBoxRatio;
  12259. },
  12260. set: function (ratio) {
  12261. this._partitioningBBoxRatio = ratio;
  12262. },
  12263. enumerable: true,
  12264. configurable: true
  12265. });
  12266. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12267. /**
  12268. * Read-only boolean : is the feature facetData enabled ?
  12269. */
  12270. get: function () {
  12271. return this._facetDataEnabled;
  12272. },
  12273. enumerable: true,
  12274. configurable: true
  12275. });
  12276. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12277. set: function (callback) {
  12278. if (this._onCollideObserver) {
  12279. this.onCollideObservable.remove(this._onCollideObserver);
  12280. }
  12281. this._onCollideObserver = this.onCollideObservable.add(callback);
  12282. },
  12283. enumerable: true,
  12284. configurable: true
  12285. });
  12286. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12287. set: function (callback) {
  12288. if (this._onCollisionPositionChangeObserver) {
  12289. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12290. }
  12291. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12292. },
  12293. enumerable: true,
  12294. configurable: true
  12295. });
  12296. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12297. /**
  12298. * 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.
  12299. */
  12300. get: function () {
  12301. return this._isOccluded;
  12302. },
  12303. set: function (value) {
  12304. this._isOccluded = value;
  12305. },
  12306. enumerable: true,
  12307. configurable: true
  12308. });
  12309. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12310. /**
  12311. * Flag to check the progress status of the query
  12312. */
  12313. get: function () {
  12314. return this._isOcclusionQueryInProgress;
  12315. },
  12316. enumerable: true,
  12317. configurable: true
  12318. });
  12319. Object.defineProperty(AbstractMesh.prototype, "material", {
  12320. get: function () {
  12321. return this._material;
  12322. },
  12323. set: function (value) {
  12324. if (this._material === value) {
  12325. return;
  12326. }
  12327. this._material = value;
  12328. if (this.onMaterialChangedObservable.hasObservers) {
  12329. this.onMaterialChangedObservable.notifyObservers(this);
  12330. }
  12331. if (!this.subMeshes) {
  12332. return;
  12333. }
  12334. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12335. var subMesh = _a[_i];
  12336. subMesh.setEffect(null);
  12337. }
  12338. },
  12339. enumerable: true,
  12340. configurable: true
  12341. });
  12342. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12343. get: function () {
  12344. return this._receiveShadows;
  12345. },
  12346. set: function (value) {
  12347. if (this._receiveShadows === value) {
  12348. return;
  12349. }
  12350. this._receiveShadows = value;
  12351. this._markSubMeshesAsLightDirty();
  12352. },
  12353. enumerable: true,
  12354. configurable: true
  12355. });
  12356. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12357. get: function () {
  12358. return this._hasVertexAlpha;
  12359. },
  12360. set: function (value) {
  12361. if (this._hasVertexAlpha === value) {
  12362. return;
  12363. }
  12364. this._hasVertexAlpha = value;
  12365. this._markSubMeshesAsAttributesDirty();
  12366. },
  12367. enumerable: true,
  12368. configurable: true
  12369. });
  12370. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12371. get: function () {
  12372. return this._useVertexColors;
  12373. },
  12374. set: function (value) {
  12375. if (this._useVertexColors === value) {
  12376. return;
  12377. }
  12378. this._useVertexColors = value;
  12379. this._markSubMeshesAsAttributesDirty();
  12380. },
  12381. enumerable: true,
  12382. configurable: true
  12383. });
  12384. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12385. get: function () {
  12386. return this._computeBonesUsingShaders;
  12387. },
  12388. set: function (value) {
  12389. if (this._computeBonesUsingShaders === value) {
  12390. return;
  12391. }
  12392. this._computeBonesUsingShaders = value;
  12393. this._markSubMeshesAsAttributesDirty();
  12394. },
  12395. enumerable: true,
  12396. configurable: true
  12397. });
  12398. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12399. get: function () {
  12400. return this._numBoneInfluencers;
  12401. },
  12402. set: function (value) {
  12403. if (this._numBoneInfluencers === value) {
  12404. return;
  12405. }
  12406. this._numBoneInfluencers = value;
  12407. this._markSubMeshesAsAttributesDirty();
  12408. },
  12409. enumerable: true,
  12410. configurable: true
  12411. });
  12412. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12413. get: function () {
  12414. return this._applyFog;
  12415. },
  12416. set: function (value) {
  12417. if (this._applyFog === value) {
  12418. return;
  12419. }
  12420. this._applyFog = value;
  12421. this._markSubMeshesAsMiscDirty();
  12422. },
  12423. enumerable: true,
  12424. configurable: true
  12425. });
  12426. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12427. get: function () {
  12428. return this._layerMask;
  12429. },
  12430. set: function (value) {
  12431. if (value === this._layerMask) {
  12432. return;
  12433. }
  12434. this._layerMask = value;
  12435. this._resyncLightSources();
  12436. },
  12437. enumerable: true,
  12438. configurable: true
  12439. });
  12440. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12441. get: function () {
  12442. return this._collisionMask;
  12443. },
  12444. set: function (mask) {
  12445. this._collisionMask = !isNaN(mask) ? mask : -1;
  12446. },
  12447. enumerable: true,
  12448. configurable: true
  12449. });
  12450. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12451. get: function () {
  12452. return this._collisionGroup;
  12453. },
  12454. set: function (mask) {
  12455. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12456. },
  12457. enumerable: true,
  12458. configurable: true
  12459. });
  12460. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12461. get: function () {
  12462. return null;
  12463. },
  12464. enumerable: true,
  12465. configurable: true
  12466. });
  12467. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12468. get: function () {
  12469. return this._skeleton;
  12470. },
  12471. set: function (value) {
  12472. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12473. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12474. }
  12475. if (value && value.needInitialSkinMatrix) {
  12476. value._registerMeshWithPoseMatrix(this);
  12477. }
  12478. this._skeleton = value;
  12479. if (!this._skeleton) {
  12480. this._bonesTransformMatrices = null;
  12481. }
  12482. this._markSubMeshesAsAttributesDirty();
  12483. },
  12484. enumerable: true,
  12485. configurable: true
  12486. });
  12487. /**
  12488. * Boolean : true if the mesh has been disposed.
  12489. */
  12490. AbstractMesh.prototype.isDisposed = function () {
  12491. return this._isDisposed;
  12492. };
  12493. /**
  12494. * Returns the string "AbstractMesh"
  12495. */
  12496. AbstractMesh.prototype.getClassName = function () {
  12497. return "AbstractMesh";
  12498. };
  12499. /**
  12500. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12501. */
  12502. AbstractMesh.prototype.toString = function (fullDetails) {
  12503. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12504. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12505. if (this._skeleton) {
  12506. ret += ", skeleton: " + this._skeleton.name;
  12507. }
  12508. if (fullDetails) {
  12509. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12510. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12511. }
  12512. return ret;
  12513. };
  12514. AbstractMesh.prototype._rebuild = function () {
  12515. if (this._occlusionQuery) {
  12516. this._occlusionQuery = null;
  12517. }
  12518. if (this._edgesRenderer) {
  12519. this._edgesRenderer._rebuild();
  12520. }
  12521. if (!this.subMeshes) {
  12522. return;
  12523. }
  12524. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12525. var subMesh = _a[_i];
  12526. subMesh._rebuild();
  12527. }
  12528. };
  12529. AbstractMesh.prototype._resyncLightSources = function () {
  12530. this._lightSources.length = 0;
  12531. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12532. var light = _a[_i];
  12533. if (!light.isEnabled()) {
  12534. continue;
  12535. }
  12536. if (light.canAffectMesh(this)) {
  12537. this._lightSources.push(light);
  12538. }
  12539. }
  12540. this._markSubMeshesAsLightDirty();
  12541. };
  12542. AbstractMesh.prototype._resyncLighSource = function (light) {
  12543. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12544. var index = this._lightSources.indexOf(light);
  12545. if (index === -1) {
  12546. if (!isIn) {
  12547. return;
  12548. }
  12549. this._lightSources.push(light);
  12550. }
  12551. else {
  12552. if (isIn) {
  12553. return;
  12554. }
  12555. this._lightSources.splice(index, 1);
  12556. }
  12557. this._markSubMeshesAsLightDirty();
  12558. };
  12559. AbstractMesh.prototype._removeLightSource = function (light) {
  12560. var index = this._lightSources.indexOf(light);
  12561. if (index === -1) {
  12562. return;
  12563. }
  12564. this._lightSources.splice(index, 1);
  12565. };
  12566. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12567. if (!this.subMeshes) {
  12568. return;
  12569. }
  12570. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12571. var subMesh = _a[_i];
  12572. if (subMesh._materialDefines) {
  12573. func(subMesh._materialDefines);
  12574. }
  12575. }
  12576. };
  12577. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12578. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12579. };
  12580. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12581. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12582. };
  12583. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12584. if (!this.subMeshes) {
  12585. return;
  12586. }
  12587. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12588. var subMesh = _a[_i];
  12589. var material = subMesh.getMaterial();
  12590. if (material) {
  12591. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12592. }
  12593. }
  12594. };
  12595. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12596. /**
  12597. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12598. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12599. * Default : (0.0, 0.0, 0.0)
  12600. */
  12601. get: function () {
  12602. return this._rotation;
  12603. },
  12604. set: function (newRotation) {
  12605. this._rotation = newRotation;
  12606. },
  12607. enumerable: true,
  12608. configurable: true
  12609. });
  12610. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12611. /**
  12612. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12613. * Default : (1.0, 1.0, 1.0)
  12614. */
  12615. get: function () {
  12616. return this._scaling;
  12617. },
  12618. set: function (newScaling) {
  12619. this._scaling = newScaling;
  12620. if (this.physicsImpostor) {
  12621. this.physicsImpostor.forceUpdate();
  12622. }
  12623. },
  12624. enumerable: true,
  12625. configurable: true
  12626. });
  12627. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12628. /**
  12629. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12630. * It's null by default.
  12631. * 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)
  12632. */
  12633. get: function () {
  12634. return this._rotationQuaternion;
  12635. },
  12636. set: function (quaternion) {
  12637. this._rotationQuaternion = quaternion;
  12638. //reset the rotation vector.
  12639. if (quaternion && this.rotation.length()) {
  12640. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12641. }
  12642. },
  12643. enumerable: true,
  12644. configurable: true
  12645. });
  12646. // Methods
  12647. /**
  12648. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12649. * Returns the AbstractMesh.
  12650. */
  12651. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12652. this._poseMatrix.copyFrom(matrix);
  12653. return this;
  12654. };
  12655. /**
  12656. * Returns the mesh Pose matrix.
  12657. * Returned object : Matrix
  12658. */
  12659. AbstractMesh.prototype.getPoseMatrix = function () {
  12660. return this._poseMatrix;
  12661. };
  12662. /**
  12663. * Disables the mesh edger rendering mode.
  12664. * Returns the AbstractMesh.
  12665. */
  12666. AbstractMesh.prototype.disableEdgesRendering = function () {
  12667. if (this._edgesRenderer !== undefined) {
  12668. this._edgesRenderer.dispose();
  12669. this._edgesRenderer = undefined;
  12670. }
  12671. return this;
  12672. };
  12673. /**
  12674. * Enables the edge rendering mode on the mesh.
  12675. * This mode makes the mesh edges visible.
  12676. * Returns the AbstractMesh.
  12677. */
  12678. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12679. if (epsilon === void 0) { epsilon = 0.95; }
  12680. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12681. this.disableEdgesRendering();
  12682. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12683. return this;
  12684. };
  12685. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12686. /**
  12687. * Returns true if the mesh is blocked. Used by the class Mesh.
  12688. * Returns the boolean `false` by default.
  12689. */
  12690. get: function () {
  12691. return false;
  12692. },
  12693. enumerable: true,
  12694. configurable: true
  12695. });
  12696. /**
  12697. * Returns the mesh itself by default, used by the class Mesh.
  12698. * Returned type : AbstractMesh
  12699. */
  12700. AbstractMesh.prototype.getLOD = function (camera) {
  12701. return this;
  12702. };
  12703. /**
  12704. * Returns 0 by default, used by the class Mesh.
  12705. * Returns an integer.
  12706. */
  12707. AbstractMesh.prototype.getTotalVertices = function () {
  12708. return 0;
  12709. };
  12710. /**
  12711. * Returns null by default, used by the class Mesh.
  12712. * Returned type : integer array
  12713. */
  12714. AbstractMesh.prototype.getIndices = function () {
  12715. return null;
  12716. };
  12717. /**
  12718. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12719. * Returned type : float array or Float32Array
  12720. */
  12721. AbstractMesh.prototype.getVerticesData = function (kind) {
  12722. return null;
  12723. };
  12724. /**
  12725. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12726. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12727. * The `data` are either a numeric array either a Float32Array.
  12728. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12729. * 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).
  12730. * Note that a new underlying VertexBuffer object is created each call.
  12731. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12732. *
  12733. * Possible `kind` values :
  12734. * - BABYLON.VertexBuffer.PositionKind
  12735. * - BABYLON.VertexBuffer.UVKind
  12736. * - BABYLON.VertexBuffer.UV2Kind
  12737. * - BABYLON.VertexBuffer.UV3Kind
  12738. * - BABYLON.VertexBuffer.UV4Kind
  12739. * - BABYLON.VertexBuffer.UV5Kind
  12740. * - BABYLON.VertexBuffer.UV6Kind
  12741. * - BABYLON.VertexBuffer.ColorKind
  12742. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12743. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12744. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12745. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12746. *
  12747. * Returns the Mesh.
  12748. */
  12749. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12750. return null;
  12751. };
  12752. /**
  12753. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12754. * If the mesh has no geometry, it is simply returned as it is.
  12755. * The `data` are either a numeric array either a Float32Array.
  12756. * No new underlying VertexBuffer object is created.
  12757. * 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.
  12758. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12759. *
  12760. * Possible `kind` values :
  12761. * - BABYLON.VertexBuffer.PositionKind
  12762. * - BABYLON.VertexBuffer.UVKind
  12763. * - BABYLON.VertexBuffer.UV2Kind
  12764. * - BABYLON.VertexBuffer.UV3Kind
  12765. * - BABYLON.VertexBuffer.UV4Kind
  12766. * - BABYLON.VertexBuffer.UV5Kind
  12767. * - BABYLON.VertexBuffer.UV6Kind
  12768. * - BABYLON.VertexBuffer.ColorKind
  12769. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12770. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12771. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12772. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12773. *
  12774. * Returns the Mesh.
  12775. */
  12776. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12777. return null;
  12778. };
  12779. /**
  12780. * Sets the mesh indices.
  12781. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12782. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12783. * This method creates a new index buffer each call.
  12784. * Returns the Mesh.
  12785. */
  12786. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12787. return null;
  12788. };
  12789. /** Returns false by default, used by the class Mesh.
  12790. * Returns a boolean
  12791. */
  12792. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12793. return false;
  12794. };
  12795. /**
  12796. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12797. * Returns a BoundingInfo
  12798. */
  12799. AbstractMesh.prototype.getBoundingInfo = function () {
  12800. if (this._masterMesh) {
  12801. return this._masterMesh.getBoundingInfo();
  12802. }
  12803. if (!this._boundingInfo) {
  12804. this._updateBoundingInfo();
  12805. }
  12806. return this._boundingInfo;
  12807. };
  12808. /**
  12809. * Sets a mesh new object BoundingInfo.
  12810. * Returns the AbstractMesh.
  12811. */
  12812. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12813. this._boundingInfo = boundingInfo;
  12814. return this;
  12815. };
  12816. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12817. get: function () {
  12818. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12819. },
  12820. enumerable: true,
  12821. configurable: true
  12822. });
  12823. AbstractMesh.prototype._preActivate = function () {
  12824. };
  12825. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12826. };
  12827. AbstractMesh.prototype._activate = function (renderId) {
  12828. this._renderId = renderId;
  12829. };
  12830. /**
  12831. * Returns the last update of the World matrix
  12832. * Returns a Matrix.
  12833. */
  12834. AbstractMesh.prototype.getWorldMatrix = function () {
  12835. if (this._masterMesh) {
  12836. return this._masterMesh.getWorldMatrix();
  12837. }
  12838. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12839. this.computeWorldMatrix();
  12840. }
  12841. return this._worldMatrix;
  12842. };
  12843. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12844. /**
  12845. * Returns directly the last state of the mesh World matrix.
  12846. * A Matrix is returned.
  12847. */
  12848. get: function () {
  12849. return this._worldMatrix;
  12850. },
  12851. enumerable: true,
  12852. configurable: true
  12853. });
  12854. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12855. /**
  12856. * Returns the current mesh absolute position.
  12857. * Retuns a Vector3.
  12858. */
  12859. get: function () {
  12860. return this._absolutePosition;
  12861. },
  12862. enumerable: true,
  12863. configurable: true
  12864. });
  12865. /**
  12866. * Prevents the World matrix to be computed any longer.
  12867. * Returns the AbstractMesh.
  12868. */
  12869. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12870. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12871. this.computeWorldMatrix(true);
  12872. this._isWorldMatrixFrozen = true;
  12873. return this;
  12874. };
  12875. /**
  12876. * Allows back the World matrix computation.
  12877. * Returns the AbstractMesh.
  12878. */
  12879. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12880. this._isWorldMatrixFrozen = false;
  12881. this.computeWorldMatrix(true);
  12882. return this;
  12883. };
  12884. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12885. /**
  12886. * True if the World matrix has been frozen.
  12887. * Returns a boolean.
  12888. */
  12889. get: function () {
  12890. return this._isWorldMatrixFrozen;
  12891. },
  12892. enumerable: true,
  12893. configurable: true
  12894. });
  12895. /**
  12896. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12897. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12898. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12899. * The passed axis is also normalized.
  12900. * Returns the AbstractMesh.
  12901. */
  12902. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12903. axis.normalize();
  12904. if (!this.rotationQuaternion) {
  12905. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12906. this.rotation = BABYLON.Vector3.Zero();
  12907. }
  12908. var rotationQuaternion;
  12909. if (!space || space === BABYLON.Space.LOCAL) {
  12910. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12911. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12912. }
  12913. else {
  12914. if (this.parent) {
  12915. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12916. invertParentWorldMatrix.invert();
  12917. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12918. }
  12919. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12920. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12921. }
  12922. return this;
  12923. };
  12924. /**
  12925. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12926. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12927. * The passed axis is also normalized.
  12928. * Returns the AbstractMesh.
  12929. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12930. */
  12931. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12932. axis.normalize();
  12933. if (!this.rotationQuaternion) {
  12934. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12935. this.rotation.copyFromFloats(0, 0, 0);
  12936. }
  12937. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12938. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12939. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12940. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12941. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12942. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12943. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12944. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12945. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12946. return this;
  12947. };
  12948. /**
  12949. * Translates the mesh along the axis vector for the passed distance in the given space.
  12950. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12951. * Returns the AbstractMesh.
  12952. */
  12953. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12954. var displacementVector = axis.scale(distance);
  12955. if (!space || space === BABYLON.Space.LOCAL) {
  12956. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12957. this.setPositionWithLocalVector(tempV3);
  12958. }
  12959. else {
  12960. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12961. }
  12962. return this;
  12963. };
  12964. /**
  12965. * Adds a rotation step to the mesh current rotation.
  12966. * x, y, z are Euler angles expressed in radians.
  12967. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12968. * This means this rotation is made in the mesh local space only.
  12969. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12970. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12971. * ```javascript
  12972. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12973. * ```
  12974. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12975. * 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.
  12976. * Returns the AbstractMesh.
  12977. */
  12978. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12979. var rotationQuaternion;
  12980. if (this.rotationQuaternion) {
  12981. rotationQuaternion = this.rotationQuaternion;
  12982. }
  12983. else {
  12984. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12985. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12986. }
  12987. var accumulation = BABYLON.Tmp.Quaternion[0];
  12988. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12989. rotationQuaternion.multiplyInPlace(accumulation);
  12990. if (!this.rotationQuaternion) {
  12991. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12992. }
  12993. return this;
  12994. };
  12995. /**
  12996. * Retuns the mesh absolute position in the World.
  12997. * Returns a Vector3.
  12998. */
  12999. AbstractMesh.prototype.getAbsolutePosition = function () {
  13000. this.computeWorldMatrix();
  13001. return this._absolutePosition;
  13002. };
  13003. /**
  13004. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13005. * Returns the AbstractMesh.
  13006. */
  13007. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13008. if (!absolutePosition) {
  13009. return;
  13010. }
  13011. var absolutePositionX;
  13012. var absolutePositionY;
  13013. var absolutePositionZ;
  13014. if (absolutePosition.x === undefined) {
  13015. if (arguments.length < 3) {
  13016. return;
  13017. }
  13018. absolutePositionX = arguments[0];
  13019. absolutePositionY = arguments[1];
  13020. absolutePositionZ = arguments[2];
  13021. }
  13022. else {
  13023. absolutePositionX = absolutePosition.x;
  13024. absolutePositionY = absolutePosition.y;
  13025. absolutePositionZ = absolutePosition.z;
  13026. }
  13027. if (this.parent) {
  13028. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13029. invertParentWorldMatrix.invert();
  13030. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13031. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13032. }
  13033. else {
  13034. this.position.x = absolutePositionX;
  13035. this.position.y = absolutePositionY;
  13036. this.position.z = absolutePositionZ;
  13037. }
  13038. return this;
  13039. };
  13040. // ================================== Point of View Movement =================================
  13041. /**
  13042. * Perform relative position change from the point of view of behind the front of the mesh.
  13043. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13044. * Supports definition of mesh facing forward or backward.
  13045. * @param {number} amountRight
  13046. * @param {number} amountUp
  13047. * @param {number} amountForward
  13048. *
  13049. * Returns the AbstractMesh.
  13050. */
  13051. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13052. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13053. return this;
  13054. };
  13055. /**
  13056. * Calculate relative position change from the point of view of behind the front of the mesh.
  13057. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13058. * Supports definition of mesh facing forward or backward.
  13059. * @param {number} amountRight
  13060. * @param {number} amountUp
  13061. * @param {number} amountForward
  13062. *
  13063. * Returns a new Vector3.
  13064. */
  13065. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13066. var rotMatrix = new BABYLON.Matrix();
  13067. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13068. rotQuaternion.toRotationMatrix(rotMatrix);
  13069. var translationDelta = BABYLON.Vector3.Zero();
  13070. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13071. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13072. return translationDelta;
  13073. };
  13074. // ================================== Point of View Rotation =================================
  13075. /**
  13076. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13077. * Supports definition of mesh facing forward or backward.
  13078. * @param {number} flipBack
  13079. * @param {number} twirlClockwise
  13080. * @param {number} tiltRight
  13081. *
  13082. * Returns the AbstractMesh.
  13083. */
  13084. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13085. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13086. return this;
  13087. };
  13088. /**
  13089. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13090. * Supports definition of mesh facing forward or backward.
  13091. * @param {number} flipBack
  13092. * @param {number} twirlClockwise
  13093. * @param {number} tiltRight
  13094. *
  13095. * Returns a new Vector3.
  13096. */
  13097. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13098. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13099. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13100. };
  13101. /**
  13102. * Sets a new pivot matrix to the mesh.
  13103. * Returns the AbstractMesh.
  13104. */
  13105. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  13106. this._pivotMatrix = matrix;
  13107. this._cache.pivotMatrixUpdated = true;
  13108. return this;
  13109. };
  13110. /**
  13111. * Returns the mesh pivot matrix.
  13112. * Default : Identity.
  13113. * A Matrix is returned.
  13114. */
  13115. AbstractMesh.prototype.getPivotMatrix = function () {
  13116. return this._pivotMatrix;
  13117. };
  13118. AbstractMesh.prototype._isSynchronized = function () {
  13119. if (this._isDirty) {
  13120. return false;
  13121. }
  13122. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13123. return false;
  13124. if (this._cache.pivotMatrixUpdated) {
  13125. return false;
  13126. }
  13127. if (this.infiniteDistance) {
  13128. return false;
  13129. }
  13130. if (!this._cache.position.equals(this.position))
  13131. return false;
  13132. if (this.rotationQuaternion) {
  13133. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13134. return false;
  13135. }
  13136. if (!this._cache.rotation.equals(this.rotation))
  13137. return false;
  13138. if (!this._cache.scaling.equals(this.scaling))
  13139. return false;
  13140. return true;
  13141. };
  13142. AbstractMesh.prototype._initCache = function () {
  13143. _super.prototype._initCache.call(this);
  13144. this._cache.localMatrixUpdated = false;
  13145. this._cache.position = BABYLON.Vector3.Zero();
  13146. this._cache.scaling = BABYLON.Vector3.Zero();
  13147. this._cache.rotation = BABYLON.Vector3.Zero();
  13148. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13149. this._cache.billboardMode = -1;
  13150. };
  13151. AbstractMesh.prototype.markAsDirty = function (property) {
  13152. if (property === "rotation") {
  13153. this.rotationQuaternion = null;
  13154. }
  13155. this._currentRenderId = Number.MAX_VALUE;
  13156. this._isDirty = true;
  13157. return this;
  13158. };
  13159. /**
  13160. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13161. * Returns the AbstractMesh.
  13162. */
  13163. AbstractMesh.prototype._updateBoundingInfo = function () {
  13164. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13165. this._boundingInfo.update(this.worldMatrixFromCache);
  13166. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13167. return this;
  13168. };
  13169. /**
  13170. * Update a mesh's children BoundingInfo objects only.
  13171. * Returns the AbstractMesh.
  13172. */
  13173. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13174. if (!this.subMeshes) {
  13175. return;
  13176. }
  13177. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13178. var subMesh = this.subMeshes[subIndex];
  13179. if (!subMesh.IsGlobal) {
  13180. subMesh.updateBoundingInfo(matrix);
  13181. }
  13182. }
  13183. return this;
  13184. };
  13185. /**
  13186. * Computes the mesh World matrix and returns it.
  13187. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13188. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13189. * If the parameter `force`is set to `true`, the actual computation is done.
  13190. * Returns the mesh World Matrix.
  13191. */
  13192. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13193. if (this._isWorldMatrixFrozen) {
  13194. return this._worldMatrix;
  13195. }
  13196. if (!force && this.isSynchronized(true)) {
  13197. this._currentRenderId = this.getScene().getRenderId();
  13198. return this._worldMatrix;
  13199. }
  13200. this._cache.position.copyFrom(this.position);
  13201. this._cache.scaling.copyFrom(this.scaling);
  13202. this._cache.pivotMatrixUpdated = false;
  13203. this._cache.billboardMode = this.billboardMode;
  13204. this._currentRenderId = this.getScene().getRenderId();
  13205. this._isDirty = false;
  13206. // Scaling
  13207. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13208. // Rotation
  13209. //rotate, if quaternion is set and rotation was used
  13210. if (this.rotationQuaternion) {
  13211. var len = this.rotation.length();
  13212. if (len) {
  13213. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13214. this.rotation.copyFromFloats(0, 0, 0);
  13215. }
  13216. }
  13217. if (this.rotationQuaternion) {
  13218. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13219. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13220. }
  13221. else {
  13222. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13223. this._cache.rotation.copyFrom(this.rotation);
  13224. }
  13225. // Translation
  13226. if (this.infiniteDistance && !this.parent) {
  13227. var camera = this.getScene().activeCamera;
  13228. if (camera) {
  13229. var cameraWorldMatrix = camera.getWorldMatrix();
  13230. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13231. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13232. }
  13233. }
  13234. else {
  13235. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13236. }
  13237. // Composing transformations
  13238. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13239. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13240. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13241. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13242. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13243. // Need to decompose each rotation here
  13244. var currentPosition = BABYLON.Tmp.Vector3[3];
  13245. if (this.parent && this.parent.getWorldMatrix) {
  13246. if (this._meshToBoneReferal) {
  13247. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13248. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13249. }
  13250. else {
  13251. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13252. }
  13253. }
  13254. else {
  13255. currentPosition.copyFrom(this.position);
  13256. }
  13257. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13258. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13259. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13260. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13261. }
  13262. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13263. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13264. }
  13265. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13266. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13267. }
  13268. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13269. }
  13270. else {
  13271. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13272. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13273. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13274. }
  13275. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13276. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13277. }
  13278. // Local world
  13279. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13280. // Parent
  13281. if (this.parent && this.parent.getWorldMatrix) {
  13282. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13283. if (this._meshToBoneReferal) {
  13284. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13285. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13286. }
  13287. else {
  13288. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13289. }
  13290. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13291. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13292. this._worldMatrix.copyFrom(this._localWorld);
  13293. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13294. }
  13295. else {
  13296. if (this._meshToBoneReferal) {
  13297. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13298. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13299. }
  13300. else {
  13301. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13302. }
  13303. }
  13304. this._markSyncedWithParent();
  13305. }
  13306. else {
  13307. this._worldMatrix.copyFrom(this._localWorld);
  13308. }
  13309. // Bounding info
  13310. this._updateBoundingInfo();
  13311. // Absolute position
  13312. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13313. // Callbacks
  13314. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13315. if (!this._poseMatrix) {
  13316. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13317. }
  13318. return this._worldMatrix;
  13319. };
  13320. /**
  13321. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13322. * @param func: callback function to add
  13323. *
  13324. * Returns the AbstractMesh.
  13325. */
  13326. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13327. this.onAfterWorldMatrixUpdateObservable.add(func);
  13328. return this;
  13329. };
  13330. /**
  13331. * Removes a registered callback function.
  13332. * Returns the AbstractMesh.
  13333. */
  13334. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13335. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13336. return this;
  13337. };
  13338. /**
  13339. * Sets the mesh position in its local space.
  13340. * Returns the AbstractMesh.
  13341. */
  13342. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13343. this.computeWorldMatrix();
  13344. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13345. return this;
  13346. };
  13347. /**
  13348. * Returns the mesh position in the local space from the current World matrix values.
  13349. * Returns a new Vector3.
  13350. */
  13351. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13352. this.computeWorldMatrix();
  13353. var invLocalWorldMatrix = this._localWorld.clone();
  13354. invLocalWorldMatrix.invert();
  13355. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13356. };
  13357. /**
  13358. * Translates the mesh along the passed Vector3 in its local space.
  13359. * Returns the AbstractMesh.
  13360. */
  13361. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13362. this.computeWorldMatrix(true);
  13363. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13364. return this;
  13365. };
  13366. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13367. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13368. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13369. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13370. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13371. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13372. /// <returns>Mesh oriented towards targetMesh</returns>
  13373. if (yawCor === void 0) { yawCor = 0; }
  13374. if (pitchCor === void 0) { pitchCor = 0; }
  13375. if (rollCor === void 0) { rollCor = 0; }
  13376. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13377. var dv = AbstractMesh._lookAtVectorCache;
  13378. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13379. targetPoint.subtractToRef(pos, dv);
  13380. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13381. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13382. var pitch = Math.atan2(dv.y, len);
  13383. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13384. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13385. return this;
  13386. };
  13387. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13388. this._meshToBoneReferal = affectedMesh;
  13389. this.parent = bone;
  13390. if (bone.getWorldMatrix().determinant() < 0) {
  13391. this.scalingDeterminant *= -1;
  13392. }
  13393. return this;
  13394. };
  13395. AbstractMesh.prototype.detachFromBone = function () {
  13396. if (this.parent.getWorldMatrix().determinant() < 0) {
  13397. this.scalingDeterminant *= -1;
  13398. }
  13399. this._meshToBoneReferal = null;
  13400. this.parent = null;
  13401. return this;
  13402. };
  13403. /**
  13404. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13405. * A mesh is in the frustum if its bounding box intersects the frustum.
  13406. * Boolean returned.
  13407. */
  13408. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13409. return this._boundingInfo.isInFrustum(frustumPlanes);
  13410. };
  13411. /**
  13412. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13413. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13414. * Boolean returned.
  13415. */
  13416. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13417. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13418. ;
  13419. };
  13420. /**
  13421. * True if the mesh intersects another mesh or a SolidParticle object.
  13422. * 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)
  13423. * Returns a boolean.
  13424. */
  13425. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13426. if (!this._boundingInfo || !mesh._boundingInfo) {
  13427. return false;
  13428. }
  13429. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13430. };
  13431. /**
  13432. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13433. * Returns a boolean.
  13434. */
  13435. AbstractMesh.prototype.intersectsPoint = function (point) {
  13436. if (!this._boundingInfo) {
  13437. return false;
  13438. }
  13439. return this._boundingInfo.intersectsPoint(point);
  13440. };
  13441. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13442. return this.physicsImpostor;
  13443. };
  13444. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13445. if (!camera) {
  13446. camera = this.getScene().activeCamera;
  13447. }
  13448. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13449. };
  13450. /**
  13451. * Returns the distance from the mesh to the active camera.
  13452. * Returns a float.
  13453. */
  13454. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13455. if (!camera) {
  13456. camera = this.getScene().activeCamera;
  13457. }
  13458. return this.absolutePosition.subtract(camera.position).length();
  13459. };
  13460. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13461. if (!this.physicsImpostor) {
  13462. return;
  13463. }
  13464. this.physicsImpostor.applyImpulse(force, contactPoint);
  13465. return this;
  13466. };
  13467. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13468. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13469. return;
  13470. }
  13471. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13472. mainPivot: pivot1,
  13473. connectedPivot: pivot2,
  13474. nativeParams: options
  13475. });
  13476. return this;
  13477. };
  13478. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13479. // Collisions
  13480. /**
  13481. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13482. * Default `false`.
  13483. */
  13484. get: function () {
  13485. return this._checkCollisions;
  13486. },
  13487. set: function (collisionEnabled) {
  13488. this._checkCollisions = collisionEnabled;
  13489. if (this.getScene().workerCollisions) {
  13490. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13491. }
  13492. },
  13493. enumerable: true,
  13494. configurable: true
  13495. });
  13496. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  13497. var globalPosition = this.getAbsolutePosition();
  13498. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13499. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13500. if (!this._collider) {
  13501. this._collider = new BABYLON.Collider();
  13502. }
  13503. this._collider.radius = this.ellipsoid;
  13504. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13505. return this;
  13506. };
  13507. // Submeshes octree
  13508. /**
  13509. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13510. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13511. * Returns an Octree of submeshes.
  13512. */
  13513. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13514. if (maxCapacity === void 0) { maxCapacity = 64; }
  13515. if (maxDepth === void 0) { maxDepth = 2; }
  13516. if (!this._submeshesOctree) {
  13517. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13518. }
  13519. this.computeWorldMatrix(true);
  13520. // Update octree
  13521. var bbox = this.getBoundingInfo().boundingBox;
  13522. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13523. return this._submeshesOctree;
  13524. };
  13525. // Collisions
  13526. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13527. this._generatePointsArray();
  13528. // Transformation
  13529. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13530. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13531. subMesh._lastColliderWorldVertices = [];
  13532. subMesh._trianglePlanes = [];
  13533. var start = subMesh.verticesStart;
  13534. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13535. for (var i = start; i < end; i++) {
  13536. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13537. }
  13538. }
  13539. // Collide
  13540. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13541. if (collider.collisionFound) {
  13542. collider.collidedMesh = this;
  13543. }
  13544. return this;
  13545. };
  13546. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13547. var subMeshes;
  13548. var len;
  13549. // Octrees
  13550. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13551. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13552. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13553. len = intersections.length;
  13554. subMeshes = intersections.data;
  13555. }
  13556. else {
  13557. subMeshes = this.subMeshes;
  13558. len = subMeshes.length;
  13559. }
  13560. for (var index = 0; index < len; index++) {
  13561. var subMesh = subMeshes[index];
  13562. // Bounding test
  13563. if (len > 1 && !subMesh._checkCollision(collider))
  13564. continue;
  13565. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13566. }
  13567. return this;
  13568. };
  13569. AbstractMesh.prototype._checkCollision = function (collider) {
  13570. // Bounding box test
  13571. if (!this._boundingInfo._checkCollision(collider))
  13572. return this;
  13573. // Transformation matrix
  13574. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13575. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13576. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13577. return this;
  13578. };
  13579. // Picking
  13580. AbstractMesh.prototype._generatePointsArray = function () {
  13581. return false;
  13582. };
  13583. /**
  13584. * Checks if the passed Ray intersects with the mesh.
  13585. * Returns an object PickingInfo.
  13586. */
  13587. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13588. var pickingInfo = new BABYLON.PickingInfo();
  13589. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13590. return pickingInfo;
  13591. }
  13592. if (!this._generatePointsArray()) {
  13593. return pickingInfo;
  13594. }
  13595. var intersectInfo = null;
  13596. // Octrees
  13597. var subMeshes;
  13598. var len;
  13599. if (this._submeshesOctree && this.useOctreeForPicking) {
  13600. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13601. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13602. len = intersections.length;
  13603. subMeshes = intersections.data;
  13604. }
  13605. else {
  13606. subMeshes = this.subMeshes;
  13607. len = subMeshes.length;
  13608. }
  13609. for (var index = 0; index < len; index++) {
  13610. var subMesh = subMeshes[index];
  13611. // Bounding test
  13612. if (len > 1 && !subMesh.canIntersects(ray))
  13613. continue;
  13614. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13615. if (currentIntersectInfo) {
  13616. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13617. intersectInfo = currentIntersectInfo;
  13618. intersectInfo.subMeshId = index;
  13619. if (fastCheck) {
  13620. break;
  13621. }
  13622. }
  13623. }
  13624. }
  13625. if (intersectInfo) {
  13626. // Get picked point
  13627. var world = this.getWorldMatrix();
  13628. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13629. var direction = ray.direction.clone();
  13630. direction = direction.scale(intersectInfo.distance);
  13631. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13632. var pickedPoint = worldOrigin.add(worldDirection);
  13633. // Return result
  13634. pickingInfo.hit = true;
  13635. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13636. pickingInfo.pickedPoint = pickedPoint;
  13637. pickingInfo.pickedMesh = this;
  13638. pickingInfo.bu = intersectInfo.bu;
  13639. pickingInfo.bv = intersectInfo.bv;
  13640. pickingInfo.faceId = intersectInfo.faceId;
  13641. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13642. return pickingInfo;
  13643. }
  13644. return pickingInfo;
  13645. };
  13646. /**
  13647. * Clones the mesh, used by the class Mesh.
  13648. * Just returns `null` for an AbstractMesh.
  13649. */
  13650. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13651. return null;
  13652. };
  13653. /**
  13654. * Disposes all the mesh submeshes.
  13655. * Returns the AbstractMesh.
  13656. */
  13657. AbstractMesh.prototype.releaseSubMeshes = function () {
  13658. if (this.subMeshes) {
  13659. while (this.subMeshes.length) {
  13660. this.subMeshes[0].dispose();
  13661. }
  13662. }
  13663. else {
  13664. this.subMeshes = new Array();
  13665. }
  13666. return this;
  13667. };
  13668. /**
  13669. * Disposes the AbstractMesh.
  13670. * Some internal references are kept for further use.
  13671. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13672. * Returns nothing.
  13673. */
  13674. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13675. var _this = this;
  13676. var index;
  13677. // Action manager
  13678. if (this.actionManager) {
  13679. this.actionManager.dispose();
  13680. this.actionManager = null;
  13681. }
  13682. // Skeleton
  13683. this.skeleton = null;
  13684. // Animations
  13685. this.getScene().stopAnimation(this);
  13686. // Physics
  13687. if (this.physicsImpostor) {
  13688. this.physicsImpostor.dispose();
  13689. }
  13690. // Intersections in progress
  13691. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13692. var other = this._intersectionsInProgress[index];
  13693. var pos = other._intersectionsInProgress.indexOf(this);
  13694. other._intersectionsInProgress.splice(pos, 1);
  13695. }
  13696. this._intersectionsInProgress = [];
  13697. // Lights
  13698. var lights = this.getScene().lights;
  13699. lights.forEach(function (light) {
  13700. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13701. if (meshIndex !== -1) {
  13702. light.includedOnlyMeshes.splice(meshIndex, 1);
  13703. }
  13704. meshIndex = light.excludedMeshes.indexOf(_this);
  13705. if (meshIndex !== -1) {
  13706. light.excludedMeshes.splice(meshIndex, 1);
  13707. }
  13708. // Shadow generators
  13709. var generator = light.getShadowGenerator();
  13710. if (generator) {
  13711. var shadowMap = generator.getShadowMap();
  13712. meshIndex = shadowMap.renderList.indexOf(_this);
  13713. if (meshIndex !== -1) {
  13714. shadowMap.renderList.splice(meshIndex, 1);
  13715. }
  13716. }
  13717. });
  13718. // Edges
  13719. if (this._edgesRenderer) {
  13720. this._edgesRenderer.dispose();
  13721. this._edgesRenderer = null;
  13722. }
  13723. // SubMeshes
  13724. if (this.getClassName() !== "InstancedMesh") {
  13725. this.releaseSubMeshes();
  13726. }
  13727. // Octree
  13728. var sceneOctree = this.getScene().selectionOctree;
  13729. if (sceneOctree) {
  13730. var index = sceneOctree.dynamicContent.indexOf(this);
  13731. if (index !== -1) {
  13732. sceneOctree.dynamicContent.splice(index, 1);
  13733. }
  13734. }
  13735. // Query
  13736. var engine = this.getScene().getEngine();
  13737. if (this._occlusionQuery) {
  13738. this._isOcclusionQueryInProgress = false;
  13739. engine.deleteQuery(this._occlusionQuery);
  13740. this._occlusionQuery = null;
  13741. }
  13742. // Engine
  13743. engine.wipeCaches();
  13744. // Remove from scene
  13745. this.getScene().removeMesh(this);
  13746. if (!doNotRecurse) {
  13747. // Particles
  13748. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13749. if (this.getScene().particleSystems[index].emitter === this) {
  13750. this.getScene().particleSystems[index].dispose();
  13751. index--;
  13752. }
  13753. }
  13754. // Children
  13755. var objects = this.getDescendants(true);
  13756. for (index = 0; index < objects.length; index++) {
  13757. objects[index].dispose();
  13758. }
  13759. }
  13760. else {
  13761. var childMeshes = this.getChildMeshes(true);
  13762. for (index = 0; index < childMeshes.length; index++) {
  13763. var child = childMeshes[index];
  13764. child.parent = null;
  13765. child.computeWorldMatrix(true);
  13766. }
  13767. }
  13768. // facet data
  13769. if (this._facetDataEnabled) {
  13770. this.disableFacetData();
  13771. }
  13772. this.onAfterWorldMatrixUpdateObservable.clear();
  13773. this.onCollideObservable.clear();
  13774. this.onCollisionPositionChangeObservable.clear();
  13775. this._isDisposed = true;
  13776. _super.prototype.dispose.call(this);
  13777. };
  13778. /**
  13779. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13780. * This Vector3 is expressed in the World space.
  13781. */
  13782. AbstractMesh.prototype.getDirection = function (localAxis) {
  13783. var result = BABYLON.Vector3.Zero();
  13784. this.getDirectionToRef(localAxis, result);
  13785. return result;
  13786. };
  13787. /**
  13788. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13789. * localAxis is expressed in the mesh local space.
  13790. * result is computed in the Wordl space from the mesh World matrix.
  13791. * Returns the AbstractMesh.
  13792. */
  13793. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13794. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13795. return this;
  13796. };
  13797. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13798. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13799. if (this.getScene().getRenderId() == 0) {
  13800. this.computeWorldMatrix(true);
  13801. }
  13802. var wm = this.getWorldMatrix();
  13803. if (space == BABYLON.Space.WORLD) {
  13804. var tmat = BABYLON.Tmp.Matrix[0];
  13805. wm.invertToRef(tmat);
  13806. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13807. }
  13808. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13809. this._pivotMatrix.m[12] = -point.x;
  13810. this._pivotMatrix.m[13] = -point.y;
  13811. this._pivotMatrix.m[14] = -point.z;
  13812. this._cache.pivotMatrixUpdated = true;
  13813. return this;
  13814. };
  13815. /**
  13816. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13817. */
  13818. AbstractMesh.prototype.getPivotPoint = function () {
  13819. var point = BABYLON.Vector3.Zero();
  13820. this.getPivotPointToRef(point);
  13821. return point;
  13822. };
  13823. /**
  13824. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13825. * Returns the AbstractMesh.
  13826. */
  13827. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13828. result.x = -this._pivotMatrix.m[12];
  13829. result.y = -this._pivotMatrix.m[13];
  13830. result.z = -this._pivotMatrix.m[14];
  13831. return this;
  13832. };
  13833. /**
  13834. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13835. */
  13836. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13837. var point = BABYLON.Vector3.Zero();
  13838. this.getAbsolutePivotPointToRef(point);
  13839. return point;
  13840. };
  13841. /**
  13842. * Defines the passed mesh as the parent of the current mesh.
  13843. * Returns the AbstractMesh.
  13844. */
  13845. AbstractMesh.prototype.setParent = function (mesh) {
  13846. var child = this;
  13847. var parent = mesh;
  13848. if (mesh == null) {
  13849. var rotation = BABYLON.Tmp.Quaternion[0];
  13850. var position = BABYLON.Tmp.Vector3[0];
  13851. var scale = BABYLON.Tmp.Vector3[1];
  13852. child.getWorldMatrix().decompose(scale, rotation, position);
  13853. if (child.rotationQuaternion) {
  13854. child.rotationQuaternion.copyFrom(rotation);
  13855. }
  13856. else {
  13857. rotation.toEulerAnglesToRef(child.rotation);
  13858. }
  13859. child.position.x = position.x;
  13860. child.position.y = position.y;
  13861. child.position.z = position.z;
  13862. }
  13863. else {
  13864. var rotation = BABYLON.Tmp.Quaternion[0];
  13865. var position = BABYLON.Tmp.Vector3[0];
  13866. var scale = BABYLON.Tmp.Vector3[1];
  13867. var m1 = BABYLON.Tmp.Matrix[0];
  13868. var m2 = BABYLON.Tmp.Matrix[1];
  13869. parent.getWorldMatrix().decompose(scale, rotation, position);
  13870. rotation.toRotationMatrix(m1);
  13871. m2.setTranslation(position);
  13872. m2.multiplyToRef(m1, m1);
  13873. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13874. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13875. m.decompose(scale, rotation, position);
  13876. if (child.rotationQuaternion) {
  13877. child.rotationQuaternion.copyFrom(rotation);
  13878. }
  13879. else {
  13880. rotation.toEulerAnglesToRef(child.rotation);
  13881. }
  13882. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13883. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13884. m.decompose(scale, rotation, position);
  13885. child.position.x = position.x;
  13886. child.position.y = position.y;
  13887. child.position.z = position.z;
  13888. }
  13889. child.parent = parent;
  13890. return this;
  13891. };
  13892. /**
  13893. * Adds the passed mesh as a child to the current mesh.
  13894. * Returns the AbstractMesh.
  13895. */
  13896. AbstractMesh.prototype.addChild = function (mesh) {
  13897. mesh.setParent(this);
  13898. return this;
  13899. };
  13900. /**
  13901. * Removes the passed mesh from the current mesh children list.
  13902. * Returns the AbstractMesh.
  13903. */
  13904. AbstractMesh.prototype.removeChild = function (mesh) {
  13905. mesh.setParent(null);
  13906. return this;
  13907. };
  13908. /**
  13909. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13910. * Returns the AbstractMesh.
  13911. */
  13912. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13913. result.x = this._pivotMatrix.m[12];
  13914. result.y = this._pivotMatrix.m[13];
  13915. result.z = this._pivotMatrix.m[14];
  13916. this.getPivotPointToRef(result);
  13917. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13918. return this;
  13919. };
  13920. // Facet data
  13921. /**
  13922. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13923. * Returns the AbstractMesh.
  13924. */
  13925. AbstractMesh.prototype._initFacetData = function () {
  13926. if (!this._facetNormals) {
  13927. this._facetNormals = new Array();
  13928. }
  13929. if (!this._facetPositions) {
  13930. this._facetPositions = new Array();
  13931. }
  13932. if (!this._facetPartitioning) {
  13933. this._facetPartitioning = new Array();
  13934. }
  13935. this._facetNb = this.getIndices().length / 3;
  13936. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13937. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13938. for (var f = 0; f < this._facetNb; f++) {
  13939. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13940. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13941. }
  13942. this._facetDataEnabled = true;
  13943. return this;
  13944. };
  13945. /**
  13946. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13947. * This method can be called within the render loop.
  13948. * 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.
  13949. * Returns the AbstractMesh.
  13950. */
  13951. AbstractMesh.prototype.updateFacetData = function () {
  13952. if (!this._facetDataEnabled) {
  13953. this._initFacetData();
  13954. }
  13955. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13956. var indices = this.getIndices();
  13957. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13958. var bInfo = this.getBoundingInfo();
  13959. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13960. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13961. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13962. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13963. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13964. this._subDiv.max = this._partitioningSubdivisions;
  13965. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13966. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13967. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13968. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13969. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13970. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13971. // set the parameters for ComputeNormals()
  13972. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13973. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13974. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13975. this._facetParameters.bInfo = bInfo;
  13976. this._facetParameters.bbSize = this._bbSize;
  13977. this._facetParameters.subDiv = this._subDiv;
  13978. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13979. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13980. return this;
  13981. };
  13982. /**
  13983. * Returns the facetLocalNormals array.
  13984. * The normals are expressed in the mesh local space.
  13985. */
  13986. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13987. if (!this._facetNormals) {
  13988. this.updateFacetData();
  13989. }
  13990. return this._facetNormals;
  13991. };
  13992. /**
  13993. * Returns the facetLocalPositions array.
  13994. * The facet positions are expressed in the mesh local space.
  13995. */
  13996. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13997. if (!this._facetPositions) {
  13998. this.updateFacetData();
  13999. }
  14000. return this._facetPositions;
  14001. };
  14002. /**
  14003. * Returns the facetLocalPartioning array.
  14004. */
  14005. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14006. if (!this._facetPartitioning) {
  14007. this.updateFacetData();
  14008. }
  14009. return this._facetPartitioning;
  14010. };
  14011. /**
  14012. * Returns the i-th facet position in the world system.
  14013. * This method allocates a new Vector3 per call.
  14014. */
  14015. AbstractMesh.prototype.getFacetPosition = function (i) {
  14016. var pos = BABYLON.Vector3.Zero();
  14017. this.getFacetPositionToRef(i, pos);
  14018. return pos;
  14019. };
  14020. /**
  14021. * Sets the reference Vector3 with the i-th facet position in the world system.
  14022. * Returns the AbstractMesh.
  14023. */
  14024. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14025. var localPos = (this.getFacetLocalPositions())[i];
  14026. var world = this.getWorldMatrix();
  14027. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14028. return this;
  14029. };
  14030. /**
  14031. * Returns the i-th facet normal in the world system.
  14032. * This method allocates a new Vector3 per call.
  14033. */
  14034. AbstractMesh.prototype.getFacetNormal = function (i) {
  14035. var norm = BABYLON.Vector3.Zero();
  14036. this.getFacetNormalToRef(i, norm);
  14037. return norm;
  14038. };
  14039. /**
  14040. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14041. * Returns the AbstractMesh.
  14042. */
  14043. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14044. var localNorm = (this.getFacetLocalNormals())[i];
  14045. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14046. return this;
  14047. };
  14048. /**
  14049. * 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).
  14050. */
  14051. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14052. var bInfo = this.getBoundingInfo();
  14053. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14054. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14055. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14056. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14057. return null;
  14058. }
  14059. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14060. };
  14061. /**
  14062. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14063. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14064. * 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.
  14065. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14066. * 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.
  14067. */
  14068. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14069. if (checkFace === void 0) { checkFace = false; }
  14070. if (facing === void 0) { facing = true; }
  14071. var world = this.getWorldMatrix();
  14072. var invMat = BABYLON.Tmp.Matrix[5];
  14073. world.invertToRef(invMat);
  14074. var invVect = BABYLON.Tmp.Vector3[8];
  14075. var closest = null;
  14076. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14077. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14078. if (projected) {
  14079. // tranform the local computed projected vector to world coordinates
  14080. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14081. }
  14082. return closest;
  14083. };
  14084. /**
  14085. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14086. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14087. * 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.
  14088. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14089. * 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.
  14090. */
  14091. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14092. if (checkFace === void 0) { checkFace = false; }
  14093. if (facing === void 0) { facing = true; }
  14094. var closest = null;
  14095. var tmpx = 0.0;
  14096. var tmpy = 0.0;
  14097. var tmpz = 0.0;
  14098. var d = 0.0; // tmp dot facet normal * facet position
  14099. var t0 = 0.0;
  14100. var projx = 0.0;
  14101. var projy = 0.0;
  14102. var projz = 0.0;
  14103. // Get all the facets in the same partitioning block than (x, y, z)
  14104. var facetPositions = this.getFacetLocalPositions();
  14105. var facetNormals = this.getFacetLocalNormals();
  14106. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14107. if (!facetsInBlock) {
  14108. return null;
  14109. }
  14110. // Get the closest facet to (x, y, z)
  14111. var shortest = Number.MAX_VALUE; // init distance vars
  14112. var tmpDistance = shortest;
  14113. var fib; // current facet in the block
  14114. var norm; // current facet normal
  14115. var p0; // current facet barycenter position
  14116. // loop on all the facets in the current partitioning block
  14117. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14118. fib = facetsInBlock[idx];
  14119. norm = facetNormals[fib];
  14120. p0 = facetPositions[fib];
  14121. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14122. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14123. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14124. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14125. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14126. projx = x + norm.x * t0;
  14127. projy = y + norm.y * t0;
  14128. projz = z + norm.z * t0;
  14129. tmpx = projx - x;
  14130. tmpy = projy - y;
  14131. tmpz = projz - z;
  14132. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14133. if (tmpDistance < shortest) {
  14134. shortest = tmpDistance;
  14135. closest = fib;
  14136. if (projected) {
  14137. projected.x = projx;
  14138. projected.y = projy;
  14139. projected.z = projz;
  14140. }
  14141. }
  14142. }
  14143. }
  14144. return closest;
  14145. };
  14146. /**
  14147. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14148. */
  14149. AbstractMesh.prototype.getFacetDataParameters = function () {
  14150. return this._facetParameters;
  14151. };
  14152. /**
  14153. * Disables the feature FacetData and frees the related memory.
  14154. * Returns the AbstractMesh.
  14155. */
  14156. AbstractMesh.prototype.disableFacetData = function () {
  14157. if (this._facetDataEnabled) {
  14158. this._facetDataEnabled = false;
  14159. this._facetPositions = null;
  14160. this._facetNormals = null;
  14161. this._facetPartitioning = null;
  14162. this._facetParameters = null;
  14163. }
  14164. return this;
  14165. };
  14166. /**
  14167. * Creates new normals data for the mesh.
  14168. * @param updatable.
  14169. */
  14170. AbstractMesh.prototype.createNormals = function (updatable) {
  14171. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14172. var indices = this.getIndices();
  14173. var normals;
  14174. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14175. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14176. }
  14177. else {
  14178. normals = [];
  14179. }
  14180. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14181. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14182. };
  14183. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14184. var engine = this.getEngine();
  14185. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14186. this._isOccluded = false;
  14187. return;
  14188. }
  14189. if (this.isOcclusionQueryInProgress) {
  14190. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14191. if (isOcclusionQueryAvailable) {
  14192. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14193. this._isOcclusionQueryInProgress = false;
  14194. this._occlusionInternalRetryCounter = 0;
  14195. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14196. }
  14197. else {
  14198. this._occlusionInternalRetryCounter++;
  14199. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14200. this._isOcclusionQueryInProgress = false;
  14201. this._occlusionInternalRetryCounter = 0;
  14202. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14203. // if strict continue the last state of the object.
  14204. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14205. }
  14206. else {
  14207. return;
  14208. }
  14209. }
  14210. }
  14211. var scene = this.getScene();
  14212. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14213. if (!this._occlusionQuery) {
  14214. this._occlusionQuery = engine.createQuery();
  14215. }
  14216. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14217. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14218. engine.endQuery(this.occlusionQueryAlgorithmType);
  14219. this._isOcclusionQueryInProgress = true;
  14220. };
  14221. // Statics
  14222. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14223. AbstractMesh._BILLBOARDMODE_X = 1;
  14224. AbstractMesh._BILLBOARDMODE_Y = 2;
  14225. AbstractMesh._BILLBOARDMODE_Z = 4;
  14226. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14227. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14228. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14229. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14230. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14231. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14232. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14233. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14234. return AbstractMesh;
  14235. }(BABYLON.Node));
  14236. BABYLON.AbstractMesh = AbstractMesh;
  14237. })(BABYLON || (BABYLON = {}));
  14238. //# sourceMappingURL=babylon.abstractMesh.js.map
  14239. var BABYLON;
  14240. (function (BABYLON) {
  14241. var Light = (function (_super) {
  14242. __extends(Light, _super);
  14243. /**
  14244. * Creates a Light object in the scene.
  14245. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14246. */
  14247. function Light(name, scene) {
  14248. var _this = _super.call(this, name, scene) || this;
  14249. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14250. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14251. _this.intensity = 1.0;
  14252. _this.range = Number.MAX_VALUE;
  14253. /**
  14254. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14255. * of light.
  14256. */
  14257. _this._photometricScale = 1.0;
  14258. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14259. _this._radius = 0.00001;
  14260. _this.renderPriority = 0;
  14261. /**
  14262. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14263. * the current shadow generator.
  14264. */
  14265. _this.shadowEnabled = true;
  14266. _this._excludeWithLayerMask = 0;
  14267. _this._includeOnlyWithLayerMask = 0;
  14268. _this._lightmapMode = 0;
  14269. _this._excludedMeshesIds = new Array();
  14270. _this._includedOnlyMeshesIds = new Array();
  14271. _this.getScene().addLight(_this);
  14272. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14273. _this._buildUniformLayout();
  14274. _this.includedOnlyMeshes = new Array();
  14275. _this.excludedMeshes = new Array();
  14276. _this._resyncMeshes();
  14277. return _this;
  14278. }
  14279. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14280. /**
  14281. * If every light affecting the material is in this lightmapMode,
  14282. * material.lightmapTexture adds or multiplies
  14283. * (depends on material.useLightmapAsShadowmap)
  14284. * after every other light calculations.
  14285. */
  14286. get: function () {
  14287. return Light._LIGHTMAP_DEFAULT;
  14288. },
  14289. enumerable: true,
  14290. configurable: true
  14291. });
  14292. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14293. /**
  14294. * material.lightmapTexture as only diffuse lighting from this light
  14295. * adds pnly specular lighting from this light
  14296. * adds dynamic shadows
  14297. */
  14298. get: function () {
  14299. return Light._LIGHTMAP_SPECULAR;
  14300. },
  14301. enumerable: true,
  14302. configurable: true
  14303. });
  14304. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14305. /**
  14306. * material.lightmapTexture as only lighting
  14307. * no light calculation from this light
  14308. * only adds dynamic shadows from this light
  14309. */
  14310. get: function () {
  14311. return Light._LIGHTMAP_SHADOWSONLY;
  14312. },
  14313. enumerable: true,
  14314. configurable: true
  14315. });
  14316. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14317. /**
  14318. * Each light type uses the default quantity according to its type:
  14319. * point/spot lights use luminous intensity
  14320. * directional lights use illuminance
  14321. */
  14322. get: function () {
  14323. return Light._INTENSITYMODE_AUTOMATIC;
  14324. },
  14325. enumerable: true,
  14326. configurable: true
  14327. });
  14328. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14329. /**
  14330. * lumen (lm)
  14331. */
  14332. get: function () {
  14333. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14334. },
  14335. enumerable: true,
  14336. configurable: true
  14337. });
  14338. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14339. /**
  14340. * candela (lm/sr)
  14341. */
  14342. get: function () {
  14343. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14344. },
  14345. enumerable: true,
  14346. configurable: true
  14347. });
  14348. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14349. /**
  14350. * lux (lm/m^2)
  14351. */
  14352. get: function () {
  14353. return Light._INTENSITYMODE_ILLUMINANCE;
  14354. },
  14355. enumerable: true,
  14356. configurable: true
  14357. });
  14358. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14359. /**
  14360. * nit (cd/m^2)
  14361. */
  14362. get: function () {
  14363. return Light._INTENSITYMODE_LUMINANCE;
  14364. },
  14365. enumerable: true,
  14366. configurable: true
  14367. });
  14368. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14369. /**
  14370. * Light type const id of the point light.
  14371. */
  14372. get: function () {
  14373. return Light._LIGHTTYPEID_POINTLIGHT;
  14374. },
  14375. enumerable: true,
  14376. configurable: true
  14377. });
  14378. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14379. /**
  14380. * Light type const id of the directional light.
  14381. */
  14382. get: function () {
  14383. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14384. },
  14385. enumerable: true,
  14386. configurable: true
  14387. });
  14388. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14389. /**
  14390. * Light type const id of the spot light.
  14391. */
  14392. get: function () {
  14393. return Light._LIGHTTYPEID_SPOTLIGHT;
  14394. },
  14395. enumerable: true,
  14396. configurable: true
  14397. });
  14398. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14399. /**
  14400. * Light type const id of the hemispheric light.
  14401. */
  14402. get: function () {
  14403. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14404. },
  14405. enumerable: true,
  14406. configurable: true
  14407. });
  14408. Object.defineProperty(Light.prototype, "intensityMode", {
  14409. /**
  14410. * Gets the photometric scale used to interpret the intensity.
  14411. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14412. */
  14413. get: function () {
  14414. return this._intensityMode;
  14415. },
  14416. /**
  14417. * Sets the photometric scale used to interpret the intensity.
  14418. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14419. */
  14420. set: function (value) {
  14421. this._intensityMode = value;
  14422. this._computePhotometricScale();
  14423. },
  14424. enumerable: true,
  14425. configurable: true
  14426. });
  14427. ;
  14428. ;
  14429. Object.defineProperty(Light.prototype, "radius", {
  14430. /**
  14431. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14432. */
  14433. get: function () {
  14434. return this._radius;
  14435. },
  14436. /**
  14437. * sets the light radius used by PBR Materials to simulate soft area lights.
  14438. */
  14439. set: function (value) {
  14440. this._radius = value;
  14441. this._computePhotometricScale();
  14442. },
  14443. enumerable: true,
  14444. configurable: true
  14445. });
  14446. ;
  14447. ;
  14448. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14449. get: function () {
  14450. return this._includedOnlyMeshes;
  14451. },
  14452. set: function (value) {
  14453. this._includedOnlyMeshes = value;
  14454. this._hookArrayForIncludedOnly(value);
  14455. },
  14456. enumerable: true,
  14457. configurable: true
  14458. });
  14459. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14460. get: function () {
  14461. return this._excludedMeshes;
  14462. },
  14463. set: function (value) {
  14464. this._excludedMeshes = value;
  14465. this._hookArrayForExcluded(value);
  14466. },
  14467. enumerable: true,
  14468. configurable: true
  14469. });
  14470. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14471. get: function () {
  14472. return this._excludeWithLayerMask;
  14473. },
  14474. set: function (value) {
  14475. this._excludeWithLayerMask = value;
  14476. this._resyncMeshes();
  14477. },
  14478. enumerable: true,
  14479. configurable: true
  14480. });
  14481. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14482. get: function () {
  14483. return this._includeOnlyWithLayerMask;
  14484. },
  14485. set: function (value) {
  14486. this._includeOnlyWithLayerMask = value;
  14487. this._resyncMeshes();
  14488. },
  14489. enumerable: true,
  14490. configurable: true
  14491. });
  14492. Object.defineProperty(Light.prototype, "lightmapMode", {
  14493. get: function () {
  14494. return this._lightmapMode;
  14495. },
  14496. set: function (value) {
  14497. if (this._lightmapMode === value) {
  14498. return;
  14499. }
  14500. this._lightmapMode = value;
  14501. this._markMeshesAsLightDirty();
  14502. },
  14503. enumerable: true,
  14504. configurable: true
  14505. });
  14506. Light.prototype._buildUniformLayout = function () {
  14507. // Overridden
  14508. };
  14509. /**
  14510. * Returns the string "Light".
  14511. */
  14512. Light.prototype.getClassName = function () {
  14513. return "Light";
  14514. };
  14515. /**
  14516. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14517. */
  14518. Light.prototype.toString = function (fullDetails) {
  14519. var ret = "Name: " + this.name;
  14520. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14521. if (this.animations) {
  14522. for (var i = 0; i < this.animations.length; i++) {
  14523. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14524. }
  14525. }
  14526. if (fullDetails) {
  14527. }
  14528. return ret;
  14529. };
  14530. /**
  14531. * Set the enabled state of this node.
  14532. * @param {boolean} value - the new enabled state
  14533. * @see isEnabled
  14534. */
  14535. Light.prototype.setEnabled = function (value) {
  14536. _super.prototype.setEnabled.call(this, value);
  14537. this._resyncMeshes();
  14538. };
  14539. /**
  14540. * Returns the Light associated shadow generator.
  14541. */
  14542. Light.prototype.getShadowGenerator = function () {
  14543. return this._shadowGenerator;
  14544. };
  14545. /**
  14546. * Returns a Vector3, the absolute light position in the World.
  14547. */
  14548. Light.prototype.getAbsolutePosition = function () {
  14549. return BABYLON.Vector3.Zero();
  14550. };
  14551. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14552. };
  14553. Light.prototype._getWorldMatrix = function () {
  14554. return BABYLON.Matrix.Identity();
  14555. };
  14556. /**
  14557. * Boolean : True if the light will affect the passed mesh.
  14558. */
  14559. Light.prototype.canAffectMesh = function (mesh) {
  14560. if (!mesh) {
  14561. return true;
  14562. }
  14563. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14564. return false;
  14565. }
  14566. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14567. return false;
  14568. }
  14569. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14570. return false;
  14571. }
  14572. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14573. return false;
  14574. }
  14575. return true;
  14576. };
  14577. /**
  14578. * Returns the light World matrix.
  14579. */
  14580. Light.prototype.getWorldMatrix = function () {
  14581. this._currentRenderId = this.getScene().getRenderId();
  14582. var worldMatrix = this._getWorldMatrix();
  14583. if (this.parent && this.parent.getWorldMatrix) {
  14584. if (!this._parentedWorldMatrix) {
  14585. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14586. }
  14587. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14588. this._markSyncedWithParent();
  14589. return this._parentedWorldMatrix;
  14590. }
  14591. return worldMatrix;
  14592. };
  14593. /**
  14594. * Sort function to order lights for rendering.
  14595. * @param a First Light object to compare to second.
  14596. * @param b Second Light object to compare first.
  14597. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14598. */
  14599. Light.compareLightsPriority = function (a, b) {
  14600. //shadow-casting lights have priority over non-shadow-casting lights
  14601. //the renderPrioirty is a secondary sort criterion
  14602. if (a.shadowEnabled !== b.shadowEnabled) {
  14603. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14604. }
  14605. return b.renderPriority - a.renderPriority;
  14606. };
  14607. /**
  14608. * Disposes the light.
  14609. */
  14610. Light.prototype.dispose = function () {
  14611. if (this._shadowGenerator) {
  14612. this._shadowGenerator.dispose();
  14613. this._shadowGenerator = null;
  14614. }
  14615. // Animations
  14616. this.getScene().stopAnimation(this);
  14617. // Remove from meshes
  14618. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14619. var mesh = _a[_i];
  14620. mesh._removeLightSource(this);
  14621. }
  14622. this._uniformBuffer.dispose();
  14623. // Remove from scene
  14624. this.getScene().removeLight(this);
  14625. _super.prototype.dispose.call(this);
  14626. };
  14627. /**
  14628. * Returns the light type ID (integer).
  14629. */
  14630. Light.prototype.getTypeID = function () {
  14631. return 0;
  14632. };
  14633. /**
  14634. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14635. */
  14636. Light.prototype.getScaledIntensity = function () {
  14637. return this._photometricScale * this.intensity;
  14638. };
  14639. /**
  14640. * Returns a new Light object, named "name", from the current one.
  14641. */
  14642. Light.prototype.clone = function (name) {
  14643. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14644. };
  14645. /**
  14646. * Serializes the current light into a Serialization object.
  14647. * Returns the serialized object.
  14648. */
  14649. Light.prototype.serialize = function () {
  14650. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14651. // Type
  14652. serializationObject.type = this.getTypeID();
  14653. // Parent
  14654. if (this.parent) {
  14655. serializationObject.parentId = this.parent.id;
  14656. }
  14657. // Inclusion / exclusions
  14658. if (this.excludedMeshes.length > 0) {
  14659. serializationObject.excludedMeshesIds = [];
  14660. this.excludedMeshes.forEach(function (mesh) {
  14661. serializationObject.excludedMeshesIds.push(mesh.id);
  14662. });
  14663. }
  14664. if (this.includedOnlyMeshes.length > 0) {
  14665. serializationObject.includedOnlyMeshesIds = [];
  14666. this.includedOnlyMeshes.forEach(function (mesh) {
  14667. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14668. });
  14669. }
  14670. // Animations
  14671. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14672. serializationObject.ranges = this.serializeAnimationRanges();
  14673. return serializationObject;
  14674. };
  14675. /**
  14676. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14677. * This new light is named "name" and added to the passed scene.
  14678. */
  14679. Light.GetConstructorFromName = function (type, name, scene) {
  14680. switch (type) {
  14681. case 0:
  14682. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14683. case 1:
  14684. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14685. case 2:
  14686. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14687. case 3:
  14688. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14689. }
  14690. };
  14691. /**
  14692. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14693. */
  14694. Light.Parse = function (parsedLight, scene) {
  14695. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14696. // Inclusion / exclusions
  14697. if (parsedLight.excludedMeshesIds) {
  14698. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14699. }
  14700. if (parsedLight.includedOnlyMeshesIds) {
  14701. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14702. }
  14703. // Parent
  14704. if (parsedLight.parentId) {
  14705. light._waitingParentId = parsedLight.parentId;
  14706. }
  14707. // Animations
  14708. if (parsedLight.animations) {
  14709. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14710. var parsedAnimation = parsedLight.animations[animationIndex];
  14711. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14712. }
  14713. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14714. }
  14715. if (parsedLight.autoAnimate) {
  14716. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14717. }
  14718. return light;
  14719. };
  14720. Light.prototype._hookArrayForExcluded = function (array) {
  14721. var _this = this;
  14722. var oldPush = array.push;
  14723. array.push = function () {
  14724. var items = [];
  14725. for (var _i = 0; _i < arguments.length; _i++) {
  14726. items[_i] = arguments[_i];
  14727. }
  14728. var result = oldPush.apply(array, items);
  14729. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14730. var item = items_1[_a];
  14731. item._resyncLighSource(_this);
  14732. }
  14733. return result;
  14734. };
  14735. var oldSplice = array.splice;
  14736. array.splice = function (index, deleteCount) {
  14737. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14738. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14739. var item = deleted_1[_i];
  14740. item._resyncLighSource(_this);
  14741. }
  14742. return deleted;
  14743. };
  14744. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14745. var item = array_1[_i];
  14746. item._resyncLighSource(this);
  14747. }
  14748. };
  14749. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14750. var _this = this;
  14751. var oldPush = array.push;
  14752. array.push = function () {
  14753. var items = [];
  14754. for (var _i = 0; _i < arguments.length; _i++) {
  14755. items[_i] = arguments[_i];
  14756. }
  14757. var result = oldPush.apply(array, items);
  14758. _this._resyncMeshes();
  14759. return result;
  14760. };
  14761. var oldSplice = array.splice;
  14762. array.splice = function (index, deleteCount) {
  14763. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14764. _this._resyncMeshes();
  14765. return deleted;
  14766. };
  14767. this._resyncMeshes();
  14768. };
  14769. Light.prototype._resyncMeshes = function () {
  14770. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14771. var mesh = _a[_i];
  14772. mesh._resyncLighSource(this);
  14773. }
  14774. };
  14775. Light.prototype._markMeshesAsLightDirty = function () {
  14776. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14777. var mesh = _a[_i];
  14778. if (mesh._lightSources.indexOf(this) !== -1) {
  14779. mesh._markSubMeshesAsLightDirty();
  14780. }
  14781. }
  14782. };
  14783. /**
  14784. * Recomputes the cached photometric scale if needed.
  14785. */
  14786. Light.prototype._computePhotometricScale = function () {
  14787. this._photometricScale = this._getPhotometricScale();
  14788. this.getScene().resetCachedMaterial();
  14789. };
  14790. /**
  14791. * Returns the Photometric Scale according to the light type and intensity mode.
  14792. */
  14793. Light.prototype._getPhotometricScale = function () {
  14794. var photometricScale = 0.0;
  14795. var lightTypeID = this.getTypeID();
  14796. //get photometric mode
  14797. var photometricMode = this.intensityMode;
  14798. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14799. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14800. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14801. }
  14802. else {
  14803. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14804. }
  14805. }
  14806. //compute photometric scale
  14807. switch (lightTypeID) {
  14808. case Light.LIGHTTYPEID_POINTLIGHT:
  14809. case Light.LIGHTTYPEID_SPOTLIGHT:
  14810. switch (photometricMode) {
  14811. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14812. photometricScale = 1.0 / (4.0 * Math.PI);
  14813. break;
  14814. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14815. photometricScale = 1.0;
  14816. break;
  14817. case Light.INTENSITYMODE_LUMINANCE:
  14818. photometricScale = this.radius * this.radius;
  14819. break;
  14820. }
  14821. break;
  14822. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14823. switch (photometricMode) {
  14824. case Light.INTENSITYMODE_ILLUMINANCE:
  14825. photometricScale = 1.0;
  14826. break;
  14827. case Light.INTENSITYMODE_LUMINANCE:
  14828. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14829. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14830. var apexAngleRadians = this.radius;
  14831. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14832. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14833. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14834. photometricScale = solidAngle;
  14835. break;
  14836. }
  14837. break;
  14838. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14839. // No fall off in hemisperic light.
  14840. photometricScale = 1.0;
  14841. break;
  14842. }
  14843. return photometricScale;
  14844. };
  14845. Light.prototype._reorderLightsInScene = function () {
  14846. var scene = this.getScene();
  14847. if (this.renderPriority != 0) {
  14848. scene.requireLightSorting = true;
  14849. }
  14850. this.getScene().sortLightsByPriority();
  14851. };
  14852. //lightmapMode Consts
  14853. Light._LIGHTMAP_DEFAULT = 0;
  14854. Light._LIGHTMAP_SPECULAR = 1;
  14855. Light._LIGHTMAP_SHADOWSONLY = 2;
  14856. // Intensity Mode Consts
  14857. Light._INTENSITYMODE_AUTOMATIC = 0;
  14858. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14859. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14860. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14861. Light._INTENSITYMODE_LUMINANCE = 4;
  14862. // Light types ids const.
  14863. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14864. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14865. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14866. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14867. __decorate([
  14868. BABYLON.serializeAsColor3()
  14869. ], Light.prototype, "diffuse", void 0);
  14870. __decorate([
  14871. BABYLON.serializeAsColor3()
  14872. ], Light.prototype, "specular", void 0);
  14873. __decorate([
  14874. BABYLON.serialize()
  14875. ], Light.prototype, "intensity", void 0);
  14876. __decorate([
  14877. BABYLON.serialize()
  14878. ], Light.prototype, "range", void 0);
  14879. __decorate([
  14880. BABYLON.serialize()
  14881. ], Light.prototype, "intensityMode", null);
  14882. __decorate([
  14883. BABYLON.serialize()
  14884. ], Light.prototype, "radius", null);
  14885. __decorate([
  14886. BABYLON.serialize()
  14887. ], Light.prototype, "_renderPriority", void 0);
  14888. __decorate([
  14889. BABYLON.expandToProperty("_reorderLightsInScene")
  14890. ], Light.prototype, "renderPriority", void 0);
  14891. __decorate([
  14892. BABYLON.serialize()
  14893. ], Light.prototype, "shadowEnabled", void 0);
  14894. __decorate([
  14895. BABYLON.serialize("excludeWithLayerMask")
  14896. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14897. __decorate([
  14898. BABYLON.serialize("includeOnlyWithLayerMask")
  14899. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14900. __decorate([
  14901. BABYLON.serialize("lightmapMode")
  14902. ], Light.prototype, "_lightmapMode", void 0);
  14903. return Light;
  14904. }(BABYLON.Node));
  14905. BABYLON.Light = Light;
  14906. })(BABYLON || (BABYLON = {}));
  14907. //# sourceMappingURL=babylon.light.js.map
  14908. var BABYLON;
  14909. (function (BABYLON) {
  14910. var Camera = (function (_super) {
  14911. __extends(Camera, _super);
  14912. function Camera(name, position, scene) {
  14913. var _this = _super.call(this, name, scene) || this;
  14914. _this.upVector = BABYLON.Vector3.Up();
  14915. _this.orthoLeft = null;
  14916. _this.orthoRight = null;
  14917. _this.orthoBottom = null;
  14918. _this.orthoTop = null;
  14919. _this.fov = 0.8;
  14920. _this.minZ = 1;
  14921. _this.maxZ = 10000.0;
  14922. _this.inertia = 0.9;
  14923. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14924. _this.isIntermediate = false;
  14925. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14926. _this.layerMask = 0x0FFFFFFF;
  14927. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14928. // Camera rig members
  14929. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14930. _this._rigCameras = new Array();
  14931. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14932. _this.customRenderTargets = new Array();
  14933. // Observables
  14934. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14935. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14936. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14937. // Cache
  14938. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14939. _this._projectionMatrix = new BABYLON.Matrix();
  14940. _this._doNotComputeProjectionMatrix = false;
  14941. _this._postProcesses = new Array();
  14942. _this._transformMatrix = BABYLON.Matrix.Zero();
  14943. _this._activeMeshes = new BABYLON.SmartArray(256);
  14944. _this._globalPosition = BABYLON.Vector3.Zero();
  14945. _this._refreshFrustumPlanes = true;
  14946. _this.getScene().addCamera(_this);
  14947. if (!_this.getScene().activeCamera) {
  14948. _this.getScene().activeCamera = _this;
  14949. }
  14950. _this.position = position;
  14951. return _this;
  14952. }
  14953. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14954. get: function () {
  14955. return Camera._PERSPECTIVE_CAMERA;
  14956. },
  14957. enumerable: true,
  14958. configurable: true
  14959. });
  14960. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14961. get: function () {
  14962. return Camera._ORTHOGRAPHIC_CAMERA;
  14963. },
  14964. enumerable: true,
  14965. configurable: true
  14966. });
  14967. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14968. get: function () {
  14969. return Camera._FOVMODE_VERTICAL_FIXED;
  14970. },
  14971. enumerable: true,
  14972. configurable: true
  14973. });
  14974. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14975. get: function () {
  14976. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14977. },
  14978. enumerable: true,
  14979. configurable: true
  14980. });
  14981. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14982. get: function () {
  14983. return Camera._RIG_MODE_NONE;
  14984. },
  14985. enumerable: true,
  14986. configurable: true
  14987. });
  14988. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14989. get: function () {
  14990. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14991. },
  14992. enumerable: true,
  14993. configurable: true
  14994. });
  14995. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14996. get: function () {
  14997. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14998. },
  14999. enumerable: true,
  15000. configurable: true
  15001. });
  15002. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15003. get: function () {
  15004. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15005. },
  15006. enumerable: true,
  15007. configurable: true
  15008. });
  15009. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15010. get: function () {
  15011. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15012. },
  15013. enumerable: true,
  15014. configurable: true
  15015. });
  15016. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15017. get: function () {
  15018. return Camera._RIG_MODE_VR;
  15019. },
  15020. enumerable: true,
  15021. configurable: true
  15022. });
  15023. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15024. get: function () {
  15025. return Camera._RIG_MODE_WEBVR;
  15026. },
  15027. enumerable: true,
  15028. configurable: true
  15029. });
  15030. /**
  15031. * Store current camera state (fov, position, etc..)
  15032. */
  15033. Camera.prototype.storeState = function () {
  15034. this._stateStored = true;
  15035. this._storedFov = this.fov;
  15036. return this;
  15037. };
  15038. /**
  15039. * Restored camera state. You must call storeState() first
  15040. */
  15041. Camera.prototype.restoreState = function () {
  15042. if (!this._stateStored) {
  15043. return false;
  15044. }
  15045. this.fov = this._storedFov;
  15046. return true;
  15047. };
  15048. Camera.prototype.getClassName = function () {
  15049. return "Camera";
  15050. };
  15051. /**
  15052. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15053. */
  15054. Camera.prototype.toString = function (fullDetails) {
  15055. var ret = "Name: " + this.name;
  15056. ret += ", type: " + this.getClassName();
  15057. if (this.animations) {
  15058. for (var i = 0; i < this.animations.length; i++) {
  15059. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15060. }
  15061. }
  15062. if (fullDetails) {
  15063. }
  15064. return ret;
  15065. };
  15066. Object.defineProperty(Camera.prototype, "globalPosition", {
  15067. get: function () {
  15068. return this._globalPosition;
  15069. },
  15070. enumerable: true,
  15071. configurable: true
  15072. });
  15073. Camera.prototype.getActiveMeshes = function () {
  15074. return this._activeMeshes;
  15075. };
  15076. Camera.prototype.isActiveMesh = function (mesh) {
  15077. return (this._activeMeshes.indexOf(mesh) !== -1);
  15078. };
  15079. //Cache
  15080. Camera.prototype._initCache = function () {
  15081. _super.prototype._initCache.call(this);
  15082. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15083. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15084. this._cache.mode = undefined;
  15085. this._cache.minZ = undefined;
  15086. this._cache.maxZ = undefined;
  15087. this._cache.fov = undefined;
  15088. this._cache.fovMode = undefined;
  15089. this._cache.aspectRatio = undefined;
  15090. this._cache.orthoLeft = undefined;
  15091. this._cache.orthoRight = undefined;
  15092. this._cache.orthoBottom = undefined;
  15093. this._cache.orthoTop = undefined;
  15094. this._cache.renderWidth = undefined;
  15095. this._cache.renderHeight = undefined;
  15096. };
  15097. Camera.prototype._updateCache = function (ignoreParentClass) {
  15098. if (!ignoreParentClass) {
  15099. _super.prototype._updateCache.call(this);
  15100. }
  15101. var engine = this.getEngine();
  15102. this._cache.position.copyFrom(this.position);
  15103. this._cache.upVector.copyFrom(this.upVector);
  15104. this._cache.mode = this.mode;
  15105. this._cache.minZ = this.minZ;
  15106. this._cache.maxZ = this.maxZ;
  15107. this._cache.fov = this.fov;
  15108. this._cache.fovMode = this.fovMode;
  15109. this._cache.aspectRatio = engine.getAspectRatio(this);
  15110. this._cache.orthoLeft = this.orthoLeft;
  15111. this._cache.orthoRight = this.orthoRight;
  15112. this._cache.orthoBottom = this.orthoBottom;
  15113. this._cache.orthoTop = this.orthoTop;
  15114. this._cache.renderWidth = engine.getRenderWidth();
  15115. this._cache.renderHeight = engine.getRenderHeight();
  15116. };
  15117. Camera.prototype._updateFromScene = function () {
  15118. this.updateCache();
  15119. this.update();
  15120. };
  15121. // Synchronized
  15122. Camera.prototype._isSynchronized = function () {
  15123. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15124. };
  15125. Camera.prototype._isSynchronizedViewMatrix = function () {
  15126. if (!_super.prototype._isSynchronized.call(this))
  15127. return false;
  15128. return this._cache.position.equals(this.position)
  15129. && this._cache.upVector.equals(this.upVector)
  15130. && this.isSynchronizedWithParent();
  15131. };
  15132. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15133. var check = this._cache.mode === this.mode
  15134. && this._cache.minZ === this.minZ
  15135. && this._cache.maxZ === this.maxZ;
  15136. if (!check) {
  15137. return false;
  15138. }
  15139. var engine = this.getEngine();
  15140. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15141. check = this._cache.fov === this.fov
  15142. && this._cache.fovMode === this.fovMode
  15143. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15144. }
  15145. else {
  15146. check = this._cache.orthoLeft === this.orthoLeft
  15147. && this._cache.orthoRight === this.orthoRight
  15148. && this._cache.orthoBottom === this.orthoBottom
  15149. && this._cache.orthoTop === this.orthoTop
  15150. && this._cache.renderWidth === engine.getRenderWidth()
  15151. && this._cache.renderHeight === engine.getRenderHeight();
  15152. }
  15153. return check;
  15154. };
  15155. // Controls
  15156. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15157. };
  15158. Camera.prototype.detachControl = function (element) {
  15159. };
  15160. Camera.prototype.update = function () {
  15161. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15162. this._updateRigCameras();
  15163. }
  15164. this._checkInputs();
  15165. };
  15166. Camera.prototype._checkInputs = function () {
  15167. this.onAfterCheckInputsObservable.notifyObservers(this);
  15168. };
  15169. Object.defineProperty(Camera.prototype, "rigCameras", {
  15170. get: function () {
  15171. return this._rigCameras;
  15172. },
  15173. enumerable: true,
  15174. configurable: true
  15175. });
  15176. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15177. get: function () {
  15178. return this._rigPostProcess;
  15179. },
  15180. enumerable: true,
  15181. configurable: true
  15182. });
  15183. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15184. // invalidate framebuffer
  15185. if (this._postProcesses.length > 0) {
  15186. this._postProcesses[0].markTextureDirty();
  15187. }
  15188. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15189. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15190. var cam = this._rigCameras[i];
  15191. var rigPostProcess = cam._rigPostProcess;
  15192. // for VR rig, there does not have to be a post process
  15193. if (rigPostProcess) {
  15194. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15195. if (isPass) {
  15196. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15197. cam.isIntermediate = this._postProcesses.length === 0;
  15198. }
  15199. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15200. rigPostProcess.markTextureDirty();
  15201. }
  15202. else {
  15203. cam._postProcesses = this._postProcesses.slice(0);
  15204. }
  15205. }
  15206. };
  15207. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15208. if (insertAt === void 0) { insertAt = null; }
  15209. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15210. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15211. return 0;
  15212. }
  15213. if (insertAt == null || insertAt < 0) {
  15214. this._postProcesses.push(postProcess);
  15215. }
  15216. else {
  15217. this._postProcesses.splice(insertAt, 0, postProcess);
  15218. }
  15219. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15220. return this._postProcesses.indexOf(postProcess);
  15221. };
  15222. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15223. if (atIndices === void 0) { atIndices = null; }
  15224. var result = [];
  15225. var i;
  15226. var index;
  15227. if (!atIndices) {
  15228. var idx = this._postProcesses.indexOf(postProcess);
  15229. if (idx !== -1) {
  15230. this._postProcesses.splice(idx, 1);
  15231. }
  15232. }
  15233. else {
  15234. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15235. // iterate descending, so can just splice as we go
  15236. for (i = atIndices.length - 1; i >= 0; i--) {
  15237. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15238. result.push(i);
  15239. continue;
  15240. }
  15241. index = atIndices[i];
  15242. this._postProcesses.splice(index, 1);
  15243. }
  15244. }
  15245. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15246. return result;
  15247. };
  15248. Camera.prototype.getWorldMatrix = function () {
  15249. if (!this._worldMatrix) {
  15250. this._worldMatrix = BABYLON.Matrix.Identity();
  15251. }
  15252. var viewMatrix = this.getViewMatrix();
  15253. viewMatrix.invertToRef(this._worldMatrix);
  15254. return this._worldMatrix;
  15255. };
  15256. Camera.prototype._getViewMatrix = function () {
  15257. return BABYLON.Matrix.Identity();
  15258. };
  15259. Camera.prototype.getViewMatrix = function (force) {
  15260. if (!force && this._isSynchronizedViewMatrix()) {
  15261. return this._computedViewMatrix;
  15262. }
  15263. this._computedViewMatrix = this._getViewMatrix();
  15264. this._currentRenderId = this.getScene().getRenderId();
  15265. this._refreshFrustumPlanes = true;
  15266. if (!this.parent || !this.parent.getWorldMatrix) {
  15267. this._globalPosition.copyFrom(this.position);
  15268. }
  15269. else {
  15270. if (!this._worldMatrix) {
  15271. this._worldMatrix = BABYLON.Matrix.Identity();
  15272. }
  15273. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15274. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15275. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15276. this._computedViewMatrix.invert();
  15277. this._markSyncedWithParent();
  15278. }
  15279. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15280. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15281. }
  15282. this.onViewMatrixChangedObservable.notifyObservers(this);
  15283. return this._computedViewMatrix;
  15284. };
  15285. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15286. this._doNotComputeProjectionMatrix = true;
  15287. if (projection !== undefined) {
  15288. this._projectionMatrix = projection;
  15289. }
  15290. };
  15291. ;
  15292. Camera.prototype.unfreezeProjectionMatrix = function () {
  15293. this._doNotComputeProjectionMatrix = false;
  15294. };
  15295. ;
  15296. Camera.prototype.getProjectionMatrix = function (force) {
  15297. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15298. return this._projectionMatrix;
  15299. }
  15300. this._refreshFrustumPlanes = true;
  15301. var engine = this.getEngine();
  15302. var scene = this.getScene();
  15303. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15304. if (this.minZ <= 0) {
  15305. this.minZ = 0.1;
  15306. }
  15307. if (scene.useRightHandedSystem) {
  15308. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15309. }
  15310. else {
  15311. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15312. }
  15313. }
  15314. else {
  15315. var halfWidth = engine.getRenderWidth() / 2.0;
  15316. var halfHeight = engine.getRenderHeight() / 2.0;
  15317. if (scene.useRightHandedSystem) {
  15318. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15319. }
  15320. else {
  15321. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15322. }
  15323. }
  15324. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15325. return this._projectionMatrix;
  15326. };
  15327. Camera.prototype.getTranformationMatrix = function () {
  15328. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15329. return this._transformMatrix;
  15330. };
  15331. Camera.prototype.updateFrustumPlanes = function () {
  15332. if (!this._refreshFrustumPlanes) {
  15333. return;
  15334. }
  15335. this.getTranformationMatrix();
  15336. if (!this._frustumPlanes) {
  15337. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15338. }
  15339. else {
  15340. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15341. }
  15342. this._refreshFrustumPlanes = false;
  15343. };
  15344. Camera.prototype.isInFrustum = function (target) {
  15345. this.updateFrustumPlanes();
  15346. return target.isInFrustum(this._frustumPlanes);
  15347. };
  15348. Camera.prototype.isCompletelyInFrustum = function (target) {
  15349. this.updateFrustumPlanes();
  15350. return target.isCompletelyInFrustum(this._frustumPlanes);
  15351. };
  15352. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15353. if (length === void 0) { length = 100; }
  15354. if (!transform) {
  15355. transform = this.getWorldMatrix();
  15356. }
  15357. if (!origin) {
  15358. origin = this.position;
  15359. }
  15360. var forward = new BABYLON.Vector3(0, 0, 1);
  15361. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15362. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15363. return new BABYLON.Ray(origin, direction, length);
  15364. };
  15365. Camera.prototype.dispose = function () {
  15366. // Observables
  15367. this.onViewMatrixChangedObservable.clear();
  15368. this.onProjectionMatrixChangedObservable.clear();
  15369. this.onAfterCheckInputsObservable.clear();
  15370. // Inputs
  15371. if (this.inputs) {
  15372. this.inputs.clear();
  15373. }
  15374. // Animations
  15375. this.getScene().stopAnimation(this);
  15376. // Remove from scene
  15377. this.getScene().removeCamera(this);
  15378. while (this._rigCameras.length > 0) {
  15379. this._rigCameras.pop().dispose();
  15380. }
  15381. // Postprocesses
  15382. var i = this._postProcesses.length;
  15383. while (--i >= 0) {
  15384. this._postProcesses[i].dispose(this);
  15385. }
  15386. // Render targets
  15387. var i = this.customRenderTargets.length;
  15388. while (--i >= 0) {
  15389. this.customRenderTargets[i].dispose();
  15390. }
  15391. this.customRenderTargets = [];
  15392. // Active Meshes
  15393. this._activeMeshes.dispose();
  15394. _super.prototype.dispose.call(this);
  15395. };
  15396. Object.defineProperty(Camera.prototype, "leftCamera", {
  15397. // ---- Camera rigs section ----
  15398. get: function () {
  15399. if (this._rigCameras.length < 1) {
  15400. return undefined;
  15401. }
  15402. return this._rigCameras[0];
  15403. },
  15404. enumerable: true,
  15405. configurable: true
  15406. });
  15407. Object.defineProperty(Camera.prototype, "rightCamera", {
  15408. get: function () {
  15409. if (this._rigCameras.length < 2) {
  15410. return undefined;
  15411. }
  15412. return this._rigCameras[1];
  15413. },
  15414. enumerable: true,
  15415. configurable: true
  15416. });
  15417. Camera.prototype.getLeftTarget = function () {
  15418. if (this._rigCameras.length < 1) {
  15419. return undefined;
  15420. }
  15421. return this._rigCameras[0].getTarget();
  15422. };
  15423. Camera.prototype.getRightTarget = function () {
  15424. if (this._rigCameras.length < 2) {
  15425. return undefined;
  15426. }
  15427. return this._rigCameras[1].getTarget();
  15428. };
  15429. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15430. while (this._rigCameras.length > 0) {
  15431. this._rigCameras.pop().dispose();
  15432. }
  15433. this.cameraRigMode = mode;
  15434. this._cameraRigParams = {};
  15435. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15436. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15437. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15438. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15439. // create the rig cameras, unless none
  15440. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15441. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15442. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15443. }
  15444. switch (this.cameraRigMode) {
  15445. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15446. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15447. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15448. break;
  15449. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15450. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15451. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15452. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15453. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15454. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15455. break;
  15456. case Camera.RIG_MODE_VR:
  15457. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15458. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15459. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15460. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15461. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15462. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15463. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15464. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15465. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15466. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15467. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15468. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15469. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15470. if (metrics.compensateDistortion) {
  15471. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15472. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15473. }
  15474. break;
  15475. case Camera.RIG_MODE_WEBVR:
  15476. if (rigParams.vrDisplay) {
  15477. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15478. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15479. //Left eye
  15480. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15481. this._rigCameras[0].setCameraRigParameter("left", true);
  15482. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15483. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15484. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15485. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15486. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15487. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15488. this._rigCameras[0].parent = this;
  15489. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15490. //Right eye
  15491. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15492. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15493. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15494. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15495. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15496. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15497. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15498. this._rigCameras[1].parent = this;
  15499. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15500. }
  15501. break;
  15502. }
  15503. this._cascadePostProcessesToRigCams();
  15504. this.
  15505. update();
  15506. };
  15507. Camera.prototype._getVRProjectionMatrix = function () {
  15508. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15509. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15510. return this._projectionMatrix;
  15511. };
  15512. Camera.prototype._updateCameraRotationMatrix = function () {
  15513. //Here for WebVR
  15514. };
  15515. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15516. //Here for WebVR
  15517. };
  15518. /**
  15519. * This function MUST be overwritten by the different WebVR cameras available.
  15520. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15521. */
  15522. Camera.prototype._getWebVRProjectionMatrix = function () {
  15523. return BABYLON.Matrix.Identity();
  15524. };
  15525. /**
  15526. * This function MUST be overwritten by the different WebVR cameras available.
  15527. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15528. */
  15529. Camera.prototype._getWebVRViewMatrix = function () {
  15530. return BABYLON.Matrix.Identity();
  15531. };
  15532. Camera.prototype.setCameraRigParameter = function (name, value) {
  15533. if (!this._cameraRigParams) {
  15534. this._cameraRigParams = {};
  15535. }
  15536. this._cameraRigParams[name] = value;
  15537. //provisionnally:
  15538. if (name === "interaxialDistance") {
  15539. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15540. }
  15541. };
  15542. /**
  15543. * needs to be overridden by children so sub has required properties to be copied
  15544. */
  15545. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15546. return null;
  15547. };
  15548. /**
  15549. * May need to be overridden by children
  15550. */
  15551. Camera.prototype._updateRigCameras = function () {
  15552. for (var i = 0; i < this._rigCameras.length; i++) {
  15553. this._rigCameras[i].minZ = this.minZ;
  15554. this._rigCameras[i].maxZ = this.maxZ;
  15555. this._rigCameras[i].fov = this.fov;
  15556. }
  15557. // only update viewport when ANAGLYPH
  15558. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15559. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15560. }
  15561. };
  15562. Camera.prototype._setupInputs = function () {
  15563. };
  15564. Camera.prototype.serialize = function () {
  15565. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15566. // Type
  15567. serializationObject.type = this.getClassName();
  15568. // Parent
  15569. if (this.parent) {
  15570. serializationObject.parentId = this.parent.id;
  15571. }
  15572. if (this.inputs) {
  15573. this.inputs.serialize(serializationObject);
  15574. }
  15575. // Animations
  15576. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15577. serializationObject.ranges = this.serializeAnimationRanges();
  15578. return serializationObject;
  15579. };
  15580. Camera.prototype.clone = function (name) {
  15581. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15582. };
  15583. Camera.prototype.getDirection = function (localAxis) {
  15584. var result = BABYLON.Vector3.Zero();
  15585. this.getDirectionToRef(localAxis, result);
  15586. return result;
  15587. };
  15588. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15589. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15590. };
  15591. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15592. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15593. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15594. switch (type) {
  15595. case "ArcRotateCamera":
  15596. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15597. case "DeviceOrientationCamera":
  15598. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15599. case "FollowCamera":
  15600. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15601. case "ArcFollowCamera":
  15602. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15603. case "GamepadCamera":
  15604. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15605. case "TouchCamera":
  15606. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15607. case "VirtualJoysticksCamera":
  15608. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15609. case "WebVRFreeCamera":
  15610. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15611. case "WebVRGamepadCamera":
  15612. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15613. case "VRDeviceOrientationFreeCamera":
  15614. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15615. case "VRDeviceOrientationGamepadCamera":
  15616. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15617. case "AnaglyphArcRotateCamera":
  15618. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15619. case "AnaglyphFreeCamera":
  15620. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15621. case "AnaglyphGamepadCamera":
  15622. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15623. case "AnaglyphUniversalCamera":
  15624. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15625. case "StereoscopicArcRotateCamera":
  15626. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15627. case "StereoscopicFreeCamera":
  15628. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15629. case "StereoscopicGamepadCamera":
  15630. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15631. case "StereoscopicUniversalCamera":
  15632. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15633. case "FreeCamera":// Forcing Universal here
  15634. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15635. default:// Universal Camera is the default value
  15636. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15637. }
  15638. };
  15639. Camera.Parse = function (parsedCamera, scene) {
  15640. var type = parsedCamera.type;
  15641. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15642. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15643. // Parent
  15644. if (parsedCamera.parentId) {
  15645. camera._waitingParentId = parsedCamera.parentId;
  15646. }
  15647. //If camera has an input manager, let it parse inputs settings
  15648. if (camera.inputs) {
  15649. camera.inputs.parse(parsedCamera);
  15650. camera._setupInputs();
  15651. }
  15652. if (camera.setPosition) {
  15653. camera.position.copyFromFloats(0, 0, 0);
  15654. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15655. }
  15656. // Target
  15657. if (parsedCamera.target) {
  15658. if (camera.setTarget) {
  15659. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15660. }
  15661. }
  15662. // Apply 3d rig, when found
  15663. if (parsedCamera.cameraRigMode) {
  15664. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15665. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15666. }
  15667. // Animations
  15668. if (parsedCamera.animations) {
  15669. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15670. var parsedAnimation = parsedCamera.animations[animationIndex];
  15671. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15672. }
  15673. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15674. }
  15675. if (parsedCamera.autoAnimate) {
  15676. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15677. }
  15678. return camera;
  15679. };
  15680. // Statics
  15681. Camera._PERSPECTIVE_CAMERA = 0;
  15682. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15683. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15684. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15685. Camera._RIG_MODE_NONE = 0;
  15686. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15687. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15688. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15689. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15690. Camera._RIG_MODE_VR = 20;
  15691. Camera._RIG_MODE_WEBVR = 21;
  15692. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15693. __decorate([
  15694. BABYLON.serializeAsVector3()
  15695. ], Camera.prototype, "position", void 0);
  15696. __decorate([
  15697. BABYLON.serializeAsVector3()
  15698. ], Camera.prototype, "upVector", void 0);
  15699. __decorate([
  15700. BABYLON.serialize()
  15701. ], Camera.prototype, "orthoLeft", void 0);
  15702. __decorate([
  15703. BABYLON.serialize()
  15704. ], Camera.prototype, "orthoRight", void 0);
  15705. __decorate([
  15706. BABYLON.serialize()
  15707. ], Camera.prototype, "orthoBottom", void 0);
  15708. __decorate([
  15709. BABYLON.serialize()
  15710. ], Camera.prototype, "orthoTop", void 0);
  15711. __decorate([
  15712. BABYLON.serialize()
  15713. ], Camera.prototype, "fov", void 0);
  15714. __decorate([
  15715. BABYLON.serialize()
  15716. ], Camera.prototype, "minZ", void 0);
  15717. __decorate([
  15718. BABYLON.serialize()
  15719. ], Camera.prototype, "maxZ", void 0);
  15720. __decorate([
  15721. BABYLON.serialize()
  15722. ], Camera.prototype, "inertia", void 0);
  15723. __decorate([
  15724. BABYLON.serialize()
  15725. ], Camera.prototype, "mode", void 0);
  15726. __decorate([
  15727. BABYLON.serialize()
  15728. ], Camera.prototype, "layerMask", void 0);
  15729. __decorate([
  15730. BABYLON.serialize()
  15731. ], Camera.prototype, "fovMode", void 0);
  15732. __decorate([
  15733. BABYLON.serialize()
  15734. ], Camera.prototype, "cameraRigMode", void 0);
  15735. __decorate([
  15736. BABYLON.serialize()
  15737. ], Camera.prototype, "interaxialDistance", void 0);
  15738. __decorate([
  15739. BABYLON.serialize()
  15740. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15741. return Camera;
  15742. }(BABYLON.Node));
  15743. BABYLON.Camera = Camera;
  15744. })(BABYLON || (BABYLON = {}));
  15745. //# sourceMappingURL=babylon.camera.js.map
  15746. var BABYLON;
  15747. (function (BABYLON) {
  15748. var RenderingManager = (function () {
  15749. function RenderingManager(scene) {
  15750. this._renderingGroups = new Array();
  15751. this._autoClearDepthStencil = {};
  15752. this._customOpaqueSortCompareFn = {};
  15753. this._customAlphaTestSortCompareFn = {};
  15754. this._customTransparentSortCompareFn = {};
  15755. this._renderinGroupInfo = null;
  15756. this._scene = scene;
  15757. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15758. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15759. }
  15760. }
  15761. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15762. if (depth === void 0) { depth = true; }
  15763. if (stencil === void 0) { stencil = true; }
  15764. if (this._depthStencilBufferAlreadyCleaned) {
  15765. return;
  15766. }
  15767. this._scene.getEngine().clear(null, false, depth, stencil);
  15768. this._depthStencilBufferAlreadyCleaned = true;
  15769. };
  15770. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15771. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15772. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15773. var info = null;
  15774. if (observable) {
  15775. if (!this._renderinGroupInfo) {
  15776. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15777. }
  15778. info = this._renderinGroupInfo;
  15779. info.scene = this._scene;
  15780. info.camera = this._scene.activeCamera;
  15781. }
  15782. // Dispatch sprites
  15783. if (renderSprites) {
  15784. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15785. var manager = this._scene.spriteManagers[index];
  15786. this.dispatchSprites(manager);
  15787. }
  15788. }
  15789. // Render
  15790. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15791. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15792. var renderingGroup = this._renderingGroups[index];
  15793. if (!renderingGroup && !observable)
  15794. continue;
  15795. this._currentIndex = index;
  15796. var renderingGroupMask = 0;
  15797. // Fire PRECLEAR stage
  15798. if (observable) {
  15799. renderingGroupMask = Math.pow(2, index);
  15800. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15801. info.renderingGroupId = index;
  15802. observable.notifyObservers(info, renderingGroupMask);
  15803. }
  15804. // Clear depth/stencil if needed
  15805. if (RenderingManager.AUTOCLEAR) {
  15806. var autoClear = this._autoClearDepthStencil[index];
  15807. if (autoClear && autoClear.autoClear) {
  15808. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15809. }
  15810. }
  15811. if (observable) {
  15812. // Fire PREOPAQUE stage
  15813. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15814. observable.notifyObservers(info, renderingGroupMask);
  15815. // Fire PRETRANSPARENT stage
  15816. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15817. observable.notifyObservers(info, renderingGroupMask);
  15818. }
  15819. if (renderingGroup)
  15820. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15821. // Fire POSTTRANSPARENT stage
  15822. if (observable) {
  15823. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15824. observable.notifyObservers(info, renderingGroupMask);
  15825. }
  15826. }
  15827. };
  15828. RenderingManager.prototype.reset = function () {
  15829. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15830. var renderingGroup = this._renderingGroups[index];
  15831. if (renderingGroup) {
  15832. renderingGroup.prepare();
  15833. }
  15834. }
  15835. };
  15836. RenderingManager.prototype.dispose = function () {
  15837. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15838. var renderingGroup = this._renderingGroups[index];
  15839. if (renderingGroup) {
  15840. renderingGroup.dispose();
  15841. }
  15842. }
  15843. this._renderingGroups.length = 0;
  15844. };
  15845. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15846. if (!this._renderingGroups[renderingGroupId]) {
  15847. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15848. }
  15849. };
  15850. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15851. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15852. this._prepareRenderingGroup(renderingGroupId);
  15853. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15854. };
  15855. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15856. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15857. this._prepareRenderingGroup(renderingGroupId);
  15858. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15859. };
  15860. RenderingManager.prototype.dispatch = function (subMesh) {
  15861. var mesh = subMesh.getMesh();
  15862. var renderingGroupId = mesh.renderingGroupId || 0;
  15863. this._prepareRenderingGroup(renderingGroupId);
  15864. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15865. };
  15866. /**
  15867. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15868. * This allowed control for front to back rendering or reversly depending of the special needs.
  15869. *
  15870. * @param renderingGroupId The rendering group id corresponding to its index
  15871. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15872. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15873. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15874. */
  15875. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15876. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15877. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15878. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15879. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15880. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15881. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15882. if (this._renderingGroups[renderingGroupId]) {
  15883. var group = this._renderingGroups[renderingGroupId];
  15884. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15885. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15886. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15887. }
  15888. };
  15889. /**
  15890. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15891. *
  15892. * @param renderingGroupId The rendering group id corresponding to its index
  15893. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15894. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15895. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15896. */
  15897. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15898. if (depth === void 0) { depth = true; }
  15899. if (stencil === void 0) { stencil = true; }
  15900. this._autoClearDepthStencil[renderingGroupId] = {
  15901. autoClear: autoClearDepthStencil,
  15902. depth: depth,
  15903. stencil: stencil
  15904. };
  15905. };
  15906. /**
  15907. * The max id used for rendering groups (not included)
  15908. */
  15909. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15910. /**
  15911. * The min id used for rendering groups (included)
  15912. */
  15913. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15914. /**
  15915. * Used to globally prevent autoclearing scenes.
  15916. */
  15917. RenderingManager.AUTOCLEAR = true;
  15918. return RenderingManager;
  15919. }());
  15920. BABYLON.RenderingManager = RenderingManager;
  15921. })(BABYLON || (BABYLON = {}));
  15922. //# sourceMappingURL=babylon.renderingManager.js.map
  15923. var BABYLON;
  15924. (function (BABYLON) {
  15925. var RenderingGroup = (function () {
  15926. /**
  15927. * Creates a new rendering group.
  15928. * @param index The rendering group index
  15929. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15930. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15931. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15932. */
  15933. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15934. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15935. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15936. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15937. this.index = index;
  15938. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15939. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15940. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15941. this._particleSystems = new BABYLON.SmartArray(256);
  15942. this._spriteManagers = new BABYLON.SmartArray(256);
  15943. this._edgesRenderers = new BABYLON.SmartArray(16);
  15944. this._scene = scene;
  15945. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15946. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15947. this.transparentSortCompareFn = transparentSortCompareFn;
  15948. }
  15949. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15950. /**
  15951. * Set the opaque sort comparison function.
  15952. * If null the sub meshes will be render in the order they were created
  15953. */
  15954. set: function (value) {
  15955. this._opaqueSortCompareFn = value;
  15956. if (value) {
  15957. this._renderOpaque = this.renderOpaqueSorted;
  15958. }
  15959. else {
  15960. this._renderOpaque = RenderingGroup.renderUnsorted;
  15961. }
  15962. },
  15963. enumerable: true,
  15964. configurable: true
  15965. });
  15966. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15967. /**
  15968. * Set the alpha test sort comparison function.
  15969. * If null the sub meshes will be render in the order they were created
  15970. */
  15971. set: function (value) {
  15972. this._alphaTestSortCompareFn = value;
  15973. if (value) {
  15974. this._renderAlphaTest = this.renderAlphaTestSorted;
  15975. }
  15976. else {
  15977. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15978. }
  15979. },
  15980. enumerable: true,
  15981. configurable: true
  15982. });
  15983. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15984. /**
  15985. * Set the transparent sort comparison function.
  15986. * If null the sub meshes will be render in the order they were created
  15987. */
  15988. set: function (value) {
  15989. if (value) {
  15990. this._transparentSortCompareFn = value;
  15991. }
  15992. else {
  15993. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15994. }
  15995. this._renderTransparent = this.renderTransparentSorted;
  15996. },
  15997. enumerable: true,
  15998. configurable: true
  15999. });
  16000. /**
  16001. * Render all the sub meshes contained in the group.
  16002. * @param customRenderFunction Used to override the default render behaviour of the group.
  16003. * @returns true if rendered some submeshes.
  16004. */
  16005. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16006. if (customRenderFunction) {
  16007. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16008. return;
  16009. }
  16010. var engine = this._scene.getEngine();
  16011. // Opaque
  16012. if (this._opaqueSubMeshes.length !== 0) {
  16013. this._renderOpaque(this._opaqueSubMeshes);
  16014. }
  16015. // Alpha test
  16016. if (this._alphaTestSubMeshes.length !== 0) {
  16017. engine.setAlphaTesting(true);
  16018. this._renderAlphaTest(this._alphaTestSubMeshes);
  16019. engine.setAlphaTesting(false);
  16020. }
  16021. var stencilState = engine.getStencilBuffer();
  16022. engine.setStencilBuffer(false);
  16023. // Sprites
  16024. if (renderSprites) {
  16025. this._renderSprites();
  16026. }
  16027. // Particles
  16028. if (renderParticles) {
  16029. this._renderParticles(activeMeshes);
  16030. }
  16031. if (this.onBeforeTransparentRendering) {
  16032. this.onBeforeTransparentRendering();
  16033. }
  16034. // Transparent
  16035. if (this._transparentSubMeshes.length !== 0) {
  16036. this._renderTransparent(this._transparentSubMeshes);
  16037. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16038. }
  16039. // Set back stencil to false in case it changes before the edge renderer.
  16040. engine.setStencilBuffer(false);
  16041. // Edges
  16042. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16043. this._edgesRenderers.data[edgesRendererIndex].render();
  16044. }
  16045. // Restore Stencil state.
  16046. engine.setStencilBuffer(stencilState);
  16047. };
  16048. /**
  16049. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16050. * @param subMeshes The submeshes to render
  16051. */
  16052. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16053. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16054. };
  16055. /**
  16056. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16057. * @param subMeshes The submeshes to render
  16058. */
  16059. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16060. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16061. };
  16062. /**
  16063. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16064. * @param subMeshes The submeshes to render
  16065. */
  16066. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16067. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16068. };
  16069. /**
  16070. * Renders the submeshes in a specified order.
  16071. * @param subMeshes The submeshes to sort before render
  16072. * @param sortCompareFn The comparison function use to sort
  16073. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16074. * @param transparent Specifies to activate blending if true
  16075. */
  16076. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16077. var subIndex = 0;
  16078. var subMesh;
  16079. for (; subIndex < subMeshes.length; subIndex++) {
  16080. subMesh = subMeshes.data[subIndex];
  16081. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16082. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16083. }
  16084. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16085. sortedArray.sort(sortCompareFn);
  16086. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16087. subMesh = sortedArray[subIndex];
  16088. subMesh.render(transparent);
  16089. }
  16090. };
  16091. /**
  16092. * Renders the submeshes in the order they were dispatched (no sort applied).
  16093. * @param subMeshes The submeshes to render
  16094. */
  16095. RenderingGroup.renderUnsorted = function (subMeshes) {
  16096. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16097. var submesh = subMeshes.data[subIndex];
  16098. submesh.render(false);
  16099. }
  16100. };
  16101. /**
  16102. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16103. * are rendered back to front if in the same alpha index.
  16104. *
  16105. * @param a The first submesh
  16106. * @param b The second submesh
  16107. * @returns The result of the comparison
  16108. */
  16109. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16110. // Alpha index first
  16111. if (a._alphaIndex > b._alphaIndex) {
  16112. return 1;
  16113. }
  16114. if (a._alphaIndex < b._alphaIndex) {
  16115. return -1;
  16116. }
  16117. // Then distance to camera
  16118. return RenderingGroup.backToFrontSortCompare(a, b);
  16119. };
  16120. /**
  16121. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16122. * are rendered back to front.
  16123. *
  16124. * @param a The first submesh
  16125. * @param b The second submesh
  16126. * @returns The result of the comparison
  16127. */
  16128. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16129. // Then distance to camera
  16130. if (a._distanceToCamera < b._distanceToCamera) {
  16131. return 1;
  16132. }
  16133. if (a._distanceToCamera > b._distanceToCamera) {
  16134. return -1;
  16135. }
  16136. return 0;
  16137. };
  16138. /**
  16139. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16140. * are rendered front to back (prevent overdraw).
  16141. *
  16142. * @param a The first submesh
  16143. * @param b The second submesh
  16144. * @returns The result of the comparison
  16145. */
  16146. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16147. // Then distance to camera
  16148. if (a._distanceToCamera < b._distanceToCamera) {
  16149. return -1;
  16150. }
  16151. if (a._distanceToCamera > b._distanceToCamera) {
  16152. return 1;
  16153. }
  16154. return 0;
  16155. };
  16156. /**
  16157. * Resets the different lists of submeshes to prepare a new frame.
  16158. */
  16159. RenderingGroup.prototype.prepare = function () {
  16160. this._opaqueSubMeshes.reset();
  16161. this._transparentSubMeshes.reset();
  16162. this._alphaTestSubMeshes.reset();
  16163. this._particleSystems.reset();
  16164. this._spriteManagers.reset();
  16165. this._edgesRenderers.reset();
  16166. };
  16167. RenderingGroup.prototype.dispose = function () {
  16168. this._opaqueSubMeshes.dispose();
  16169. this._transparentSubMeshes.dispose();
  16170. this._alphaTestSubMeshes.dispose();
  16171. this._particleSystems.dispose();
  16172. this._spriteManagers.dispose();
  16173. this._edgesRenderers.dispose();
  16174. };
  16175. /**
  16176. * Inserts the submesh in its correct queue depending on its material.
  16177. * @param subMesh The submesh to dispatch
  16178. */
  16179. RenderingGroup.prototype.dispatch = function (subMesh) {
  16180. var material = subMesh.getMaterial();
  16181. var mesh = subMesh.getMesh();
  16182. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16183. this._transparentSubMeshes.push(subMesh);
  16184. }
  16185. else if (material.needAlphaTesting()) {
  16186. this._alphaTestSubMeshes.push(subMesh);
  16187. }
  16188. else {
  16189. this._opaqueSubMeshes.push(subMesh); // Opaque
  16190. }
  16191. if (mesh._edgesRenderer) {
  16192. this._edgesRenderers.push(mesh._edgesRenderer);
  16193. }
  16194. };
  16195. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16196. this._spriteManagers.push(spriteManager);
  16197. };
  16198. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16199. this._particleSystems.push(particleSystem);
  16200. };
  16201. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16202. if (this._particleSystems.length === 0) {
  16203. return;
  16204. }
  16205. // Particles
  16206. var activeCamera = this._scene.activeCamera;
  16207. this._scene._particlesDuration.beginMonitoring();
  16208. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16209. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16210. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16211. continue;
  16212. }
  16213. var emitter = particleSystem.emitter;
  16214. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16215. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16216. }
  16217. }
  16218. this._scene._particlesDuration.endMonitoring(false);
  16219. };
  16220. RenderingGroup.prototype._renderSprites = function () {
  16221. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16222. return;
  16223. }
  16224. // Sprites
  16225. var activeCamera = this._scene.activeCamera;
  16226. this._scene._spritesDuration.beginMonitoring();
  16227. for (var id = 0; id < this._spriteManagers.length; id++) {
  16228. var spriteManager = this._spriteManagers.data[id];
  16229. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16230. spriteManager.render();
  16231. }
  16232. }
  16233. this._scene._spritesDuration.endMonitoring(false);
  16234. };
  16235. return RenderingGroup;
  16236. }());
  16237. BABYLON.RenderingGroup = RenderingGroup;
  16238. })(BABYLON || (BABYLON = {}));
  16239. //# sourceMappingURL=babylon.renderingGroup.js.map
  16240. var BABYLON;
  16241. (function (BABYLON) {
  16242. var ClickInfo = (function () {
  16243. function ClickInfo() {
  16244. this._singleClick = false;
  16245. this._doubleClick = false;
  16246. this._hasSwiped = false;
  16247. this._ignore = false;
  16248. }
  16249. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16250. get: function () {
  16251. return this._singleClick;
  16252. },
  16253. set: function (b) {
  16254. this._singleClick = b;
  16255. },
  16256. enumerable: true,
  16257. configurable: true
  16258. });
  16259. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16260. get: function () {
  16261. return this._doubleClick;
  16262. },
  16263. set: function (b) {
  16264. this._doubleClick = b;
  16265. },
  16266. enumerable: true,
  16267. configurable: true
  16268. });
  16269. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16270. get: function () {
  16271. return this._hasSwiped;
  16272. },
  16273. set: function (b) {
  16274. this._hasSwiped = b;
  16275. },
  16276. enumerable: true,
  16277. configurable: true
  16278. });
  16279. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16280. get: function () {
  16281. return this._ignore;
  16282. },
  16283. set: function (b) {
  16284. this._ignore = b;
  16285. },
  16286. enumerable: true,
  16287. configurable: true
  16288. });
  16289. return ClickInfo;
  16290. }());
  16291. /**
  16292. * This class is used by the onRenderingGroupObservable
  16293. */
  16294. var RenderingGroupInfo = (function () {
  16295. function RenderingGroupInfo() {
  16296. }
  16297. /**
  16298. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16299. * This stage will be fired no matter what
  16300. */
  16301. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16302. /**
  16303. * Called before opaque object are rendered.
  16304. * This stage will be fired only if there's 3D Opaque content to render
  16305. */
  16306. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16307. /**
  16308. * Called after the opaque objects are rendered and before the transparent ones
  16309. * This stage will be fired only if there's 3D transparent content to render
  16310. */
  16311. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16312. /**
  16313. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16314. * This stage will be fired no matter what
  16315. */
  16316. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16317. return RenderingGroupInfo;
  16318. }());
  16319. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16320. /**
  16321. * Represents a scene to be rendered by the engine.
  16322. * @see http://doc.babylonjs.com/page.php?p=21911
  16323. */
  16324. var Scene = (function () {
  16325. /**
  16326. * @constructor
  16327. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16328. */
  16329. function Scene(engine) {
  16330. // Members
  16331. this.autoClear = true;
  16332. this.autoClearDepthAndStencil = true;
  16333. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16334. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16335. this.forceWireframe = false;
  16336. this._forcePointsCloud = false;
  16337. this.forceShowBoundingBoxes = false;
  16338. this.animationsEnabled = true;
  16339. this.constantlyUpdateMeshUnderPointer = false;
  16340. this.hoverCursor = "pointer";
  16341. this.defaultCursor = "";
  16342. // Metadata
  16343. this.metadata = null;
  16344. // Events
  16345. /**
  16346. * An event triggered when the scene is disposed.
  16347. * @type {BABYLON.Observable}
  16348. */
  16349. this.onDisposeObservable = new BABYLON.Observable();
  16350. /**
  16351. * An event triggered before rendering the scene
  16352. * @type {BABYLON.Observable}
  16353. */
  16354. this.onBeforeRenderObservable = new BABYLON.Observable();
  16355. /**
  16356. * An event triggered after rendering the scene
  16357. * @type {BABYLON.Observable}
  16358. */
  16359. this.onAfterRenderObservable = new BABYLON.Observable();
  16360. /**
  16361. * An event triggered when the scene is ready
  16362. * @type {BABYLON.Observable}
  16363. */
  16364. this.onReadyObservable = new BABYLON.Observable();
  16365. /**
  16366. * An event triggered before rendering a camera
  16367. * @type {BABYLON.Observable}
  16368. */
  16369. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16370. /**
  16371. * An event triggered after rendering a camera
  16372. * @type {BABYLON.Observable}
  16373. */
  16374. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16375. /**
  16376. * An event triggered when a camera is created
  16377. * @type {BABYLON.Observable}
  16378. */
  16379. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16380. /**
  16381. * An event triggered when a camera is removed
  16382. * @type {BABYLON.Observable}
  16383. */
  16384. this.onCameraRemovedObservable = new BABYLON.Observable();
  16385. /**
  16386. * An event triggered when a light is created
  16387. * @type {BABYLON.Observable}
  16388. */
  16389. this.onNewLightAddedObservable = new BABYLON.Observable();
  16390. /**
  16391. * An event triggered when a light is removed
  16392. * @type {BABYLON.Observable}
  16393. */
  16394. this.onLightRemovedObservable = new BABYLON.Observable();
  16395. /**
  16396. * An event triggered when a geometry is created
  16397. * @type {BABYLON.Observable}
  16398. */
  16399. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16400. /**
  16401. * An event triggered when a geometry is removed
  16402. * @type {BABYLON.Observable}
  16403. */
  16404. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16405. /**
  16406. * An event triggered when a mesh is created
  16407. * @type {BABYLON.Observable}
  16408. */
  16409. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16410. /**
  16411. * An event triggered when a mesh is removed
  16412. * @type {BABYLON.Observable}
  16413. */
  16414. this.onMeshRemovedObservable = new BABYLON.Observable();
  16415. /**
  16416. * An event triggered before calculating deterministic simulation step
  16417. * @type {BABYLON.Observable}
  16418. */
  16419. this.onBeforeStepObservable = new BABYLON.Observable();
  16420. /**
  16421. * An event triggered after calculating deterministic simulation step
  16422. * @type {BABYLON.Observable}
  16423. */
  16424. this.onAfterStepObservable = new BABYLON.Observable();
  16425. /**
  16426. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16427. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16428. * 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)
  16429. */
  16430. this.onRenderingGroupObservable = new BABYLON.Observable();
  16431. // Animations
  16432. this.animations = [];
  16433. /**
  16434. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  16435. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16436. */
  16437. this.onPrePointerObservable = new BABYLON.Observable();
  16438. /**
  16439. * Observable event triggered each time an input event is received from the rendering canvas
  16440. */
  16441. this.onPointerObservable = new BABYLON.Observable();
  16442. this._meshPickProceed = false;
  16443. this._previousHasSwiped = false;
  16444. this._currentPickResult = null;
  16445. this._previousPickResult = null;
  16446. this._isButtonPressed = false;
  16447. this._doubleClickOccured = false;
  16448. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16449. this.cameraToUseForPointers = null;
  16450. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16451. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16452. this._startingPointerTime = 0;
  16453. this._previousStartingPointerTime = 0;
  16454. // Deterministic lockstep
  16455. this._timeAccumulator = 0;
  16456. this._currentStepId = 0;
  16457. this._currentInternalStep = 0;
  16458. // Keyboard
  16459. /**
  16460. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16461. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16462. */
  16463. this.onPreKeyboardObservable = new BABYLON.Observable();
  16464. /**
  16465. * Observable event triggered each time an keyboard event is received from the hosting window
  16466. */
  16467. this.onKeyboardObservable = new BABYLON.Observable();
  16468. // Coordinate system
  16469. /**
  16470. * use right-handed coordinate system on this scene.
  16471. * @type {boolean}
  16472. */
  16473. this._useRightHandedSystem = false;
  16474. // Fog
  16475. this._fogEnabled = true;
  16476. this._fogMode = Scene.FOGMODE_NONE;
  16477. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16478. this.fogDensity = 0.1;
  16479. this.fogStart = 0;
  16480. this.fogEnd = 1000.0;
  16481. // Lights
  16482. /**
  16483. * is shadow enabled on this scene.
  16484. * @type {boolean}
  16485. */
  16486. this._shadowsEnabled = true;
  16487. /**
  16488. * is light enabled on this scene.
  16489. * @type {boolean}
  16490. */
  16491. this._lightsEnabled = true;
  16492. /**
  16493. * All of the lights added to this scene.
  16494. * @see BABYLON.Light
  16495. * @type {BABYLON.Light[]}
  16496. */
  16497. this.lights = new Array();
  16498. // Cameras
  16499. /** All of the cameras added to this scene. */
  16500. this.cameras = new Array();
  16501. /** All of the active cameras added to this scene. */
  16502. this.activeCameras = new Array();
  16503. // Meshes
  16504. /**
  16505. * All of the (abstract) meshes added to this scene.
  16506. * @see BABYLON.AbstractMesh
  16507. * @type {BABYLON.AbstractMesh[]}
  16508. */
  16509. this.meshes = new Array();
  16510. // Geometries
  16511. this._geometries = new Array();
  16512. this.materials = new Array();
  16513. this.multiMaterials = new Array();
  16514. // Textures
  16515. this._texturesEnabled = true;
  16516. this.textures = new Array();
  16517. // Particles
  16518. this.particlesEnabled = true;
  16519. this.particleSystems = new Array();
  16520. // Sprites
  16521. this.spritesEnabled = true;
  16522. this.spriteManagers = new Array();
  16523. // Layers
  16524. this.layers = new Array();
  16525. this.highlightLayers = new Array();
  16526. // Skeletons
  16527. this._skeletonsEnabled = true;
  16528. this.skeletons = new Array();
  16529. // Morph targets
  16530. this.morphTargetManagers = new Array();
  16531. // Lens flares
  16532. this.lensFlaresEnabled = true;
  16533. this.lensFlareSystems = new Array();
  16534. // Collisions
  16535. this.collisionsEnabled = true;
  16536. /** Defines the gravity applied to this scene */
  16537. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16538. // Postprocesses
  16539. this.postProcesses = new Array();
  16540. this.postProcessesEnabled = true;
  16541. // Customs render targets
  16542. this.renderTargetsEnabled = true;
  16543. this.dumpNextRenderTargets = false;
  16544. this.customRenderTargets = new Array();
  16545. // Imported meshes
  16546. this.importedMeshesFiles = new Array();
  16547. // Probes
  16548. this.probesEnabled = true;
  16549. this.reflectionProbes = new Array();
  16550. this._actionManagers = new Array();
  16551. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16552. // Procedural textures
  16553. this.proceduralTexturesEnabled = true;
  16554. this._proceduralTextures = new Array();
  16555. this.soundTracks = new Array();
  16556. this._audioEnabled = true;
  16557. this._headphone = false;
  16558. // Performance counters
  16559. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16560. this._totalLightsCounter = new BABYLON.PerfCounter();
  16561. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16562. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16563. this._totalVertices = new BABYLON.PerfCounter();
  16564. this._activeIndices = new BABYLON.PerfCounter();
  16565. this._activeParticles = new BABYLON.PerfCounter();
  16566. this._lastFrameDuration = new BABYLON.PerfCounter();
  16567. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16568. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16569. this._particlesDuration = new BABYLON.PerfCounter();
  16570. this._renderDuration = new BABYLON.PerfCounter();
  16571. this._spritesDuration = new BABYLON.PerfCounter();
  16572. this._activeBones = new BABYLON.PerfCounter();
  16573. this._animationTime = 0;
  16574. this.animationTimeScale = 1;
  16575. this._renderId = 0;
  16576. this._executeWhenReadyTimeoutId = -1;
  16577. this._intermediateRendering = false;
  16578. this._viewUpdateFlag = -1;
  16579. this._projectionUpdateFlag = -1;
  16580. this._toBeDisposed = new BABYLON.SmartArray(256);
  16581. this._pendingData = []; //ANY
  16582. this._activeMeshes = new BABYLON.SmartArray(256);
  16583. this._processedMaterials = new BABYLON.SmartArray(256);
  16584. this._renderTargets = new BABYLON.SmartArray(256);
  16585. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16586. this._activeSkeletons = new BABYLON.SmartArray(32);
  16587. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16588. this._activeAnimatables = new Array();
  16589. this._transformMatrix = BABYLON.Matrix.Zero();
  16590. this.requireLightSorting = false;
  16591. this._uniqueIdCounter = 0;
  16592. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16593. this._engine.scenes.push(this);
  16594. this._uid = null;
  16595. this._renderingManager = new BABYLON.RenderingManager(this);
  16596. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16597. if (BABYLON.OutlineRenderer) {
  16598. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16599. }
  16600. this.attachControl();
  16601. if (BABYLON.SoundTrack) {
  16602. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16603. }
  16604. //simplification queue
  16605. if (BABYLON.SimplificationQueue) {
  16606. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16607. }
  16608. //collision coordinator initialization. For now legacy per default.
  16609. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16610. // Uniform Buffer
  16611. this._createUbo();
  16612. // Default Image processing definition.
  16613. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16614. }
  16615. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16616. /** The fog is deactivated */
  16617. get: function () {
  16618. return Scene._FOGMODE_NONE;
  16619. },
  16620. enumerable: true,
  16621. configurable: true
  16622. });
  16623. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16624. /** The fog density is following an exponential function */
  16625. get: function () {
  16626. return Scene._FOGMODE_EXP;
  16627. },
  16628. enumerable: true,
  16629. configurable: true
  16630. });
  16631. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16632. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16633. get: function () {
  16634. return Scene._FOGMODE_EXP2;
  16635. },
  16636. enumerable: true,
  16637. configurable: true
  16638. });
  16639. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16640. /** The fog density is following a linear function. */
  16641. get: function () {
  16642. return Scene._FOGMODE_LINEAR;
  16643. },
  16644. enumerable: true,
  16645. configurable: true
  16646. });
  16647. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16648. /**
  16649. * Texture used in all pbr material as the reflection texture.
  16650. * As in the majority of the scene they are the same (exception for multi room and so on),
  16651. * this is easier to reference from here than from all the materials.
  16652. */
  16653. get: function () {
  16654. return this._environmentTexture;
  16655. },
  16656. /**
  16657. * Texture used in all pbr material as the reflection texture.
  16658. * As in the majority of the scene they are the same (exception for multi room and so on),
  16659. * this is easier to set here than in all the materials.
  16660. */
  16661. set: function (value) {
  16662. this._environmentTexture = value;
  16663. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16664. },
  16665. enumerable: true,
  16666. configurable: true
  16667. });
  16668. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16669. /**
  16670. * Default image processing configuration used either in the rendering
  16671. * Forward main pass or through the imageProcessingPostProcess if present.
  16672. * As in the majority of the scene they are the same (exception for multi camera),
  16673. * this is easier to reference from here than from all the materials and post process.
  16674. *
  16675. * No setter as we it is a shared configuration, you can set the values instead.
  16676. */
  16677. get: function () {
  16678. return this._imageProcessingConfiguration;
  16679. },
  16680. enumerable: true,
  16681. configurable: true
  16682. });
  16683. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16684. get: function () {
  16685. return this._forcePointsCloud;
  16686. },
  16687. set: function (value) {
  16688. if (this._forcePointsCloud === value) {
  16689. return;
  16690. }
  16691. this._forcePointsCloud = value;
  16692. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16693. },
  16694. enumerable: true,
  16695. configurable: true
  16696. });
  16697. Object.defineProperty(Scene.prototype, "onDispose", {
  16698. /** A function to be executed when this scene is disposed. */
  16699. set: function (callback) {
  16700. if (this._onDisposeObserver) {
  16701. this.onDisposeObservable.remove(this._onDisposeObserver);
  16702. }
  16703. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16704. },
  16705. enumerable: true,
  16706. configurable: true
  16707. });
  16708. Object.defineProperty(Scene.prototype, "beforeRender", {
  16709. /** A function to be executed before rendering this scene */
  16710. set: function (callback) {
  16711. if (this._onBeforeRenderObserver) {
  16712. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16713. }
  16714. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16715. },
  16716. enumerable: true,
  16717. configurable: true
  16718. });
  16719. Object.defineProperty(Scene.prototype, "afterRender", {
  16720. /** A function to be executed after rendering this scene */
  16721. set: function (callback) {
  16722. if (this._onAfterRenderObserver) {
  16723. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16724. }
  16725. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16726. },
  16727. enumerable: true,
  16728. configurable: true
  16729. });
  16730. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16731. set: function (callback) {
  16732. if (this._onBeforeCameraRenderObserver) {
  16733. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16734. }
  16735. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16736. },
  16737. enumerable: true,
  16738. configurable: true
  16739. });
  16740. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16741. set: function (callback) {
  16742. if (this._onAfterCameraRenderObserver) {
  16743. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16744. }
  16745. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16746. },
  16747. enumerable: true,
  16748. configurable: true
  16749. });
  16750. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16751. get: function () {
  16752. if (!this._gamepadManager) {
  16753. this._gamepadManager = new BABYLON.GamepadManager();
  16754. }
  16755. return this._gamepadManager;
  16756. },
  16757. enumerable: true,
  16758. configurable: true
  16759. });
  16760. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16761. get: function () {
  16762. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16763. },
  16764. enumerable: true,
  16765. configurable: true
  16766. });
  16767. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16768. get: function () {
  16769. return this._useRightHandedSystem;
  16770. },
  16771. set: function (value) {
  16772. if (this._useRightHandedSystem === value) {
  16773. return;
  16774. }
  16775. this._useRightHandedSystem = value;
  16776. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16777. },
  16778. enumerable: true,
  16779. configurable: true
  16780. });
  16781. Scene.prototype.setStepId = function (newStepId) {
  16782. this._currentStepId = newStepId;
  16783. };
  16784. ;
  16785. Scene.prototype.getStepId = function () {
  16786. return this._currentStepId;
  16787. };
  16788. ;
  16789. Scene.prototype.getInternalStep = function () {
  16790. return this._currentInternalStep;
  16791. };
  16792. ;
  16793. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16794. get: function () {
  16795. return this._fogEnabled;
  16796. },
  16797. /**
  16798. * is fog enabled on this scene.
  16799. */
  16800. set: function (value) {
  16801. if (this._fogEnabled === value) {
  16802. return;
  16803. }
  16804. this._fogEnabled = value;
  16805. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16806. },
  16807. enumerable: true,
  16808. configurable: true
  16809. });
  16810. Object.defineProperty(Scene.prototype, "fogMode", {
  16811. get: function () {
  16812. return this._fogMode;
  16813. },
  16814. set: function (value) {
  16815. if (this._fogMode === value) {
  16816. return;
  16817. }
  16818. this._fogMode = value;
  16819. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16820. },
  16821. enumerable: true,
  16822. configurable: true
  16823. });
  16824. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16825. get: function () {
  16826. return this._shadowsEnabled;
  16827. },
  16828. set: function (value) {
  16829. if (this._shadowsEnabled === value) {
  16830. return;
  16831. }
  16832. this._shadowsEnabled = value;
  16833. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16834. },
  16835. enumerable: true,
  16836. configurable: true
  16837. });
  16838. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16839. get: function () {
  16840. return this._lightsEnabled;
  16841. },
  16842. set: function (value) {
  16843. if (this._lightsEnabled === value) {
  16844. return;
  16845. }
  16846. this._lightsEnabled = value;
  16847. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16848. },
  16849. enumerable: true,
  16850. configurable: true
  16851. });
  16852. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16853. /** The default material used on meshes when no material is affected */
  16854. get: function () {
  16855. if (!this._defaultMaterial) {
  16856. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16857. }
  16858. return this._defaultMaterial;
  16859. },
  16860. /** The default material used on meshes when no material is affected */
  16861. set: function (value) {
  16862. this._defaultMaterial = value;
  16863. },
  16864. enumerable: true,
  16865. configurable: true
  16866. });
  16867. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16868. get: function () {
  16869. return this._texturesEnabled;
  16870. },
  16871. set: function (value) {
  16872. if (this._texturesEnabled === value) {
  16873. return;
  16874. }
  16875. this._texturesEnabled = value;
  16876. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16877. },
  16878. enumerable: true,
  16879. configurable: true
  16880. });
  16881. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16882. get: function () {
  16883. return this._skeletonsEnabled;
  16884. },
  16885. set: function (value) {
  16886. if (this._skeletonsEnabled === value) {
  16887. return;
  16888. }
  16889. this._skeletonsEnabled = value;
  16890. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16891. },
  16892. enumerable: true,
  16893. configurable: true
  16894. });
  16895. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16896. get: function () {
  16897. if (!this._postProcessRenderPipelineManager) {
  16898. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16899. }
  16900. return this._postProcessRenderPipelineManager;
  16901. },
  16902. enumerable: true,
  16903. configurable: true
  16904. });
  16905. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16906. get: function () {
  16907. return this._frustumPlanes;
  16908. },
  16909. enumerable: true,
  16910. configurable: true
  16911. });
  16912. Object.defineProperty(Scene.prototype, "debugLayer", {
  16913. // Properties
  16914. get: function () {
  16915. if (!this._debugLayer) {
  16916. this._debugLayer = new BABYLON.DebugLayer(this);
  16917. }
  16918. return this._debugLayer;
  16919. },
  16920. enumerable: true,
  16921. configurable: true
  16922. });
  16923. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16924. get: function () {
  16925. return this._workerCollisions;
  16926. },
  16927. set: function (enabled) {
  16928. if (!BABYLON.CollisionCoordinatorLegacy) {
  16929. return;
  16930. }
  16931. enabled = (enabled && !!Worker);
  16932. this._workerCollisions = enabled;
  16933. if (this.collisionCoordinator) {
  16934. this.collisionCoordinator.destroy();
  16935. }
  16936. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16937. this.collisionCoordinator.init(this);
  16938. },
  16939. enumerable: true,
  16940. configurable: true
  16941. });
  16942. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16943. get: function () {
  16944. return this._selectionOctree;
  16945. },
  16946. enumerable: true,
  16947. configurable: true
  16948. });
  16949. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16950. /**
  16951. * The mesh that is currently under the pointer.
  16952. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16953. */
  16954. get: function () {
  16955. return this._pointerOverMesh;
  16956. },
  16957. enumerable: true,
  16958. configurable: true
  16959. });
  16960. Object.defineProperty(Scene.prototype, "pointerX", {
  16961. /**
  16962. * Current on-screen X position of the pointer
  16963. * @return {number} X position of the pointer
  16964. */
  16965. get: function () {
  16966. return this._pointerX;
  16967. },
  16968. enumerable: true,
  16969. configurable: true
  16970. });
  16971. Object.defineProperty(Scene.prototype, "pointerY", {
  16972. /**
  16973. * Current on-screen Y position of the pointer
  16974. * @return {number} Y position of the pointer
  16975. */
  16976. get: function () {
  16977. return this._pointerY;
  16978. },
  16979. enumerable: true,
  16980. configurable: true
  16981. });
  16982. Scene.prototype.getCachedMaterial = function () {
  16983. return this._cachedMaterial;
  16984. };
  16985. Scene.prototype.getCachedEffect = function () {
  16986. return this._cachedEffect;
  16987. };
  16988. Scene.prototype.getCachedVisibility = function () {
  16989. return this._cachedVisibility;
  16990. };
  16991. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  16992. if (visibility === void 0) { visibility = 1; }
  16993. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16994. };
  16995. Scene.prototype.getBoundingBoxRenderer = function () {
  16996. if (!this._boundingBoxRenderer) {
  16997. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16998. }
  16999. return this._boundingBoxRenderer;
  17000. };
  17001. Scene.prototype.getOutlineRenderer = function () {
  17002. return this._outlineRenderer;
  17003. };
  17004. Scene.prototype.getEngine = function () {
  17005. return this._engine;
  17006. };
  17007. Scene.prototype.getTotalVertices = function () {
  17008. return this._totalVertices.current;
  17009. };
  17010. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17011. get: function () {
  17012. return this._totalVertices;
  17013. },
  17014. enumerable: true,
  17015. configurable: true
  17016. });
  17017. Scene.prototype.getActiveIndices = function () {
  17018. return this._activeIndices.current;
  17019. };
  17020. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17021. get: function () {
  17022. return this._activeIndices;
  17023. },
  17024. enumerable: true,
  17025. configurable: true
  17026. });
  17027. Scene.prototype.getActiveParticles = function () {
  17028. return this._activeParticles.current;
  17029. };
  17030. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17031. get: function () {
  17032. return this._activeParticles;
  17033. },
  17034. enumerable: true,
  17035. configurable: true
  17036. });
  17037. Scene.prototype.getActiveBones = function () {
  17038. return this._activeBones.current;
  17039. };
  17040. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17041. get: function () {
  17042. return this._activeBones;
  17043. },
  17044. enumerable: true,
  17045. configurable: true
  17046. });
  17047. // Stats
  17048. Scene.prototype.getLastFrameDuration = function () {
  17049. return this._lastFrameDuration.current;
  17050. };
  17051. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17052. get: function () {
  17053. return this._lastFrameDuration;
  17054. },
  17055. enumerable: true,
  17056. configurable: true
  17057. });
  17058. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17059. return this._evaluateActiveMeshesDuration.current;
  17060. };
  17061. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17062. get: function () {
  17063. return this._evaluateActiveMeshesDuration;
  17064. },
  17065. enumerable: true,
  17066. configurable: true
  17067. });
  17068. Scene.prototype.getActiveMeshes = function () {
  17069. return this._activeMeshes;
  17070. };
  17071. Scene.prototype.getRenderTargetsDuration = function () {
  17072. return this._renderTargetsDuration.current;
  17073. };
  17074. Scene.prototype.getRenderDuration = function () {
  17075. return this._renderDuration.current;
  17076. };
  17077. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17078. get: function () {
  17079. return this._renderDuration;
  17080. },
  17081. enumerable: true,
  17082. configurable: true
  17083. });
  17084. Scene.prototype.getParticlesDuration = function () {
  17085. return this._particlesDuration.current;
  17086. };
  17087. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17088. get: function () {
  17089. return this._particlesDuration;
  17090. },
  17091. enumerable: true,
  17092. configurable: true
  17093. });
  17094. Scene.prototype.getSpritesDuration = function () {
  17095. return this._spritesDuration.current;
  17096. };
  17097. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17098. get: function () {
  17099. return this._spritesDuration;
  17100. },
  17101. enumerable: true,
  17102. configurable: true
  17103. });
  17104. Scene.prototype.getAnimationRatio = function () {
  17105. return this._animationRatio;
  17106. };
  17107. Scene.prototype.getRenderId = function () {
  17108. return this._renderId;
  17109. };
  17110. Scene.prototype.incrementRenderId = function () {
  17111. this._renderId++;
  17112. };
  17113. Scene.prototype._updatePointerPosition = function (evt) {
  17114. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17115. this._pointerX = evt.clientX - canvasRect.left;
  17116. this._pointerY = evt.clientY - canvasRect.top;
  17117. this._unTranslatedPointerX = this._pointerX;
  17118. this._unTranslatedPointerY = this._pointerY;
  17119. };
  17120. Scene.prototype._createUbo = function () {
  17121. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17122. this._sceneUbo.addUniform("viewProjection", 16);
  17123. this._sceneUbo.addUniform("view", 16);
  17124. };
  17125. // Pointers handling
  17126. /**
  17127. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17128. * @param attachUp defines if you want to attach events to pointerup
  17129. * @param attachDown defines if you want to attach events to pointerdown
  17130. * @param attachMove defines if you want to attach events to pointermove
  17131. */
  17132. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17133. var _this = this;
  17134. if (attachUp === void 0) { attachUp = true; }
  17135. if (attachDown === void 0) { attachDown = true; }
  17136. if (attachMove === void 0) { attachMove = true; }
  17137. this._initActionManager = function (act, clickInfo) {
  17138. if (!_this._meshPickProceed) {
  17139. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17140. _this._currentPickResult = pickResult;
  17141. if (pickResult) {
  17142. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17143. }
  17144. _this._meshPickProceed = true;
  17145. }
  17146. return act;
  17147. };
  17148. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17149. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17150. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17151. btn !== _this._previousButtonPressed) {
  17152. _this._doubleClickOccured = false;
  17153. clickInfo.singleClick = true;
  17154. clickInfo.ignore = false;
  17155. cb(clickInfo, _this._currentPickResult);
  17156. }
  17157. };
  17158. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17159. var clickInfo = new ClickInfo();
  17160. _this._currentPickResult = null;
  17161. var act;
  17162. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17163. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17164. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17165. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17166. act = _this._initActionManager(act, clickInfo);
  17167. if (act)
  17168. checkPicking = act.hasPickTriggers;
  17169. }
  17170. if (checkPicking) {
  17171. var btn = evt.button;
  17172. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17173. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17174. if (!clickInfo.hasSwiped) {
  17175. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17176. if (!checkSingleClickImmediately) {
  17177. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17178. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17179. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17180. act = _this._initActionManager(act, clickInfo);
  17181. if (act)
  17182. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17183. }
  17184. }
  17185. if (checkSingleClickImmediately) {
  17186. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17187. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17188. btn !== _this._previousButtonPressed) {
  17189. clickInfo.singleClick = true;
  17190. cb(clickInfo, _this._currentPickResult);
  17191. }
  17192. }
  17193. else {
  17194. // wait that no double click has been raised during the double click delay
  17195. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17196. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17197. }
  17198. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17199. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17200. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17201. act = _this._initActionManager(act, clickInfo);
  17202. if (act)
  17203. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17204. }
  17205. if (checkDoubleClick) {
  17206. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17207. if (btn === _this._previousButtonPressed &&
  17208. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17209. !_this._doubleClickOccured) {
  17210. // pointer has not moved for 2 clicks, it's a double click
  17211. if (!clickInfo.hasSwiped &&
  17212. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17213. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17214. _this._previousStartingPointerTime = 0;
  17215. _this._doubleClickOccured = true;
  17216. clickInfo.doubleClick = true;
  17217. clickInfo.ignore = false;
  17218. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17219. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17220. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17221. cb(clickInfo, _this._currentPickResult);
  17222. }
  17223. else {
  17224. _this._doubleClickOccured = false;
  17225. _this._previousStartingPointerTime = _this._startingPointerTime;
  17226. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17227. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17228. _this._previousButtonPressed = btn;
  17229. _this._previousHasSwiped = clickInfo.hasSwiped;
  17230. if (Scene.ExclusiveDoubleClickMode) {
  17231. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17232. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17233. }
  17234. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17235. cb(clickInfo, _this._previousPickResult);
  17236. }
  17237. else {
  17238. cb(clickInfo, _this._currentPickResult);
  17239. }
  17240. }
  17241. }
  17242. else {
  17243. _this._doubleClickOccured = false;
  17244. _this._previousStartingPointerTime = _this._startingPointerTime;
  17245. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17246. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17247. _this._previousButtonPressed = btn;
  17248. _this._previousHasSwiped = clickInfo.hasSwiped;
  17249. }
  17250. }
  17251. }
  17252. }
  17253. clickInfo.ignore = true;
  17254. cb(clickInfo, _this._currentPickResult);
  17255. };
  17256. var spritePredicate = function (sprite) {
  17257. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17258. };
  17259. this._onPointerMove = function (evt) {
  17260. _this._updatePointerPosition(evt);
  17261. // PreObservable support
  17262. if (_this.onPrePointerObservable.hasObservers()) {
  17263. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17264. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17265. _this.onPrePointerObservable.notifyObservers(pi, type);
  17266. if (pi.skipOnPointerObservable) {
  17267. return;
  17268. }
  17269. }
  17270. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17271. return;
  17272. }
  17273. var canvas = _this._engine.getRenderingCanvas();
  17274. if (!_this.pointerMovePredicate) {
  17275. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17276. }
  17277. // Meshes
  17278. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17279. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17280. _this.setPointerOverSprite(null);
  17281. _this.setPointerOverMesh(pickResult.pickedMesh);
  17282. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17283. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17284. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17285. }
  17286. else {
  17287. canvas.style.cursor = _this.hoverCursor;
  17288. }
  17289. }
  17290. else {
  17291. canvas.style.cursor = _this.defaultCursor;
  17292. }
  17293. }
  17294. else {
  17295. _this.setPointerOverMesh(null);
  17296. // Sprites
  17297. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17298. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17299. _this.setPointerOverSprite(pickResult.pickedSprite);
  17300. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17301. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17302. }
  17303. else {
  17304. canvas.style.cursor = _this.hoverCursor;
  17305. }
  17306. }
  17307. else {
  17308. _this.setPointerOverSprite(null);
  17309. // Restore pointer
  17310. canvas.style.cursor = _this.defaultCursor;
  17311. }
  17312. }
  17313. if (_this.onPointerMove) {
  17314. _this.onPointerMove(evt, pickResult);
  17315. }
  17316. if (_this.onPointerObservable.hasObservers()) {
  17317. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17318. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17319. _this.onPointerObservable.notifyObservers(pi, type);
  17320. }
  17321. };
  17322. this._onPointerDown = function (evt) {
  17323. _this._isButtonPressed = true;
  17324. _this._pickedDownMesh = null;
  17325. _this._meshPickProceed = false;
  17326. _this._updatePointerPosition(evt);
  17327. // PreObservable support
  17328. if (_this.onPrePointerObservable.hasObservers()) {
  17329. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17330. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17331. _this.onPrePointerObservable.notifyObservers(pi, type);
  17332. if (pi.skipOnPointerObservable) {
  17333. return;
  17334. }
  17335. }
  17336. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17337. return;
  17338. }
  17339. _this._startingPointerPosition.x = _this._pointerX;
  17340. _this._startingPointerPosition.y = _this._pointerY;
  17341. _this._startingPointerTime = new Date().getTime();
  17342. if (!_this.pointerDownPredicate) {
  17343. _this.pointerDownPredicate = function (mesh) {
  17344. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17345. };
  17346. }
  17347. // Meshes
  17348. _this._pickedDownMesh = null;
  17349. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17350. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17351. _this._pickedDownMesh = pickResult.pickedMesh;
  17352. var actionManager = pickResult.pickedMesh.actionManager;
  17353. if (actionManager) {
  17354. if (actionManager.hasPickTriggers) {
  17355. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17356. switch (evt.button) {
  17357. case 0:
  17358. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17359. break;
  17360. case 1:
  17361. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17362. break;
  17363. case 2:
  17364. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17365. break;
  17366. }
  17367. }
  17368. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17369. window.setTimeout((function () {
  17370. var _this = this;
  17371. 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);
  17372. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17373. if (this._isButtonPressed &&
  17374. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17375. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17376. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17377. this._startingPointerTime = 0;
  17378. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17379. }
  17380. }
  17381. }).bind(_this), Scene.LongPressDelay);
  17382. }
  17383. }
  17384. }
  17385. if (_this.onPointerDown) {
  17386. _this.onPointerDown(evt, pickResult);
  17387. }
  17388. if (_this.onPointerObservable.hasObservers()) {
  17389. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17390. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17391. _this.onPointerObservable.notifyObservers(pi, type);
  17392. }
  17393. // Sprites
  17394. _this._pickedDownSprite = null;
  17395. if (_this.spriteManagers.length > 0) {
  17396. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17397. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17398. if (pickResult.pickedSprite.actionManager) {
  17399. _this._pickedDownSprite = pickResult.pickedSprite;
  17400. switch (evt.button) {
  17401. case 0:
  17402. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17403. break;
  17404. case 1:
  17405. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17406. break;
  17407. case 2:
  17408. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17409. break;
  17410. }
  17411. if (pickResult.pickedSprite.actionManager) {
  17412. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17413. }
  17414. }
  17415. }
  17416. }
  17417. };
  17418. this._onPointerUp = function (evt) {
  17419. _this._isButtonPressed = false;
  17420. _this._pickedUpMesh = null;
  17421. _this._meshPickProceed = false;
  17422. _this._updatePointerPosition(evt);
  17423. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17424. // PreObservable support
  17425. if (this.onPrePointerObservable.hasObservers()) {
  17426. if (!clickInfo.ignore) {
  17427. if (!clickInfo.hasSwiped) {
  17428. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17429. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17430. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17431. this.onPrePointerObservable.notifyObservers(pi, type);
  17432. if (pi.skipOnPointerObservable) {
  17433. return;
  17434. }
  17435. }
  17436. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17437. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17438. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17439. this.onPrePointerObservable.notifyObservers(pi, type);
  17440. if (pi.skipOnPointerObservable) {
  17441. return;
  17442. }
  17443. }
  17444. }
  17445. }
  17446. else {
  17447. var type = BABYLON.PointerEventTypes.POINTERUP;
  17448. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17449. this.onPrePointerObservable.notifyObservers(pi, type);
  17450. if (pi.skipOnPointerObservable) {
  17451. return;
  17452. }
  17453. }
  17454. }
  17455. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17456. return;
  17457. }
  17458. if (!this.pointerUpPredicate) {
  17459. this.pointerUpPredicate = function (mesh) {
  17460. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17461. };
  17462. }
  17463. // Meshes
  17464. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17465. this._initActionManager(null, clickInfo);
  17466. }
  17467. if (!pickResult) {
  17468. pickResult = this._currentPickResult;
  17469. }
  17470. if (pickResult && pickResult && pickResult.pickedMesh) {
  17471. this._pickedUpMesh = pickResult.pickedMesh;
  17472. if (this._pickedDownMesh === this._pickedUpMesh) {
  17473. if (this.onPointerPick) {
  17474. this.onPointerPick(evt, pickResult);
  17475. }
  17476. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17477. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17478. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17479. this.onPointerObservable.notifyObservers(pi, type);
  17480. }
  17481. }
  17482. if (pickResult.pickedMesh.actionManager) {
  17483. if (clickInfo.ignore) {
  17484. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17485. }
  17486. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17487. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17488. }
  17489. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17490. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17491. }
  17492. }
  17493. }
  17494. if (this._pickedDownMesh &&
  17495. this._pickedDownMesh.actionManager &&
  17496. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17497. this._pickedDownMesh !== this._pickedUpMesh) {
  17498. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17499. }
  17500. if (this.onPointerUp) {
  17501. this.onPointerUp(evt, pickResult);
  17502. }
  17503. if (this.onPointerObservable.hasObservers()) {
  17504. if (!clickInfo.ignore) {
  17505. if (!clickInfo.hasSwiped) {
  17506. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17507. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17508. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17509. this.onPointerObservable.notifyObservers(pi, type);
  17510. }
  17511. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17512. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17513. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17514. this.onPointerObservable.notifyObservers(pi, type);
  17515. }
  17516. }
  17517. }
  17518. else {
  17519. var type = BABYLON.PointerEventTypes.POINTERUP;
  17520. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17521. this.onPointerObservable.notifyObservers(pi, type);
  17522. }
  17523. }
  17524. // Sprites
  17525. if (this.spriteManagers.length > 0) {
  17526. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17527. if (pickResult.hit && pickResult.pickedSprite) {
  17528. if (pickResult.pickedSprite.actionManager) {
  17529. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17530. if (pickResult.pickedSprite.actionManager) {
  17531. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17532. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17533. }
  17534. }
  17535. }
  17536. }
  17537. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17538. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17539. }
  17540. }
  17541. this._previousPickResult = this._currentPickResult;
  17542. }).bind(_this));
  17543. };
  17544. this._onKeyDown = function (evt) {
  17545. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  17546. if (_this.onPreKeyboardObservable.hasObservers()) {
  17547. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17548. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17549. if (pi.skipOnPointerObservable) {
  17550. return;
  17551. }
  17552. }
  17553. if (_this.onKeyboardObservable.hasObservers()) {
  17554. var pi = new BABYLON.KeyboardInfo(type, evt);
  17555. _this.onKeyboardObservable.notifyObservers(pi, type);
  17556. }
  17557. if (_this.actionManager) {
  17558. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17559. }
  17560. };
  17561. this._onKeyUp = function (evt) {
  17562. var type = BABYLON.KeyboardEventTypes.KEYUP;
  17563. if (_this.onPreKeyboardObservable.hasObservers()) {
  17564. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17565. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17566. if (pi.skipOnPointerObservable) {
  17567. return;
  17568. }
  17569. }
  17570. if (_this.onKeyboardObservable.hasObservers()) {
  17571. var pi = new BABYLON.KeyboardInfo(type, evt);
  17572. _this.onKeyboardObservable.notifyObservers(pi, type);
  17573. }
  17574. if (_this.actionManager) {
  17575. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17576. }
  17577. };
  17578. var engine = this.getEngine();
  17579. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  17580. canvas.addEventListener("keydown", _this._onKeyDown, false);
  17581. canvas.addEventListener("keyup", _this._onKeyUp, false);
  17582. });
  17583. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  17584. canvas.removeEventListener("keydown", _this._onKeyDown);
  17585. canvas.removeEventListener("keyup", _this._onKeyUp);
  17586. });
  17587. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17588. var canvas = this._engine.getRenderingCanvas();
  17589. if (attachMove) {
  17590. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17591. // Wheel
  17592. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17593. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17594. }
  17595. if (attachDown) {
  17596. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17597. }
  17598. if (attachUp) {
  17599. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17600. }
  17601. canvas.tabIndex = 1;
  17602. };
  17603. Scene.prototype.detachControl = function () {
  17604. var engine = this.getEngine();
  17605. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17606. var canvas = engine.getRenderingCanvas();
  17607. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17608. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17609. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17610. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  17611. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  17612. // Wheel
  17613. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17614. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17615. // Keyboard
  17616. canvas.removeEventListener("keydown", this._onKeyDown);
  17617. canvas.removeEventListener("keyup", this._onKeyUp);
  17618. // Observables
  17619. this.onKeyboardObservable.clear();
  17620. this.onPreKeyboardObservable.clear();
  17621. this.onPointerObservable.clear();
  17622. this.onPrePointerObservable.clear();
  17623. };
  17624. // Ready
  17625. Scene.prototype.isReady = function () {
  17626. if (this._pendingData.length > 0) {
  17627. return false;
  17628. }
  17629. var index;
  17630. // Geometries
  17631. for (index = 0; index < this._geometries.length; index++) {
  17632. var geometry = this._geometries[index];
  17633. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17634. return false;
  17635. }
  17636. }
  17637. // Meshes
  17638. for (index = 0; index < this.meshes.length; index++) {
  17639. var mesh = this.meshes[index];
  17640. if (!mesh.isEnabled()) {
  17641. continue;
  17642. }
  17643. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17644. continue;
  17645. }
  17646. if (!mesh.isReady()) {
  17647. return false;
  17648. }
  17649. var mat = mesh.material;
  17650. if (mat) {
  17651. if (!mat.isReady(mesh)) {
  17652. return false;
  17653. }
  17654. }
  17655. }
  17656. return true;
  17657. };
  17658. Scene.prototype.resetCachedMaterial = function () {
  17659. this._cachedMaterial = null;
  17660. this._cachedEffect = null;
  17661. this._cachedVisibility = null;
  17662. };
  17663. Scene.prototype.registerBeforeRender = function (func) {
  17664. this.onBeforeRenderObservable.add(func);
  17665. };
  17666. Scene.prototype.unregisterBeforeRender = function (func) {
  17667. this.onBeforeRenderObservable.removeCallback(func);
  17668. };
  17669. Scene.prototype.registerAfterRender = function (func) {
  17670. this.onAfterRenderObservable.add(func);
  17671. };
  17672. Scene.prototype.unregisterAfterRender = function (func) {
  17673. this.onAfterRenderObservable.removeCallback(func);
  17674. };
  17675. Scene.prototype._addPendingData = function (data) {
  17676. this._pendingData.push(data);
  17677. };
  17678. Scene.prototype._removePendingData = function (data) {
  17679. var index = this._pendingData.indexOf(data);
  17680. if (index !== -1) {
  17681. this._pendingData.splice(index, 1);
  17682. }
  17683. };
  17684. Scene.prototype.getWaitingItemsCount = function () {
  17685. return this._pendingData.length;
  17686. };
  17687. /**
  17688. * Registers a function to be executed when the scene is ready.
  17689. * @param {Function} func - the function to be executed.
  17690. */
  17691. Scene.prototype.executeWhenReady = function (func) {
  17692. var _this = this;
  17693. this.onReadyObservable.add(func);
  17694. if (this._executeWhenReadyTimeoutId !== -1) {
  17695. return;
  17696. }
  17697. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17698. _this._checkIsReady();
  17699. }, 150);
  17700. };
  17701. Scene.prototype._checkIsReady = function () {
  17702. var _this = this;
  17703. if (this.isReady()) {
  17704. this.onReadyObservable.notifyObservers(this);
  17705. this.onReadyObservable.clear();
  17706. this._executeWhenReadyTimeoutId = -1;
  17707. return;
  17708. }
  17709. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17710. _this._checkIsReady();
  17711. }, 150);
  17712. };
  17713. // Animations
  17714. /**
  17715. * Will start the animation sequence of a given target
  17716. * @param target - the target
  17717. * @param {number} from - from which frame should animation start
  17718. * @param {number} to - till which frame should animation run.
  17719. * @param {boolean} [loop] - should the animation loop
  17720. * @param {number} [speedRatio] - the speed in which to run the animation
  17721. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17722. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17723. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17724. * See BABYLON.Animatable
  17725. */
  17726. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17727. if (speedRatio === void 0) { speedRatio = 1.0; }
  17728. if (from > to && speedRatio > 0) {
  17729. speedRatio *= -1;
  17730. }
  17731. this.stopAnimation(target);
  17732. if (!animatable) {
  17733. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17734. }
  17735. // Local animations
  17736. if (target.animations) {
  17737. animatable.appendAnimations(target, target.animations);
  17738. }
  17739. // Children animations
  17740. if (target.getAnimatables) {
  17741. var animatables = target.getAnimatables();
  17742. for (var index = 0; index < animatables.length; index++) {
  17743. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17744. }
  17745. }
  17746. animatable.reset();
  17747. return animatable;
  17748. };
  17749. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17750. if (speedRatio === undefined) {
  17751. speedRatio = 1.0;
  17752. }
  17753. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17754. return animatable;
  17755. };
  17756. Scene.prototype.getAnimatableByTarget = function (target) {
  17757. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17758. if (this._activeAnimatables[index].target === target) {
  17759. return this._activeAnimatables[index];
  17760. }
  17761. }
  17762. return null;
  17763. };
  17764. Object.defineProperty(Scene.prototype, "Animatables", {
  17765. get: function () {
  17766. return this._activeAnimatables;
  17767. },
  17768. enumerable: true,
  17769. configurable: true
  17770. });
  17771. /**
  17772. * Will stop the animation of the given target
  17773. * @param target - the target
  17774. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17775. * @see beginAnimation
  17776. */
  17777. Scene.prototype.stopAnimation = function (target, animationName) {
  17778. var animatable = this.getAnimatableByTarget(target);
  17779. if (animatable) {
  17780. animatable.stop(animationName);
  17781. }
  17782. };
  17783. Scene.prototype._animate = function () {
  17784. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17785. return;
  17786. }
  17787. // Getting time
  17788. var now = BABYLON.Tools.Now;
  17789. if (!this._animationTimeLast) {
  17790. if (this._pendingData.length > 0) {
  17791. return;
  17792. }
  17793. this._animationTimeLast = now;
  17794. }
  17795. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17796. this._animationTime += deltaTime;
  17797. this._animationTimeLast = now;
  17798. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17799. this._activeAnimatables[index]._animate(this._animationTime);
  17800. }
  17801. };
  17802. // Matrix
  17803. Scene.prototype.getViewMatrix = function () {
  17804. return this._viewMatrix;
  17805. };
  17806. Scene.prototype.getProjectionMatrix = function () {
  17807. return this._projectionMatrix;
  17808. };
  17809. Scene.prototype.getTransformMatrix = function () {
  17810. return this._transformMatrix;
  17811. };
  17812. Scene.prototype.setTransformMatrix = function (view, projection) {
  17813. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17814. return;
  17815. }
  17816. this._viewUpdateFlag = view.updateFlag;
  17817. this._projectionUpdateFlag = projection.updateFlag;
  17818. this._viewMatrix = view;
  17819. this._projectionMatrix = projection;
  17820. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17821. // Update frustum
  17822. if (!this._frustumPlanes) {
  17823. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17824. }
  17825. else {
  17826. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17827. }
  17828. if (this._sceneUbo.useUbo) {
  17829. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17830. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17831. this._sceneUbo.update();
  17832. }
  17833. };
  17834. Scene.prototype.getSceneUniformBuffer = function () {
  17835. return this._sceneUbo;
  17836. };
  17837. // Methods
  17838. Scene.prototype.getUniqueId = function () {
  17839. var result = this._uniqueIdCounter;
  17840. this._uniqueIdCounter++;
  17841. return result;
  17842. };
  17843. Scene.prototype.addMesh = function (newMesh) {
  17844. newMesh.uniqueId = this.getUniqueId();
  17845. var position = this.meshes.push(newMesh);
  17846. //notify the collision coordinator
  17847. if (this.collisionCoordinator) {
  17848. this.collisionCoordinator.onMeshAdded(newMesh);
  17849. }
  17850. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17851. };
  17852. Scene.prototype.removeMesh = function (toRemove) {
  17853. var index = this.meshes.indexOf(toRemove);
  17854. if (index !== -1) {
  17855. // Remove from the scene if mesh found
  17856. this.meshes.splice(index, 1);
  17857. }
  17858. //notify the collision coordinator
  17859. if (this.collisionCoordinator) {
  17860. this.collisionCoordinator.onMeshRemoved(toRemove);
  17861. }
  17862. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17863. return index;
  17864. };
  17865. Scene.prototype.removeSkeleton = function (toRemove) {
  17866. var index = this.skeletons.indexOf(toRemove);
  17867. if (index !== -1) {
  17868. // Remove from the scene if found
  17869. this.skeletons.splice(index, 1);
  17870. }
  17871. return index;
  17872. };
  17873. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17874. var index = this.morphTargetManagers.indexOf(toRemove);
  17875. if (index !== -1) {
  17876. // Remove from the scene if found
  17877. this.morphTargetManagers.splice(index, 1);
  17878. }
  17879. return index;
  17880. };
  17881. Scene.prototype.removeLight = function (toRemove) {
  17882. var index = this.lights.indexOf(toRemove);
  17883. if (index !== -1) {
  17884. // Remove from the scene if mesh found
  17885. this.lights.splice(index, 1);
  17886. this.sortLightsByPriority();
  17887. }
  17888. this.onLightRemovedObservable.notifyObservers(toRemove);
  17889. return index;
  17890. };
  17891. Scene.prototype.removeCamera = function (toRemove) {
  17892. var index = this.cameras.indexOf(toRemove);
  17893. if (index !== -1) {
  17894. // Remove from the scene if mesh found
  17895. this.cameras.splice(index, 1);
  17896. }
  17897. // Remove from activeCameras
  17898. var index2 = this.activeCameras.indexOf(toRemove);
  17899. if (index2 !== -1) {
  17900. // Remove from the scene if mesh found
  17901. this.activeCameras.splice(index2, 1);
  17902. }
  17903. // Reset the activeCamera
  17904. if (this.activeCamera === toRemove) {
  17905. if (this.cameras.length > 0) {
  17906. this.activeCamera = this.cameras[0];
  17907. }
  17908. else {
  17909. this.activeCamera = null;
  17910. }
  17911. }
  17912. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17913. return index;
  17914. };
  17915. Scene.prototype.addLight = function (newLight) {
  17916. newLight.uniqueId = this.getUniqueId();
  17917. this.lights.push(newLight);
  17918. this.sortLightsByPriority();
  17919. this.onNewLightAddedObservable.notifyObservers(newLight);
  17920. };
  17921. Scene.prototype.sortLightsByPriority = function () {
  17922. if (this.requireLightSorting) {
  17923. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17924. }
  17925. };
  17926. Scene.prototype.addCamera = function (newCamera) {
  17927. newCamera.uniqueId = this.getUniqueId();
  17928. var position = this.cameras.push(newCamera);
  17929. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17930. };
  17931. /**
  17932. * Switch active camera
  17933. * @param {Camera} newCamera - new active camera
  17934. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17935. */
  17936. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17937. if (attachControl === void 0) { attachControl = true; }
  17938. var canvas = this._engine.getRenderingCanvas();
  17939. this.activeCamera.detachControl(canvas);
  17940. this.activeCamera = newCamera;
  17941. if (attachControl) {
  17942. newCamera.attachControl(canvas);
  17943. }
  17944. };
  17945. /**
  17946. * sets the active camera of the scene using its ID
  17947. * @param {string} id - the camera's ID
  17948. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17949. * @see activeCamera
  17950. */
  17951. Scene.prototype.setActiveCameraByID = function (id) {
  17952. var camera = this.getCameraByID(id);
  17953. if (camera) {
  17954. this.activeCamera = camera;
  17955. return camera;
  17956. }
  17957. return null;
  17958. };
  17959. /**
  17960. * sets the active camera of the scene using its name
  17961. * @param {string} name - the camera's name
  17962. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17963. * @see activeCamera
  17964. */
  17965. Scene.prototype.setActiveCameraByName = function (name) {
  17966. var camera = this.getCameraByName(name);
  17967. if (camera) {
  17968. this.activeCamera = camera;
  17969. return camera;
  17970. }
  17971. return null;
  17972. };
  17973. /**
  17974. * get a material using its id
  17975. * @param {string} the material's ID
  17976. * @return {BABYLON.Material|null} the material or null if none found.
  17977. */
  17978. Scene.prototype.getMaterialByID = function (id) {
  17979. for (var index = 0; index < this.materials.length; index++) {
  17980. if (this.materials[index].id === id) {
  17981. return this.materials[index];
  17982. }
  17983. }
  17984. return null;
  17985. };
  17986. /**
  17987. * get a material using its name
  17988. * @param {string} the material's name
  17989. * @return {BABYLON.Material|null} the material or null if none found.
  17990. */
  17991. Scene.prototype.getMaterialByName = function (name) {
  17992. for (var index = 0; index < this.materials.length; index++) {
  17993. if (this.materials[index].name === name) {
  17994. return this.materials[index];
  17995. }
  17996. }
  17997. return null;
  17998. };
  17999. Scene.prototype.getLensFlareSystemByName = function (name) {
  18000. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18001. if (this.lensFlareSystems[index].name === name) {
  18002. return this.lensFlareSystems[index];
  18003. }
  18004. }
  18005. return null;
  18006. };
  18007. Scene.prototype.getLensFlareSystemByID = function (id) {
  18008. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18009. if (this.lensFlareSystems[index].id === id) {
  18010. return this.lensFlareSystems[index];
  18011. }
  18012. }
  18013. return null;
  18014. };
  18015. Scene.prototype.getCameraByID = function (id) {
  18016. for (var index = 0; index < this.cameras.length; index++) {
  18017. if (this.cameras[index].id === id) {
  18018. return this.cameras[index];
  18019. }
  18020. }
  18021. return null;
  18022. };
  18023. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18024. for (var index = 0; index < this.cameras.length; index++) {
  18025. if (this.cameras[index].uniqueId === uniqueId) {
  18026. return this.cameras[index];
  18027. }
  18028. }
  18029. return null;
  18030. };
  18031. /**
  18032. * get a camera using its name
  18033. * @param {string} the camera's name
  18034. * @return {BABYLON.Camera|null} the camera or null if none found.
  18035. */
  18036. Scene.prototype.getCameraByName = function (name) {
  18037. for (var index = 0; index < this.cameras.length; index++) {
  18038. if (this.cameras[index].name === name) {
  18039. return this.cameras[index];
  18040. }
  18041. }
  18042. return null;
  18043. };
  18044. /**
  18045. * get a bone using its id
  18046. * @param {string} the bone's id
  18047. * @return {BABYLON.Bone|null} the bone or null if not found
  18048. */
  18049. Scene.prototype.getBoneByID = function (id) {
  18050. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18051. var skeleton = this.skeletons[skeletonIndex];
  18052. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18053. if (skeleton.bones[boneIndex].id === id) {
  18054. return skeleton.bones[boneIndex];
  18055. }
  18056. }
  18057. }
  18058. return null;
  18059. };
  18060. /**
  18061. * get a bone using its id
  18062. * @param {string} the bone's name
  18063. * @return {BABYLON.Bone|null} the bone or null if not found
  18064. */
  18065. Scene.prototype.getBoneByName = function (name) {
  18066. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18067. var skeleton = this.skeletons[skeletonIndex];
  18068. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18069. if (skeleton.bones[boneIndex].name === name) {
  18070. return skeleton.bones[boneIndex];
  18071. }
  18072. }
  18073. }
  18074. return null;
  18075. };
  18076. /**
  18077. * get a light node using its name
  18078. * @param {string} the light's name
  18079. * @return {BABYLON.Light|null} the light or null if none found.
  18080. */
  18081. Scene.prototype.getLightByName = function (name) {
  18082. for (var index = 0; index < this.lights.length; index++) {
  18083. if (this.lights[index].name === name) {
  18084. return this.lights[index];
  18085. }
  18086. }
  18087. return null;
  18088. };
  18089. /**
  18090. * get a light node using its ID
  18091. * @param {string} the light's id
  18092. * @return {BABYLON.Light|null} the light or null if none found.
  18093. */
  18094. Scene.prototype.getLightByID = function (id) {
  18095. for (var index = 0; index < this.lights.length; index++) {
  18096. if (this.lights[index].id === id) {
  18097. return this.lights[index];
  18098. }
  18099. }
  18100. return null;
  18101. };
  18102. /**
  18103. * get a light node using its scene-generated unique ID
  18104. * @param {number} the light's unique id
  18105. * @return {BABYLON.Light|null} the light or null if none found.
  18106. */
  18107. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18108. for (var index = 0; index < this.lights.length; index++) {
  18109. if (this.lights[index].uniqueId === uniqueId) {
  18110. return this.lights[index];
  18111. }
  18112. }
  18113. return null;
  18114. };
  18115. /**
  18116. * get a particle system by id
  18117. * @param id {number} the particle system id
  18118. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18119. */
  18120. Scene.prototype.getParticleSystemByID = function (id) {
  18121. for (var index = 0; index < this.particleSystems.length; index++) {
  18122. if (this.particleSystems[index].id === id) {
  18123. return this.particleSystems[index];
  18124. }
  18125. }
  18126. return null;
  18127. };
  18128. /**
  18129. * get a geometry using its ID
  18130. * @param {string} the geometry's id
  18131. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18132. */
  18133. Scene.prototype.getGeometryByID = function (id) {
  18134. for (var index = 0; index < this._geometries.length; index++) {
  18135. if (this._geometries[index].id === id) {
  18136. return this._geometries[index];
  18137. }
  18138. }
  18139. return null;
  18140. };
  18141. /**
  18142. * add a new geometry to this scene.
  18143. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18144. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18145. * @return {boolean} was the geometry added or not
  18146. */
  18147. Scene.prototype.pushGeometry = function (geometry, force) {
  18148. if (!force && this.getGeometryByID(geometry.id)) {
  18149. return false;
  18150. }
  18151. this._geometries.push(geometry);
  18152. //notify the collision coordinator
  18153. if (this.collisionCoordinator) {
  18154. this.collisionCoordinator.onGeometryAdded(geometry);
  18155. }
  18156. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18157. return true;
  18158. };
  18159. /**
  18160. * Removes an existing geometry
  18161. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18162. * @return {boolean} was the geometry removed or not
  18163. */
  18164. Scene.prototype.removeGeometry = function (geometry) {
  18165. var index = this._geometries.indexOf(geometry);
  18166. if (index > -1) {
  18167. this._geometries.splice(index, 1);
  18168. //notify the collision coordinator
  18169. if (this.collisionCoordinator) {
  18170. this.collisionCoordinator.onGeometryDeleted(geometry);
  18171. }
  18172. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18173. return true;
  18174. }
  18175. return false;
  18176. };
  18177. Scene.prototype.getGeometries = function () {
  18178. return this._geometries;
  18179. };
  18180. /**
  18181. * Get the first added mesh found of a given ID
  18182. * @param {string} id - the id to search for
  18183. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18184. */
  18185. Scene.prototype.getMeshByID = function (id) {
  18186. for (var index = 0; index < this.meshes.length; index++) {
  18187. if (this.meshes[index].id === id) {
  18188. return this.meshes[index];
  18189. }
  18190. }
  18191. return null;
  18192. };
  18193. Scene.prototype.getMeshesByID = function (id) {
  18194. return this.meshes.filter(function (m) {
  18195. return m.id === id;
  18196. });
  18197. };
  18198. /**
  18199. * Get a mesh with its auto-generated unique id
  18200. * @param {number} uniqueId - the unique id to search for
  18201. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18202. */
  18203. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18204. for (var index = 0; index < this.meshes.length; index++) {
  18205. if (this.meshes[index].uniqueId === uniqueId) {
  18206. return this.meshes[index];
  18207. }
  18208. }
  18209. return null;
  18210. };
  18211. /**
  18212. * Get a the last added mesh found of a given ID
  18213. * @param {string} id - the id to search for
  18214. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18215. */
  18216. Scene.prototype.getLastMeshByID = function (id) {
  18217. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18218. if (this.meshes[index].id === id) {
  18219. return this.meshes[index];
  18220. }
  18221. }
  18222. return null;
  18223. };
  18224. /**
  18225. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18226. * @param {string} id - the id to search for
  18227. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18228. */
  18229. Scene.prototype.getLastEntryByID = function (id) {
  18230. var index;
  18231. for (index = this.meshes.length - 1; index >= 0; index--) {
  18232. if (this.meshes[index].id === id) {
  18233. return this.meshes[index];
  18234. }
  18235. }
  18236. for (index = this.cameras.length - 1; index >= 0; index--) {
  18237. if (this.cameras[index].id === id) {
  18238. return this.cameras[index];
  18239. }
  18240. }
  18241. for (index = this.lights.length - 1; index >= 0; index--) {
  18242. if (this.lights[index].id === id) {
  18243. return this.lights[index];
  18244. }
  18245. }
  18246. return null;
  18247. };
  18248. Scene.prototype.getNodeByID = function (id) {
  18249. var mesh = this.getMeshByID(id);
  18250. if (mesh) {
  18251. return mesh;
  18252. }
  18253. var light = this.getLightByID(id);
  18254. if (light) {
  18255. return light;
  18256. }
  18257. var camera = this.getCameraByID(id);
  18258. if (camera) {
  18259. return camera;
  18260. }
  18261. var bone = this.getBoneByID(id);
  18262. return bone;
  18263. };
  18264. Scene.prototype.getNodeByName = function (name) {
  18265. var mesh = this.getMeshByName(name);
  18266. if (mesh) {
  18267. return mesh;
  18268. }
  18269. var light = this.getLightByName(name);
  18270. if (light) {
  18271. return light;
  18272. }
  18273. var camera = this.getCameraByName(name);
  18274. if (camera) {
  18275. return camera;
  18276. }
  18277. var bone = this.getBoneByName(name);
  18278. return bone;
  18279. };
  18280. Scene.prototype.getMeshByName = function (name) {
  18281. for (var index = 0; index < this.meshes.length; index++) {
  18282. if (this.meshes[index].name === name) {
  18283. return this.meshes[index];
  18284. }
  18285. }
  18286. return null;
  18287. };
  18288. Scene.prototype.getSoundByName = function (name) {
  18289. var index;
  18290. if (BABYLON.AudioEngine) {
  18291. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18292. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18293. return this.mainSoundTrack.soundCollection[index];
  18294. }
  18295. }
  18296. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18297. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18298. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18299. return this.soundTracks[sdIndex].soundCollection[index];
  18300. }
  18301. }
  18302. }
  18303. }
  18304. return null;
  18305. };
  18306. Scene.prototype.getLastSkeletonByID = function (id) {
  18307. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18308. if (this.skeletons[index].id === id) {
  18309. return this.skeletons[index];
  18310. }
  18311. }
  18312. return null;
  18313. };
  18314. Scene.prototype.getSkeletonById = function (id) {
  18315. for (var index = 0; index < this.skeletons.length; index++) {
  18316. if (this.skeletons[index].id === id) {
  18317. return this.skeletons[index];
  18318. }
  18319. }
  18320. return null;
  18321. };
  18322. Scene.prototype.getSkeletonByName = function (name) {
  18323. for (var index = 0; index < this.skeletons.length; index++) {
  18324. if (this.skeletons[index].name === name) {
  18325. return this.skeletons[index];
  18326. }
  18327. }
  18328. return null;
  18329. };
  18330. Scene.prototype.getMorphTargetManagerById = function (id) {
  18331. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18332. if (this.morphTargetManagers[index].uniqueId === id) {
  18333. return this.morphTargetManagers[index];
  18334. }
  18335. }
  18336. return null;
  18337. };
  18338. Scene.prototype.isActiveMesh = function (mesh) {
  18339. return (this._activeMeshes.indexOf(mesh) !== -1);
  18340. };
  18341. /**
  18342. * Return a the first highlight layer of the scene with a given name.
  18343. * @param name The name of the highlight layer to look for.
  18344. * @return The highlight layer if found otherwise null.
  18345. */
  18346. Scene.prototype.getHighlightLayerByName = function (name) {
  18347. for (var index = 0; index < this.highlightLayers.length; index++) {
  18348. if (this.highlightLayers[index].name === name) {
  18349. return this.highlightLayers[index];
  18350. }
  18351. }
  18352. return null;
  18353. };
  18354. Object.defineProperty(Scene.prototype, "uid", {
  18355. /**
  18356. * Return a unique id as a string which can serve as an identifier for the scene
  18357. */
  18358. get: function () {
  18359. if (!this._uid) {
  18360. this._uid = BABYLON.Tools.RandomId();
  18361. }
  18362. return this._uid;
  18363. },
  18364. enumerable: true,
  18365. configurable: true
  18366. });
  18367. /**
  18368. * Add an externaly attached data from its key.
  18369. * This method call will fail and return false, if such key already exists.
  18370. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18371. * @param key the unique key that identifies the data
  18372. * @param data the data object to associate to the key for this Engine instance
  18373. * @return true if no such key were already present and the data was added successfully, false otherwise
  18374. */
  18375. Scene.prototype.addExternalData = function (key, data) {
  18376. if (!this._externalData) {
  18377. this._externalData = new BABYLON.StringDictionary();
  18378. }
  18379. return this._externalData.add(key, data);
  18380. };
  18381. /**
  18382. * Get an externaly attached data from its key
  18383. * @param key the unique key that identifies the data
  18384. * @return the associated data, if present (can be null), or undefined if not present
  18385. */
  18386. Scene.prototype.getExternalData = function (key) {
  18387. if (!this._externalData) {
  18388. return null;
  18389. }
  18390. return this._externalData.get(key);
  18391. };
  18392. /**
  18393. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18394. * @param key the unique key that identifies the data
  18395. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18396. * @return the associated data, can be null if the factory returned null.
  18397. */
  18398. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18399. if (!this._externalData) {
  18400. this._externalData = new BABYLON.StringDictionary();
  18401. }
  18402. return this._externalData.getOrAddWithFactory(key, factory);
  18403. };
  18404. /**
  18405. * Remove an externaly attached data from the Engine instance
  18406. * @param key the unique key that identifies the data
  18407. * @return true if the data was successfully removed, false if it doesn't exist
  18408. */
  18409. Scene.prototype.removeExternalData = function (key) {
  18410. return this._externalData.remove(key);
  18411. };
  18412. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18413. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18414. var material = subMesh.getMaterial();
  18415. if (mesh.showSubMeshesBoundingBox) {
  18416. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18417. }
  18418. if (material) {
  18419. // Render targets
  18420. if (material.getRenderTargetTextures) {
  18421. if (this._processedMaterials.indexOf(material) === -1) {
  18422. this._processedMaterials.push(material);
  18423. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18424. }
  18425. }
  18426. // Dispatch
  18427. this._activeIndices.addCount(subMesh.indexCount, false);
  18428. this._renderingManager.dispatch(subMesh);
  18429. }
  18430. }
  18431. };
  18432. Scene.prototype._isInIntermediateRendering = function () {
  18433. return this._intermediateRendering;
  18434. };
  18435. Scene.prototype._evaluateActiveMeshes = function () {
  18436. this.activeCamera._activeMeshes.reset();
  18437. this._activeMeshes.reset();
  18438. this._renderingManager.reset();
  18439. this._processedMaterials.reset();
  18440. this._activeParticleSystems.reset();
  18441. this._activeSkeletons.reset();
  18442. this._softwareSkinnedMeshes.reset();
  18443. if (this._boundingBoxRenderer) {
  18444. this._boundingBoxRenderer.reset();
  18445. }
  18446. // Meshes
  18447. var meshes;
  18448. var len;
  18449. if (this._selectionOctree) {
  18450. var selection = this._selectionOctree.select(this._frustumPlanes);
  18451. meshes = selection.data;
  18452. len = selection.length;
  18453. }
  18454. else {
  18455. len = this.meshes.length;
  18456. meshes = this.meshes;
  18457. }
  18458. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18459. var mesh = meshes[meshIndex];
  18460. if (mesh.isBlocked) {
  18461. continue;
  18462. }
  18463. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18464. if (!mesh.isReady() || !mesh.isEnabled()) {
  18465. continue;
  18466. }
  18467. mesh.computeWorldMatrix();
  18468. // Intersections
  18469. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18470. this._meshesForIntersections.pushNoDuplicate(mesh);
  18471. }
  18472. // Switch to current LOD
  18473. var meshLOD = mesh.getLOD(this.activeCamera);
  18474. if (!meshLOD) {
  18475. continue;
  18476. }
  18477. mesh._preActivate();
  18478. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18479. this._activeMeshes.push(mesh);
  18480. this.activeCamera._activeMeshes.push(mesh);
  18481. mesh._activate(this._renderId);
  18482. if (meshLOD !== mesh) {
  18483. meshLOD._activate(this._renderId);
  18484. }
  18485. this._activeMesh(mesh, meshLOD);
  18486. }
  18487. }
  18488. // Particle systems
  18489. this._particlesDuration.beginMonitoring();
  18490. var beforeParticlesDate = BABYLON.Tools.Now;
  18491. if (this.particlesEnabled) {
  18492. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18493. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18494. var particleSystem = this.particleSystems[particleIndex];
  18495. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18496. continue;
  18497. }
  18498. var emitter = particleSystem.emitter;
  18499. if (!emitter.position || emitter.isEnabled()) {
  18500. this._activeParticleSystems.push(particleSystem);
  18501. particleSystem.animate();
  18502. this._renderingManager.dispatchParticles(particleSystem);
  18503. }
  18504. }
  18505. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18506. }
  18507. this._particlesDuration.endMonitoring(false);
  18508. };
  18509. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18510. if (mesh.skeleton && this.skeletonsEnabled) {
  18511. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18512. mesh.skeleton.prepare();
  18513. }
  18514. if (!mesh.computeBonesUsingShaders) {
  18515. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18516. }
  18517. }
  18518. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18519. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18520. }
  18521. if (mesh && mesh.subMeshes) {
  18522. // Submeshes Octrees
  18523. var len;
  18524. var subMeshes;
  18525. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18526. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18527. len = intersections.length;
  18528. subMeshes = intersections.data;
  18529. }
  18530. else {
  18531. subMeshes = mesh.subMeshes;
  18532. len = subMeshes.length;
  18533. }
  18534. for (var subIndex = 0; subIndex < len; subIndex++) {
  18535. var subMesh = subMeshes[subIndex];
  18536. this._evaluateSubMesh(subMesh, mesh);
  18537. }
  18538. }
  18539. };
  18540. Scene.prototype.updateTransformMatrix = function (force) {
  18541. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18542. };
  18543. Scene.prototype._renderForCamera = function (camera) {
  18544. var engine = this._engine;
  18545. var startTime = BABYLON.Tools.Now;
  18546. this.activeCamera = camera;
  18547. if (!this.activeCamera)
  18548. throw new Error("Active camera not set");
  18549. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18550. // Viewport
  18551. engine.setViewport(this.activeCamera.viewport);
  18552. // Camera
  18553. this.resetCachedMaterial();
  18554. this._renderId++;
  18555. this.updateTransformMatrix();
  18556. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18557. // Meshes
  18558. this._evaluateActiveMeshesDuration.beginMonitoring();
  18559. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18560. this._evaluateActiveMeshes();
  18561. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18562. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18563. // Software skinning
  18564. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18565. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18566. mesh.applySkeleton(mesh.skeleton);
  18567. }
  18568. // Render targets
  18569. this._renderTargetsDuration.beginMonitoring();
  18570. var needsRestoreFrameBuffer = false;
  18571. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18572. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18573. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18574. }
  18575. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18576. this._intermediateRendering = true;
  18577. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18578. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18579. var renderTarget = this._renderTargets.data[renderIndex];
  18580. if (renderTarget._shouldRender()) {
  18581. this._renderId++;
  18582. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18583. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18584. }
  18585. }
  18586. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18587. this._intermediateRendering = false;
  18588. this._renderId++;
  18589. needsRestoreFrameBuffer = true; // Restore back buffer
  18590. }
  18591. // Render HighlightLayer Texture
  18592. var stencilState = this._engine.getStencilBuffer();
  18593. var renderhighlights = false;
  18594. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18595. this._intermediateRendering = true;
  18596. for (var i = 0; i < this.highlightLayers.length; i++) {
  18597. var highlightLayer = this.highlightLayers[i];
  18598. if (highlightLayer.shouldRender() &&
  18599. (!highlightLayer.camera ||
  18600. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18601. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18602. renderhighlights = true;
  18603. var renderTarget = highlightLayer._mainTexture;
  18604. if (renderTarget._shouldRender()) {
  18605. this._renderId++;
  18606. renderTarget.render(false, false);
  18607. needsRestoreFrameBuffer = true;
  18608. }
  18609. }
  18610. }
  18611. this._intermediateRendering = false;
  18612. this._renderId++;
  18613. }
  18614. if (needsRestoreFrameBuffer) {
  18615. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18616. }
  18617. this._renderTargetsDuration.endMonitoring(false);
  18618. // Prepare Frame
  18619. this.postProcessManager._prepareFrame();
  18620. this._renderDuration.beginMonitoring();
  18621. // Backgrounds
  18622. var layerIndex;
  18623. var layer;
  18624. if (this.layers.length) {
  18625. engine.setDepthBuffer(false);
  18626. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18627. layer = this.layers[layerIndex];
  18628. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18629. layer.render();
  18630. }
  18631. }
  18632. engine.setDepthBuffer(true);
  18633. }
  18634. // Render
  18635. BABYLON.Tools.StartPerformanceCounter("Main render");
  18636. // Activate HighlightLayer stencil
  18637. if (renderhighlights) {
  18638. this._engine.setStencilBuffer(true);
  18639. }
  18640. this._renderingManager.render(null, null, true, true);
  18641. // Restore HighlightLayer stencil
  18642. if (renderhighlights) {
  18643. this._engine.setStencilBuffer(stencilState);
  18644. }
  18645. BABYLON.Tools.EndPerformanceCounter("Main render");
  18646. // Bounding boxes
  18647. if (this._boundingBoxRenderer) {
  18648. this._boundingBoxRenderer.render();
  18649. }
  18650. // Lens flares
  18651. if (this.lensFlaresEnabled) {
  18652. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18653. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18654. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18655. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18656. lensFlareSystem.render();
  18657. }
  18658. }
  18659. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18660. }
  18661. // Foregrounds
  18662. if (this.layers.length) {
  18663. engine.setDepthBuffer(false);
  18664. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18665. layer = this.layers[layerIndex];
  18666. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18667. layer.render();
  18668. }
  18669. }
  18670. engine.setDepthBuffer(true);
  18671. }
  18672. // Highlight Layer
  18673. if (renderhighlights) {
  18674. engine.setDepthBuffer(false);
  18675. for (var i = 0; i < this.highlightLayers.length; i++) {
  18676. if (this.highlightLayers[i].shouldRender()) {
  18677. this.highlightLayers[i].render();
  18678. }
  18679. }
  18680. engine.setDepthBuffer(true);
  18681. }
  18682. this._renderDuration.endMonitoring(false);
  18683. // Finalize frame
  18684. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18685. // Update camera
  18686. this.activeCamera._updateFromScene();
  18687. // Reset some special arrays
  18688. this._renderTargets.reset();
  18689. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18690. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18691. };
  18692. Scene.prototype._processSubCameras = function (camera) {
  18693. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18694. this._renderForCamera(camera);
  18695. return;
  18696. }
  18697. // rig cameras
  18698. for (var index = 0; index < camera._rigCameras.length; index++) {
  18699. this._renderForCamera(camera._rigCameras[index]);
  18700. }
  18701. this.activeCamera = camera;
  18702. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18703. // Update camera
  18704. this.activeCamera._updateFromScene();
  18705. };
  18706. Scene.prototype._checkIntersections = function () {
  18707. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18708. var sourceMesh = this._meshesForIntersections.data[index];
  18709. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18710. var action = sourceMesh.actionManager.actions[actionIndex];
  18711. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18712. var parameters = action.getTriggerParameter();
  18713. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18714. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18715. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18716. if (areIntersecting && currentIntersectionInProgress === -1) {
  18717. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18718. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18719. sourceMesh._intersectionsInProgress.push(otherMesh);
  18720. }
  18721. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18722. sourceMesh._intersectionsInProgress.push(otherMesh);
  18723. }
  18724. }
  18725. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18726. //They intersected, and now they don't.
  18727. //is this trigger an exit trigger? execute an event.
  18728. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18729. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18730. }
  18731. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18732. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18733. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18734. }
  18735. }
  18736. }
  18737. }
  18738. }
  18739. };
  18740. Scene.prototype.render = function () {
  18741. if (this.isDisposed) {
  18742. return;
  18743. }
  18744. this._lastFrameDuration.beginMonitoring();
  18745. this._particlesDuration.fetchNewFrame();
  18746. this._spritesDuration.fetchNewFrame();
  18747. this._activeParticles.fetchNewFrame();
  18748. this._renderDuration.fetchNewFrame();
  18749. this._renderTargetsDuration.fetchNewFrame();
  18750. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18751. this._totalVertices.fetchNewFrame();
  18752. this._activeIndices.fetchNewFrame();
  18753. this._activeBones.fetchNewFrame();
  18754. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18755. this._meshesForIntersections.reset();
  18756. this.resetCachedMaterial();
  18757. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18758. // Actions
  18759. if (this.actionManager) {
  18760. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18761. }
  18762. //Simplification Queue
  18763. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18764. this.simplificationQueue.executeNext();
  18765. }
  18766. if (this._engine.isDeterministicLockStep()) {
  18767. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18768. var defaultTimeStep = (60.0 / 1000.0);
  18769. if (this._physicsEngine) {
  18770. defaultTimeStep = this._physicsEngine.getTimeStep();
  18771. }
  18772. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18773. this._timeAccumulator += deltaTime;
  18774. // compute the amount of fixed steps we should have taken since the last step
  18775. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18776. internalSteps = Math.min(internalSteps, maxSubSteps);
  18777. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18778. this.onBeforeStepObservable.notifyObservers(this);
  18779. // Animations
  18780. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18781. this._animate();
  18782. // Physics
  18783. if (this._physicsEngine) {
  18784. BABYLON.Tools.StartPerformanceCounter("Physics");
  18785. this._physicsEngine._step(defaultTimeStep);
  18786. BABYLON.Tools.EndPerformanceCounter("Physics");
  18787. }
  18788. this._timeAccumulator -= defaultTimeStep;
  18789. this.onAfterStepObservable.notifyObservers(this);
  18790. this._currentStepId++;
  18791. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18792. // Q: can this be optimized by putting some code in the afterStep callback?
  18793. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18794. // would return incorrect positions for internal stepIds (non-rendered steps)
  18795. this._evaluateActiveMeshes();
  18796. }
  18797. }
  18798. }
  18799. else {
  18800. // Animations
  18801. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18802. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18803. this._animate();
  18804. // Physics
  18805. if (this._physicsEngine) {
  18806. BABYLON.Tools.StartPerformanceCounter("Physics");
  18807. this._physicsEngine._step(deltaTime / 1000.0);
  18808. BABYLON.Tools.EndPerformanceCounter("Physics");
  18809. }
  18810. }
  18811. // Before render
  18812. this.onBeforeRenderObservable.notifyObservers(this);
  18813. // Customs render targets
  18814. this._renderTargetsDuration.beginMonitoring();
  18815. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18816. var engine = this.getEngine();
  18817. var currentActiveCamera = this.activeCamera;
  18818. if (this.renderTargetsEnabled) {
  18819. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18820. this._intermediateRendering = true;
  18821. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18822. var renderTarget = this.customRenderTargets[customIndex];
  18823. if (renderTarget._shouldRender()) {
  18824. this._renderId++;
  18825. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18826. if (!this.activeCamera)
  18827. throw new Error("Active camera not set");
  18828. // Viewport
  18829. engine.setViewport(this.activeCamera.viewport);
  18830. // Camera
  18831. this.updateTransformMatrix();
  18832. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18833. }
  18834. }
  18835. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18836. this._intermediateRendering = false;
  18837. this._renderId++;
  18838. }
  18839. // Restore back buffer
  18840. if (this.customRenderTargets.length > 0) {
  18841. engine.restoreDefaultFramebuffer();
  18842. }
  18843. this._renderTargetsDuration.endMonitoring();
  18844. this.activeCamera = currentActiveCamera;
  18845. // Procedural textures
  18846. if (this.proceduralTexturesEnabled) {
  18847. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18848. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18849. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18850. if (proceduralTexture._shouldRender()) {
  18851. proceduralTexture.render();
  18852. }
  18853. }
  18854. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18855. }
  18856. // Clear
  18857. if (this.autoClearDepthAndStencil || this.autoClear) {
  18858. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18859. }
  18860. // Shadows
  18861. if (this.shadowsEnabled) {
  18862. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18863. var light = this.lights[lightIndex];
  18864. var shadowGenerator = light.getShadowGenerator();
  18865. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18866. var shadowMap = shadowGenerator.getShadowMap();
  18867. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18868. this._renderTargets.push(shadowMap);
  18869. }
  18870. }
  18871. }
  18872. }
  18873. // Depth renderer
  18874. if (this._depthRenderer) {
  18875. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18876. }
  18877. // Geometry renderer
  18878. if (this._geometryBufferRenderer) {
  18879. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18880. }
  18881. // RenderPipeline
  18882. if (this._postProcessRenderPipelineManager) {
  18883. this._postProcessRenderPipelineManager.update();
  18884. }
  18885. // Multi-cameras?
  18886. if (this.activeCameras.length > 0) {
  18887. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18888. if (cameraIndex > 0) {
  18889. this._engine.clear(null, false, true, true);
  18890. }
  18891. this._processSubCameras(this.activeCameras[cameraIndex]);
  18892. }
  18893. }
  18894. else {
  18895. if (!this.activeCamera) {
  18896. throw new Error("No camera defined");
  18897. }
  18898. this._processSubCameras(this.activeCamera);
  18899. }
  18900. // Intersection checks
  18901. this._checkIntersections();
  18902. // Update the audio listener attached to the camera
  18903. if (BABYLON.AudioEngine) {
  18904. this._updateAudioParameters();
  18905. }
  18906. // After render
  18907. if (this.afterRender) {
  18908. this.afterRender();
  18909. }
  18910. this.onAfterRenderObservable.notifyObservers(this);
  18911. // Cleaning
  18912. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18913. this._toBeDisposed.data[index].dispose();
  18914. this._toBeDisposed[index] = null;
  18915. }
  18916. this._toBeDisposed.reset();
  18917. if (this.dumpNextRenderTargets) {
  18918. this.dumpNextRenderTargets = false;
  18919. }
  18920. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18921. this._lastFrameDuration.endMonitoring();
  18922. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18923. this._totalLightsCounter.addCount(this.lights.length, true);
  18924. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18925. this._totalTexturesCounter.addCount(this.textures.length, true);
  18926. this._activeBones.addCount(0, true);
  18927. this._activeIndices.addCount(0, true);
  18928. this._activeParticles.addCount(0, true);
  18929. };
  18930. Scene.prototype._updateAudioParameters = function () {
  18931. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18932. return;
  18933. }
  18934. var listeningCamera;
  18935. var audioEngine = BABYLON.Engine.audioEngine;
  18936. if (this.activeCameras.length > 0) {
  18937. listeningCamera = this.activeCameras[0];
  18938. }
  18939. else {
  18940. listeningCamera = this.activeCamera;
  18941. }
  18942. if (listeningCamera && audioEngine.canUseWebAudio) {
  18943. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18944. // for VR cameras
  18945. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18946. listeningCamera = listeningCamera.rigCameras[0];
  18947. }
  18948. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18949. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18950. cameraDirection.normalize();
  18951. // To avoid some errors on GearVR
  18952. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18953. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18954. }
  18955. var i;
  18956. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18957. var sound = this.mainSoundTrack.soundCollection[i];
  18958. if (sound.useCustomAttenuation) {
  18959. sound.updateDistanceFromListener();
  18960. }
  18961. }
  18962. for (i = 0; i < this.soundTracks.length; i++) {
  18963. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18964. sound = this.soundTracks[i].soundCollection[j];
  18965. if (sound.useCustomAttenuation) {
  18966. sound.updateDistanceFromListener();
  18967. }
  18968. }
  18969. }
  18970. }
  18971. };
  18972. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18973. // Audio
  18974. get: function () {
  18975. return this._audioEnabled;
  18976. },
  18977. set: function (value) {
  18978. this._audioEnabled = value;
  18979. if (BABYLON.AudioEngine) {
  18980. if (this._audioEnabled) {
  18981. this._enableAudio();
  18982. }
  18983. else {
  18984. this._disableAudio();
  18985. }
  18986. }
  18987. },
  18988. enumerable: true,
  18989. configurable: true
  18990. });
  18991. Scene.prototype._disableAudio = function () {
  18992. var i;
  18993. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18994. this.mainSoundTrack.soundCollection[i].pause();
  18995. }
  18996. for (i = 0; i < this.soundTracks.length; i++) {
  18997. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18998. this.soundTracks[i].soundCollection[j].pause();
  18999. }
  19000. }
  19001. };
  19002. Scene.prototype._enableAudio = function () {
  19003. var i;
  19004. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19005. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19006. this.mainSoundTrack.soundCollection[i].play();
  19007. }
  19008. }
  19009. for (i = 0; i < this.soundTracks.length; i++) {
  19010. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19011. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19012. this.soundTracks[i].soundCollection[j].play();
  19013. }
  19014. }
  19015. }
  19016. };
  19017. Object.defineProperty(Scene.prototype, "headphone", {
  19018. get: function () {
  19019. return this._headphone;
  19020. },
  19021. set: function (value) {
  19022. this._headphone = value;
  19023. if (BABYLON.AudioEngine) {
  19024. if (this._headphone) {
  19025. this._switchAudioModeForHeadphones();
  19026. }
  19027. else {
  19028. this._switchAudioModeForNormalSpeakers();
  19029. }
  19030. }
  19031. },
  19032. enumerable: true,
  19033. configurable: true
  19034. });
  19035. Scene.prototype._switchAudioModeForHeadphones = function () {
  19036. this.mainSoundTrack.switchPanningModelToHRTF();
  19037. for (var i = 0; i < this.soundTracks.length; i++) {
  19038. this.soundTracks[i].switchPanningModelToHRTF();
  19039. }
  19040. };
  19041. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19042. this.mainSoundTrack.switchPanningModelToEqualPower();
  19043. for (var i = 0; i < this.soundTracks.length; i++) {
  19044. this.soundTracks[i].switchPanningModelToEqualPower();
  19045. }
  19046. };
  19047. Scene.prototype.enableDepthRenderer = function () {
  19048. if (this._depthRenderer) {
  19049. return this._depthRenderer;
  19050. }
  19051. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19052. return this._depthRenderer;
  19053. };
  19054. Scene.prototype.disableDepthRenderer = function () {
  19055. if (!this._depthRenderer) {
  19056. return;
  19057. }
  19058. this._depthRenderer.dispose();
  19059. this._depthRenderer = null;
  19060. };
  19061. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19062. if (ratio === void 0) { ratio = 1; }
  19063. if (this._geometryBufferRenderer) {
  19064. return this._geometryBufferRenderer;
  19065. }
  19066. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19067. if (!this._geometryBufferRenderer.isSupported) {
  19068. this._geometryBufferRenderer = null;
  19069. }
  19070. return this._geometryBufferRenderer;
  19071. };
  19072. Scene.prototype.disableGeometryBufferRenderer = function () {
  19073. if (!this._geometryBufferRenderer) {
  19074. return;
  19075. }
  19076. this._geometryBufferRenderer.dispose();
  19077. this._geometryBufferRenderer = null;
  19078. };
  19079. Scene.prototype.freezeMaterials = function () {
  19080. for (var i = 0; i < this.materials.length; i++) {
  19081. this.materials[i].freeze();
  19082. }
  19083. };
  19084. Scene.prototype.unfreezeMaterials = function () {
  19085. for (var i = 0; i < this.materials.length; i++) {
  19086. this.materials[i].unfreeze();
  19087. }
  19088. };
  19089. Scene.prototype.dispose = function () {
  19090. this.beforeRender = null;
  19091. this.afterRender = null;
  19092. this.skeletons = [];
  19093. this.morphTargetManagers = [];
  19094. this.importedMeshesFiles = new Array();
  19095. this.resetCachedMaterial();
  19096. if (this._depthRenderer) {
  19097. this._depthRenderer.dispose();
  19098. }
  19099. if (this._gamepadManager) {
  19100. this._gamepadManager.dispose();
  19101. this._gamepadManager = null;
  19102. }
  19103. // Smart arrays
  19104. if (this.activeCamera) {
  19105. this.activeCamera._activeMeshes.dispose();
  19106. this.activeCamera = null;
  19107. }
  19108. this._activeMeshes.dispose();
  19109. this._renderingManager.dispose();
  19110. this._processedMaterials.dispose();
  19111. this._activeParticleSystems.dispose();
  19112. this._activeSkeletons.dispose();
  19113. this._softwareSkinnedMeshes.dispose();
  19114. this._renderTargets.dispose();
  19115. if (this._boundingBoxRenderer) {
  19116. this._boundingBoxRenderer.dispose();
  19117. }
  19118. this._meshesForIntersections.dispose();
  19119. this._toBeDisposed.dispose();
  19120. // Debug layer
  19121. if (this._debugLayer) {
  19122. this._debugLayer.hide();
  19123. }
  19124. // Events
  19125. this.onDisposeObservable.notifyObservers(this);
  19126. this.onDisposeObservable.clear();
  19127. this.onBeforeRenderObservable.clear();
  19128. this.onAfterRenderObservable.clear();
  19129. this.detachControl();
  19130. // Release sounds & sounds tracks
  19131. if (BABYLON.AudioEngine) {
  19132. this.disposeSounds();
  19133. }
  19134. // VR Helper
  19135. if (this.VRHelper) {
  19136. this.VRHelper.dispose();
  19137. }
  19138. // Detach cameras
  19139. var canvas = this._engine.getRenderingCanvas();
  19140. var index;
  19141. for (index = 0; index < this.cameras.length; index++) {
  19142. this.cameras[index].detachControl(canvas);
  19143. }
  19144. // Release lights
  19145. while (this.lights.length) {
  19146. this.lights[0].dispose();
  19147. }
  19148. // Release meshes
  19149. while (this.meshes.length) {
  19150. this.meshes[0].dispose(true);
  19151. }
  19152. // Release cameras
  19153. while (this.cameras.length) {
  19154. this.cameras[0].dispose();
  19155. }
  19156. // Release materials
  19157. if (this.defaultMaterial) {
  19158. this.defaultMaterial.dispose();
  19159. }
  19160. while (this.multiMaterials.length) {
  19161. this.multiMaterials[0].dispose();
  19162. }
  19163. while (this.materials.length) {
  19164. this.materials[0].dispose();
  19165. }
  19166. // Release particles
  19167. while (this.particleSystems.length) {
  19168. this.particleSystems[0].dispose();
  19169. }
  19170. // Release sprites
  19171. while (this.spriteManagers.length) {
  19172. this.spriteManagers[0].dispose();
  19173. }
  19174. // Release postProcesses
  19175. while (this.postProcesses.length) {
  19176. this.postProcesses[0].dispose();
  19177. }
  19178. // Release layers
  19179. while (this.layers.length) {
  19180. this.layers[0].dispose();
  19181. }
  19182. while (this.highlightLayers.length) {
  19183. this.highlightLayers[0].dispose();
  19184. }
  19185. // Release textures
  19186. while (this.textures.length) {
  19187. this.textures[0].dispose();
  19188. }
  19189. // Release UBO
  19190. this._sceneUbo.dispose();
  19191. // Post-processes
  19192. this.postProcessManager.dispose();
  19193. if (this._postProcessRenderPipelineManager) {
  19194. this._postProcessRenderPipelineManager.dispose();
  19195. }
  19196. // Physics
  19197. if (this._physicsEngine) {
  19198. this.disablePhysicsEngine();
  19199. }
  19200. // Remove from engine
  19201. index = this._engine.scenes.indexOf(this);
  19202. if (index > -1) {
  19203. this._engine.scenes.splice(index, 1);
  19204. }
  19205. this._engine.wipeCaches();
  19206. this._engine = null;
  19207. this.defaultMaterial = null;
  19208. this.multiMaterials = null;
  19209. this.materials = null;
  19210. };
  19211. Object.defineProperty(Scene.prototype, "isDisposed", {
  19212. get: function () {
  19213. return !this._engine;
  19214. },
  19215. enumerable: true,
  19216. configurable: true
  19217. });
  19218. // Release sounds & sounds tracks
  19219. Scene.prototype.disposeSounds = function () {
  19220. this.mainSoundTrack.dispose();
  19221. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19222. this.soundTracks[scIndex].dispose();
  19223. }
  19224. };
  19225. // Octrees
  19226. Scene.prototype.getWorldExtends = function () {
  19227. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19228. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19229. for (var index = 0; index < this.meshes.length; index++) {
  19230. var mesh = this.meshes[index];
  19231. mesh.computeWorldMatrix(true);
  19232. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19233. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19234. BABYLON.Tools.CheckExtends(minBox, min, max);
  19235. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19236. }
  19237. return {
  19238. min: min,
  19239. max: max
  19240. };
  19241. };
  19242. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19243. if (maxCapacity === void 0) { maxCapacity = 64; }
  19244. if (maxDepth === void 0) { maxDepth = 2; }
  19245. if (!this._selectionOctree) {
  19246. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19247. }
  19248. var worldExtends = this.getWorldExtends();
  19249. // Update octree
  19250. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19251. return this._selectionOctree;
  19252. };
  19253. // Picking
  19254. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19255. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19256. var engine = this._engine;
  19257. if (!camera) {
  19258. if (!this.activeCamera)
  19259. throw new Error("Active camera not set");
  19260. camera = this.activeCamera;
  19261. }
  19262. var cameraViewport = camera.viewport;
  19263. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19264. // Moving coordinates to local viewport world
  19265. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19266. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19267. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19268. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19269. };
  19270. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19271. if (!BABYLON.PickingInfo) {
  19272. return null;
  19273. }
  19274. var engine = this._engine;
  19275. if (!camera) {
  19276. if (!this.activeCamera)
  19277. throw new Error("Active camera not set");
  19278. camera = this.activeCamera;
  19279. }
  19280. var cameraViewport = camera.viewport;
  19281. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19282. var identity = BABYLON.Matrix.Identity();
  19283. // Moving coordinates to local viewport world
  19284. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19285. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19286. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19287. };
  19288. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19289. if (!BABYLON.PickingInfo) {
  19290. return null;
  19291. }
  19292. var pickingInfo = null;
  19293. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19294. var mesh = this.meshes[meshIndex];
  19295. if (predicate) {
  19296. if (!predicate(mesh)) {
  19297. continue;
  19298. }
  19299. }
  19300. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19301. continue;
  19302. }
  19303. var world = mesh.getWorldMatrix();
  19304. var ray = rayFunction(world);
  19305. var result = mesh.intersects(ray, fastCheck);
  19306. if (!result || !result.hit)
  19307. continue;
  19308. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19309. continue;
  19310. pickingInfo = result;
  19311. if (fastCheck) {
  19312. break;
  19313. }
  19314. }
  19315. return pickingInfo || new BABYLON.PickingInfo();
  19316. };
  19317. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19318. if (!BABYLON.PickingInfo) {
  19319. return null;
  19320. }
  19321. var pickingInfos = new Array();
  19322. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19323. var mesh = this.meshes[meshIndex];
  19324. if (predicate) {
  19325. if (!predicate(mesh)) {
  19326. continue;
  19327. }
  19328. }
  19329. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19330. continue;
  19331. }
  19332. var world = mesh.getWorldMatrix();
  19333. var ray = rayFunction(world);
  19334. var result = mesh.intersects(ray, false);
  19335. if (!result || !result.hit)
  19336. continue;
  19337. pickingInfos.push(result);
  19338. }
  19339. return pickingInfos;
  19340. };
  19341. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19342. if (!BABYLON.PickingInfo) {
  19343. return null;
  19344. }
  19345. var pickingInfo = null;
  19346. camera = camera || this.activeCamera;
  19347. if (this.spriteManagers.length > 0) {
  19348. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19349. var spriteManager = this.spriteManagers[spriteIndex];
  19350. if (!spriteManager.isPickable) {
  19351. continue;
  19352. }
  19353. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19354. if (!result || !result.hit)
  19355. continue;
  19356. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19357. continue;
  19358. pickingInfo = result;
  19359. if (fastCheck) {
  19360. break;
  19361. }
  19362. }
  19363. }
  19364. return pickingInfo || new BABYLON.PickingInfo();
  19365. };
  19366. /** Launch a ray to try to pick a mesh in the scene
  19367. * @param x position on screen
  19368. * @param y position on screen
  19369. * @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
  19370. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19371. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19372. */
  19373. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19374. var _this = this;
  19375. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19376. };
  19377. /** Launch a ray to try to pick a sprite in the scene
  19378. * @param x position on screen
  19379. * @param y position on screen
  19380. * @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
  19381. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19382. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19383. */
  19384. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19385. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19386. };
  19387. /** Use the given ray to pick a mesh in the scene
  19388. * @param ray The ray to use to pick meshes
  19389. * @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
  19390. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19391. */
  19392. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19393. var _this = this;
  19394. return this._internalPick(function (world) {
  19395. if (!_this._pickWithRayInverseMatrix) {
  19396. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19397. }
  19398. world.invertToRef(_this._pickWithRayInverseMatrix);
  19399. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19400. }, predicate, fastCheck);
  19401. };
  19402. /**
  19403. * Launch a ray to try to pick a mesh in the scene
  19404. * @param x X position on screen
  19405. * @param y Y position on screen
  19406. * @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
  19407. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19408. */
  19409. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19410. var _this = this;
  19411. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19412. };
  19413. /**
  19414. * Launch a ray to try to pick a mesh in the scene
  19415. * @param ray Ray to use
  19416. * @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
  19417. */
  19418. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19419. var _this = this;
  19420. return this._internalMultiPick(function (world) {
  19421. if (!_this._pickWithRayInverseMatrix) {
  19422. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19423. }
  19424. world.invertToRef(_this._pickWithRayInverseMatrix);
  19425. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19426. }, predicate);
  19427. };
  19428. Scene.prototype.setPointerOverMesh = function (mesh) {
  19429. if (this._pointerOverMesh === mesh) {
  19430. return;
  19431. }
  19432. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19433. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19434. }
  19435. this._pointerOverMesh = mesh;
  19436. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19437. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19438. }
  19439. };
  19440. Scene.prototype.getPointerOverMesh = function () {
  19441. return this._pointerOverMesh;
  19442. };
  19443. Scene.prototype.setPointerOverSprite = function (sprite) {
  19444. if (this._pointerOverSprite === sprite) {
  19445. return;
  19446. }
  19447. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19448. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19449. }
  19450. this._pointerOverSprite = sprite;
  19451. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19452. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19453. }
  19454. };
  19455. Scene.prototype.getPointerOverSprite = function () {
  19456. return this._pointerOverSprite;
  19457. };
  19458. // Physics
  19459. Scene.prototype.getPhysicsEngine = function () {
  19460. return this._physicsEngine;
  19461. };
  19462. /**
  19463. * Enables physics to the current scene
  19464. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19465. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19466. * @return {boolean} was the physics engine initialized
  19467. */
  19468. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19469. if (this._physicsEngine) {
  19470. return true;
  19471. }
  19472. try {
  19473. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19474. return true;
  19475. }
  19476. catch (e) {
  19477. BABYLON.Tools.Error(e.message);
  19478. return false;
  19479. }
  19480. };
  19481. Scene.prototype.disablePhysicsEngine = function () {
  19482. if (!this._physicsEngine) {
  19483. return;
  19484. }
  19485. this._physicsEngine.dispose();
  19486. this._physicsEngine = undefined;
  19487. };
  19488. Scene.prototype.isPhysicsEnabled = function () {
  19489. return this._physicsEngine !== undefined;
  19490. };
  19491. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19492. var mesh = compound.parts[0].mesh;
  19493. mesh.physicsImpostor.dispose();
  19494. mesh.physicsImpostor = null;
  19495. };
  19496. // Misc.
  19497. Scene.prototype._rebuildGeometries = function () {
  19498. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19499. var geometry = _a[_i];
  19500. geometry._rebuild();
  19501. }
  19502. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19503. var mesh = _c[_b];
  19504. mesh._rebuild();
  19505. }
  19506. if (this.postProcessManager) {
  19507. this.postProcessManager._rebuild();
  19508. }
  19509. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19510. var layer = _e[_d];
  19511. layer._rebuild();
  19512. }
  19513. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19514. var highlightLayer = _g[_f];
  19515. highlightLayer._rebuild();
  19516. }
  19517. if (this._boundingBoxRenderer) {
  19518. this._boundingBoxRenderer._rebuild();
  19519. }
  19520. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19521. var system = _j[_h];
  19522. system.rebuild();
  19523. }
  19524. if (this._postProcessRenderPipelineManager) {
  19525. this._postProcessRenderPipelineManager._rebuild();
  19526. }
  19527. };
  19528. Scene.prototype._rebuildTextures = function () {
  19529. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19530. var texture = _a[_i];
  19531. texture._rebuild();
  19532. }
  19533. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19534. };
  19535. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19536. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19537. if (replace === void 0) { replace = false; }
  19538. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19539. // Dispose existing camera or light in replace mode.
  19540. if (replace) {
  19541. if (this.activeCamera) {
  19542. this.activeCamera.dispose();
  19543. this.activeCamera = null;
  19544. }
  19545. if (this.lights) {
  19546. for (var i = 0; i < this.lights.length; i++) {
  19547. this.lights[i].dispose();
  19548. }
  19549. }
  19550. }
  19551. // Light
  19552. if (this.lights.length === 0) {
  19553. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19554. }
  19555. // Camera
  19556. if (!this.activeCamera) {
  19557. var worldExtends = this.getWorldExtends();
  19558. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19559. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19560. var camera;
  19561. var radius = worldSize.length() * 1.5;
  19562. if (createArcRotateCamera) {
  19563. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19564. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19565. arcRotateCamera.wheelPrecision = 100 / radius;
  19566. camera = arcRotateCamera;
  19567. }
  19568. else {
  19569. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19570. freeCamera.setTarget(worldCenter);
  19571. camera = freeCamera;
  19572. }
  19573. camera.minZ = radius * 0.01;
  19574. camera.maxZ = radius * 100;
  19575. camera.speed = radius * 0.2;
  19576. this.activeCamera = camera;
  19577. if (attachCameraControls) {
  19578. camera.attachControl(this.getEngine().getRenderingCanvas());
  19579. }
  19580. }
  19581. };
  19582. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19583. if (pbr === void 0) { pbr = false; }
  19584. if (scale === void 0) { scale = 1000; }
  19585. if (blur === void 0) { blur = 0; }
  19586. if (environmentTexture) {
  19587. this.environmentTexture = environmentTexture;
  19588. }
  19589. if (!this.environmentTexture) {
  19590. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19591. return;
  19592. }
  19593. // Skybox
  19594. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19595. if (pbr) {
  19596. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19597. hdrSkyboxMaterial.backFaceCulling = false;
  19598. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19599. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19600. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19601. hdrSkyboxMaterial.disableLighting = true;
  19602. hdrSkyboxMaterial.twoSidedLighting = true;
  19603. hdrSkybox.infiniteDistance = true;
  19604. hdrSkybox.material = hdrSkyboxMaterial;
  19605. }
  19606. else {
  19607. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19608. skyboxMaterial.backFaceCulling = false;
  19609. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19610. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19611. skyboxMaterial.disableLighting = true;
  19612. hdrSkybox.infiniteDistance = true;
  19613. hdrSkybox.material = skyboxMaterial;
  19614. }
  19615. return hdrSkybox;
  19616. };
  19617. Scene.prototype.createDefaultVRExperience = function () {
  19618. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19619. };
  19620. // Tags
  19621. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19622. if (tagsQuery === undefined) {
  19623. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19624. return list;
  19625. }
  19626. var listByTags = [];
  19627. forEach = forEach || (function (item) { return; });
  19628. for (var i in list) {
  19629. var item = list[i];
  19630. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19631. listByTags.push(item);
  19632. forEach(item);
  19633. }
  19634. }
  19635. return listByTags;
  19636. };
  19637. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19638. return this._getByTags(this.meshes, tagsQuery, forEach);
  19639. };
  19640. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19641. return this._getByTags(this.cameras, tagsQuery, forEach);
  19642. };
  19643. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19644. return this._getByTags(this.lights, tagsQuery, forEach);
  19645. };
  19646. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19647. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19648. };
  19649. /**
  19650. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19651. * This allowed control for front to back rendering or reversly depending of the special needs.
  19652. *
  19653. * @param renderingGroupId The rendering group id corresponding to its index
  19654. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19655. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19656. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19657. */
  19658. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19659. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19660. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19661. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19662. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19663. };
  19664. /**
  19665. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19666. *
  19667. * @param renderingGroupId The rendering group id corresponding to its index
  19668. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19669. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19670. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19671. */
  19672. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19673. if (depth === void 0) { depth = true; }
  19674. if (stencil === void 0) { stencil = true; }
  19675. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19676. };
  19677. /**
  19678. * Will flag all materials as dirty to trigger new shader compilation
  19679. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19680. */
  19681. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19682. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19683. var material = _a[_i];
  19684. if (predicate && !predicate(material)) {
  19685. continue;
  19686. }
  19687. material.markAsDirty(flag);
  19688. }
  19689. };
  19690. // Statics
  19691. Scene._FOGMODE_NONE = 0;
  19692. Scene._FOGMODE_EXP = 1;
  19693. Scene._FOGMODE_EXP2 = 2;
  19694. Scene._FOGMODE_LINEAR = 3;
  19695. Scene.MinDeltaTime = 1.0;
  19696. Scene.MaxDeltaTime = 1000.0;
  19697. /** The distance in pixel that you have to move to prevent some events */
  19698. Scene.DragMovementThreshold = 10; // in pixels
  19699. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19700. Scene.LongPressDelay = 500; // in milliseconds
  19701. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19702. Scene.DoubleClickDelay = 300; // in milliseconds
  19703. /** If you need to check double click without raising a single click at first click, enable this flag */
  19704. Scene.ExclusiveDoubleClickMode = false;
  19705. return Scene;
  19706. }());
  19707. BABYLON.Scene = Scene;
  19708. })(BABYLON || (BABYLON = {}));
  19709. //# sourceMappingURL=babylon.scene.js.map
  19710. var BABYLON;
  19711. (function (BABYLON) {
  19712. var Buffer = (function () {
  19713. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19714. if (engine instanceof BABYLON.Mesh) {
  19715. this._engine = engine.getScene().getEngine();
  19716. }
  19717. else {
  19718. this._engine = engine;
  19719. }
  19720. this._updatable = updatable;
  19721. this._data = data;
  19722. this._strideSize = stride;
  19723. if (!postponeInternalCreation) {
  19724. this.create();
  19725. }
  19726. this._instanced = instanced;
  19727. this._instanceDivisor = instanced ? 1 : 0;
  19728. }
  19729. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19730. // a lot of these parameters are ignored as they are overriden by the buffer
  19731. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19732. };
  19733. // Properties
  19734. Buffer.prototype.isUpdatable = function () {
  19735. return this._updatable;
  19736. };
  19737. Buffer.prototype.getData = function () {
  19738. return this._data;
  19739. };
  19740. Buffer.prototype.getBuffer = function () {
  19741. return this._buffer;
  19742. };
  19743. Buffer.prototype.getStrideSize = function () {
  19744. return this._strideSize;
  19745. };
  19746. Buffer.prototype.getIsInstanced = function () {
  19747. return this._instanced;
  19748. };
  19749. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19750. get: function () {
  19751. return this._instanceDivisor;
  19752. },
  19753. set: function (value) {
  19754. this._instanceDivisor = value;
  19755. if (value == 0) {
  19756. this._instanced = false;
  19757. }
  19758. else {
  19759. this._instanced = true;
  19760. }
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. // Methods
  19766. Buffer.prototype.create = function (data) {
  19767. if (!data && this._buffer) {
  19768. return; // nothing to do
  19769. }
  19770. data = data || this._data;
  19771. if (!this._buffer) {
  19772. if (this._updatable) {
  19773. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19774. this._data = data;
  19775. }
  19776. else {
  19777. this._buffer = this._engine.createVertexBuffer(data);
  19778. }
  19779. }
  19780. else if (this._updatable) {
  19781. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19782. this._data = data;
  19783. }
  19784. };
  19785. Buffer.prototype._rebuild = function () {
  19786. this._buffer = null;
  19787. this.create(this._data);
  19788. };
  19789. Buffer.prototype.update = function (data) {
  19790. this.create(data);
  19791. };
  19792. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19793. if (!this._buffer) {
  19794. return;
  19795. }
  19796. if (this._updatable) {
  19797. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19798. this._data = null;
  19799. }
  19800. };
  19801. Buffer.prototype.dispose = function () {
  19802. if (!this._buffer) {
  19803. return;
  19804. }
  19805. if (this._engine._releaseBuffer(this._buffer)) {
  19806. this._buffer = null;
  19807. }
  19808. };
  19809. return Buffer;
  19810. }());
  19811. BABYLON.Buffer = Buffer;
  19812. })(BABYLON || (BABYLON = {}));
  19813. //# sourceMappingURL=babylon.buffer.js.map
  19814. var BABYLON;
  19815. (function (BABYLON) {
  19816. var VertexBuffer = (function () {
  19817. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19818. if (!stride) {
  19819. // Deduce stride from kind
  19820. switch (kind) {
  19821. case VertexBuffer.PositionKind:
  19822. stride = 3;
  19823. break;
  19824. case VertexBuffer.NormalKind:
  19825. stride = 3;
  19826. break;
  19827. case VertexBuffer.UVKind:
  19828. case VertexBuffer.UV2Kind:
  19829. case VertexBuffer.UV3Kind:
  19830. case VertexBuffer.UV4Kind:
  19831. case VertexBuffer.UV5Kind:
  19832. case VertexBuffer.UV6Kind:
  19833. stride = 2;
  19834. break;
  19835. case VertexBuffer.TangentKind:
  19836. case VertexBuffer.ColorKind:
  19837. stride = 4;
  19838. break;
  19839. case VertexBuffer.MatricesIndicesKind:
  19840. case VertexBuffer.MatricesIndicesExtraKind:
  19841. stride = 4;
  19842. break;
  19843. case VertexBuffer.MatricesWeightsKind:
  19844. case VertexBuffer.MatricesWeightsExtraKind:
  19845. stride = 4;
  19846. break;
  19847. }
  19848. }
  19849. if (data instanceof BABYLON.Buffer) {
  19850. if (!stride) {
  19851. stride = data.getStrideSize();
  19852. }
  19853. this._buffer = data;
  19854. this._ownsBuffer = false;
  19855. }
  19856. else {
  19857. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19858. this._ownsBuffer = true;
  19859. }
  19860. this._stride = stride;
  19861. this._offset = offset ? offset : 0;
  19862. this._size = size ? size : stride;
  19863. this._kind = kind;
  19864. }
  19865. VertexBuffer.prototype._rebuild = function () {
  19866. if (!this._buffer) {
  19867. return;
  19868. }
  19869. this._buffer._rebuild();
  19870. };
  19871. /**
  19872. * Returns the kind of the VertexBuffer (string).
  19873. */
  19874. VertexBuffer.prototype.getKind = function () {
  19875. return this._kind;
  19876. };
  19877. // Properties
  19878. /**
  19879. * Boolean : is the VertexBuffer updatable ?
  19880. */
  19881. VertexBuffer.prototype.isUpdatable = function () {
  19882. return this._buffer.isUpdatable();
  19883. };
  19884. /**
  19885. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19886. */
  19887. VertexBuffer.prototype.getData = function () {
  19888. return this._buffer.getData();
  19889. };
  19890. /**
  19891. * Returns the WebGLBuffer associated to the VertexBuffer.
  19892. */
  19893. VertexBuffer.prototype.getBuffer = function () {
  19894. return this._buffer.getBuffer();
  19895. };
  19896. /**
  19897. * Returns the stride of the VertexBuffer (integer).
  19898. */
  19899. VertexBuffer.prototype.getStrideSize = function () {
  19900. return this._stride;
  19901. };
  19902. /**
  19903. * Returns the offset (integer).
  19904. */
  19905. VertexBuffer.prototype.getOffset = function () {
  19906. return this._offset;
  19907. };
  19908. /**
  19909. * Returns the VertexBuffer total size (integer).
  19910. */
  19911. VertexBuffer.prototype.getSize = function () {
  19912. return this._size;
  19913. };
  19914. /**
  19915. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19916. */
  19917. VertexBuffer.prototype.getIsInstanced = function () {
  19918. return this._buffer.getIsInstanced();
  19919. };
  19920. /**
  19921. * Returns the instancing divisor, zero for non-instanced (integer).
  19922. */
  19923. VertexBuffer.prototype.getInstanceDivisor = function () {
  19924. return this._buffer.instanceDivisor;
  19925. };
  19926. // Methods
  19927. /**
  19928. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19929. * Returns the created WebGLBuffer.
  19930. */
  19931. VertexBuffer.prototype.create = function (data) {
  19932. return this._buffer.create(data);
  19933. };
  19934. /**
  19935. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19936. * Returns the updated WebGLBuffer.
  19937. */
  19938. VertexBuffer.prototype.update = function (data) {
  19939. return this._buffer.update(data);
  19940. };
  19941. /**
  19942. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19943. * Returns the directly updated WebGLBuffer.
  19944. */
  19945. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19946. return this._buffer.updateDirectly(data, offset);
  19947. };
  19948. /**
  19949. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19950. */
  19951. VertexBuffer.prototype.dispose = function () {
  19952. if (this._ownsBuffer) {
  19953. this._buffer.dispose();
  19954. }
  19955. };
  19956. Object.defineProperty(VertexBuffer, "PositionKind", {
  19957. get: function () {
  19958. return VertexBuffer._PositionKind;
  19959. },
  19960. enumerable: true,
  19961. configurable: true
  19962. });
  19963. Object.defineProperty(VertexBuffer, "NormalKind", {
  19964. get: function () {
  19965. return VertexBuffer._NormalKind;
  19966. },
  19967. enumerable: true,
  19968. configurable: true
  19969. });
  19970. Object.defineProperty(VertexBuffer, "TangentKind", {
  19971. get: function () {
  19972. return VertexBuffer._TangentKind;
  19973. },
  19974. enumerable: true,
  19975. configurable: true
  19976. });
  19977. Object.defineProperty(VertexBuffer, "UVKind", {
  19978. get: function () {
  19979. return VertexBuffer._UVKind;
  19980. },
  19981. enumerable: true,
  19982. configurable: true
  19983. });
  19984. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19985. get: function () {
  19986. return VertexBuffer._UV2Kind;
  19987. },
  19988. enumerable: true,
  19989. configurable: true
  19990. });
  19991. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19992. get: function () {
  19993. return VertexBuffer._UV3Kind;
  19994. },
  19995. enumerable: true,
  19996. configurable: true
  19997. });
  19998. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19999. get: function () {
  20000. return VertexBuffer._UV4Kind;
  20001. },
  20002. enumerable: true,
  20003. configurable: true
  20004. });
  20005. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20006. get: function () {
  20007. return VertexBuffer._UV5Kind;
  20008. },
  20009. enumerable: true,
  20010. configurable: true
  20011. });
  20012. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20013. get: function () {
  20014. return VertexBuffer._UV6Kind;
  20015. },
  20016. enumerable: true,
  20017. configurable: true
  20018. });
  20019. Object.defineProperty(VertexBuffer, "ColorKind", {
  20020. get: function () {
  20021. return VertexBuffer._ColorKind;
  20022. },
  20023. enumerable: true,
  20024. configurable: true
  20025. });
  20026. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20027. get: function () {
  20028. return VertexBuffer._MatricesIndicesKind;
  20029. },
  20030. enumerable: true,
  20031. configurable: true
  20032. });
  20033. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20034. get: function () {
  20035. return VertexBuffer._MatricesWeightsKind;
  20036. },
  20037. enumerable: true,
  20038. configurable: true
  20039. });
  20040. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20041. get: function () {
  20042. return VertexBuffer._MatricesIndicesExtraKind;
  20043. },
  20044. enumerable: true,
  20045. configurable: true
  20046. });
  20047. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20048. get: function () {
  20049. return VertexBuffer._MatricesWeightsExtraKind;
  20050. },
  20051. enumerable: true,
  20052. configurable: true
  20053. });
  20054. // Enums
  20055. VertexBuffer._PositionKind = "position";
  20056. VertexBuffer._NormalKind = "normal";
  20057. VertexBuffer._TangentKind = "tangent";
  20058. VertexBuffer._UVKind = "uv";
  20059. VertexBuffer._UV2Kind = "uv2";
  20060. VertexBuffer._UV3Kind = "uv3";
  20061. VertexBuffer._UV4Kind = "uv4";
  20062. VertexBuffer._UV5Kind = "uv5";
  20063. VertexBuffer._UV6Kind = "uv6";
  20064. VertexBuffer._ColorKind = "color";
  20065. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20066. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20067. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20068. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20069. return VertexBuffer;
  20070. }());
  20071. BABYLON.VertexBuffer = VertexBuffer;
  20072. })(BABYLON || (BABYLON = {}));
  20073. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20074. var BABYLON;
  20075. (function (BABYLON) {
  20076. var InternalTexture = (function () {
  20077. function InternalTexture(engine, dataSource) {
  20078. this.onLoadedObservable = new BABYLON.Observable();
  20079. // Private
  20080. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20081. this._references = 1;
  20082. this._engine = engine;
  20083. this._dataSource = dataSource;
  20084. this._webGLTexture = engine._createTexture();
  20085. }
  20086. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20087. get: function () {
  20088. return this._dataSource;
  20089. },
  20090. enumerable: true,
  20091. configurable: true
  20092. });
  20093. InternalTexture.prototype.incrementReferences = function () {
  20094. this._references++;
  20095. };
  20096. InternalTexture.prototype.updateSize = function (width, height) {
  20097. this.width = width;
  20098. this.height = height;
  20099. this._size = width * height;
  20100. this.baseWidth = width;
  20101. this.baseHeight = height;
  20102. };
  20103. InternalTexture.prototype._rebuild = function () {
  20104. var _this = this;
  20105. var proxy;
  20106. this.isReady = false;
  20107. this._cachedCoordinatesMode = null;
  20108. this._cachedWrapU = null;
  20109. this._cachedWrapV = null;
  20110. this._cachedAnisotropicFilteringLevel = null;
  20111. switch (this._dataSource) {
  20112. case InternalTexture.DATASOURCE_TEMP:
  20113. return;
  20114. case InternalTexture.DATASOURCE_URL:
  20115. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20116. _this.isReady = true;
  20117. }, null, this._buffer, null, this.format);
  20118. proxy._swapAndDie(this);
  20119. return;
  20120. case InternalTexture.DATASOURCE_RAW:
  20121. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20122. proxy._swapAndDie(this);
  20123. this.isReady = true;
  20124. return;
  20125. case InternalTexture.DATASOURCE_DYNAMIC:
  20126. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20127. proxy._swapAndDie(this);
  20128. // The engine will make sure to update content so no need to flag it as isReady = true
  20129. return;
  20130. case InternalTexture.DATASOURCE_RENDERTARGET:
  20131. var options = new BABYLON.RenderTargetCreationOptions();
  20132. options.generateDepthBuffer = this._generateDepthBuffer;
  20133. options.generateMipMaps = this.generateMipMaps;
  20134. options.generateStencilBuffer = this._generateStencilBuffer;
  20135. options.samplingMode = this.samplingMode;
  20136. options.type = this.type;
  20137. if (this.isCube) {
  20138. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20139. }
  20140. else {
  20141. var size = {
  20142. width: this.width,
  20143. height: this.height
  20144. };
  20145. proxy = this._engine.createRenderTargetTexture(size, options);
  20146. }
  20147. proxy._swapAndDie(this);
  20148. this.isReady = true;
  20149. return;
  20150. case InternalTexture.DATASOURCE_CUBE:
  20151. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20152. _this.isReady = true;
  20153. }, null, this.format, this._extension);
  20154. proxy._swapAndDie(this);
  20155. return;
  20156. case InternalTexture.DATASOURCE_CUBERAW:
  20157. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20158. proxy._swapAndDie(this);
  20159. this.isReady = true;
  20160. return;
  20161. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20162. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20163. proxy._swapAndDie(_this);
  20164. _this.isReady = true;
  20165. }, null, this.format, this._extension);
  20166. return;
  20167. }
  20168. };
  20169. InternalTexture.prototype._swapAndDie = function (target) {
  20170. target._webGLTexture = this._webGLTexture;
  20171. if (this._framebuffer) {
  20172. target._framebuffer = this._framebuffer;
  20173. }
  20174. if (this._depthStencilBuffer) {
  20175. target._depthStencilBuffer = this._depthStencilBuffer;
  20176. }
  20177. if (this._lodTextureHigh) {
  20178. if (target._lodTextureHigh) {
  20179. target._lodTextureHigh.dispose();
  20180. }
  20181. target._lodTextureHigh = this._lodTextureHigh;
  20182. }
  20183. if (this._lodTextureMid) {
  20184. if (target._lodTextureMid) {
  20185. target._lodTextureMid.dispose();
  20186. }
  20187. target._lodTextureMid = this._lodTextureMid;
  20188. }
  20189. if (this._lodTextureLow) {
  20190. if (target._lodTextureLow) {
  20191. target._lodTextureLow.dispose();
  20192. }
  20193. target._lodTextureLow = this._lodTextureLow;
  20194. }
  20195. var cache = this._engine.getLoadedTexturesCache();
  20196. var index = cache.indexOf(this);
  20197. if (index !== -1) {
  20198. cache.splice(index, 1);
  20199. }
  20200. };
  20201. InternalTexture.prototype.dispose = function () {
  20202. if (!this._webGLTexture) {
  20203. return;
  20204. }
  20205. this._references--;
  20206. if (this._references === 0) {
  20207. this._engine._releaseTexture(this);
  20208. this._webGLTexture = null;
  20209. }
  20210. };
  20211. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20212. InternalTexture.DATASOURCE_URL = 1;
  20213. InternalTexture.DATASOURCE_TEMP = 2;
  20214. InternalTexture.DATASOURCE_RAW = 3;
  20215. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20216. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20217. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20218. InternalTexture.DATASOURCE_CUBE = 7;
  20219. InternalTexture.DATASOURCE_CUBERAW = 8;
  20220. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20221. return InternalTexture;
  20222. }());
  20223. BABYLON.InternalTexture = InternalTexture;
  20224. })(BABYLON || (BABYLON = {}));
  20225. //# sourceMappingURL=babylon.internalTexture.js.map
  20226. var BABYLON;
  20227. (function (BABYLON) {
  20228. var BaseTexture = (function () {
  20229. function BaseTexture(scene) {
  20230. this._hasAlpha = false;
  20231. this.getAlphaFromRGB = false;
  20232. this.level = 1;
  20233. this.coordinatesIndex = 0;
  20234. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20235. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20236. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20237. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20238. this.isCube = false;
  20239. this.gammaSpace = true;
  20240. this.invertZ = false;
  20241. this.lodLevelInAlpha = false;
  20242. this.lodGenerationOffset = 0.0;
  20243. this.lodGenerationScale = 0.8;
  20244. this.isRenderTarget = false;
  20245. this.animations = new Array();
  20246. /**
  20247. * An event triggered when the texture is disposed.
  20248. * @type {BABYLON.Observable}
  20249. */
  20250. this.onDisposeObservable = new BABYLON.Observable();
  20251. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20252. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20253. this._scene.textures.push(this);
  20254. this._uid = null;
  20255. }
  20256. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20257. get: function () {
  20258. return this._hasAlpha;
  20259. },
  20260. set: function (value) {
  20261. if (this._hasAlpha === value) {
  20262. return;
  20263. }
  20264. this._hasAlpha = value;
  20265. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20266. },
  20267. enumerable: true,
  20268. configurable: true
  20269. });
  20270. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20271. get: function () {
  20272. return this._coordinatesMode;
  20273. },
  20274. set: function (value) {
  20275. if (this._coordinatesMode === value) {
  20276. return;
  20277. }
  20278. this._coordinatesMode = value;
  20279. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20280. },
  20281. enumerable: true,
  20282. configurable: true
  20283. });
  20284. Object.defineProperty(BaseTexture.prototype, "uid", {
  20285. get: function () {
  20286. if (!this._uid) {
  20287. this._uid = BABYLON.Tools.RandomId();
  20288. }
  20289. return this._uid;
  20290. },
  20291. enumerable: true,
  20292. configurable: true
  20293. });
  20294. BaseTexture.prototype.toString = function () {
  20295. return this.name;
  20296. };
  20297. BaseTexture.prototype.getClassName = function () {
  20298. return "BaseTexture";
  20299. };
  20300. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20301. set: function (callback) {
  20302. if (this._onDisposeObserver) {
  20303. this.onDisposeObservable.remove(this._onDisposeObserver);
  20304. }
  20305. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20306. },
  20307. enumerable: true,
  20308. configurable: true
  20309. });
  20310. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20311. get: function () {
  20312. return true;
  20313. },
  20314. enumerable: true,
  20315. configurable: true
  20316. });
  20317. BaseTexture.prototype.getScene = function () {
  20318. return this._scene;
  20319. };
  20320. BaseTexture.prototype.getTextureMatrix = function () {
  20321. return null;
  20322. };
  20323. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20324. return null;
  20325. };
  20326. BaseTexture.prototype.getInternalTexture = function () {
  20327. return this._texture;
  20328. };
  20329. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20330. return !this.isBlocking || this.isReady();
  20331. };
  20332. BaseTexture.prototype.isReady = function () {
  20333. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20334. this.delayLoad();
  20335. return false;
  20336. }
  20337. if (this._texture) {
  20338. return this._texture.isReady;
  20339. }
  20340. return false;
  20341. };
  20342. BaseTexture.prototype.getSize = function () {
  20343. if (this._texture.width) {
  20344. return new BABYLON.Size(this._texture.width, this._texture.height);
  20345. }
  20346. if (this._texture._size) {
  20347. return new BABYLON.Size(this._texture._size, this._texture._size);
  20348. }
  20349. return BABYLON.Size.Zero();
  20350. };
  20351. BaseTexture.prototype.getBaseSize = function () {
  20352. if (!this.isReady() || !this._texture)
  20353. return BABYLON.Size.Zero();
  20354. if (this._texture._size) {
  20355. return new BABYLON.Size(this._texture._size, this._texture._size);
  20356. }
  20357. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20358. };
  20359. BaseTexture.prototype.scale = function (ratio) {
  20360. };
  20361. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20362. get: function () {
  20363. return false;
  20364. },
  20365. enumerable: true,
  20366. configurable: true
  20367. });
  20368. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20369. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20370. for (var index = 0; index < texturesCache.length; index++) {
  20371. var texturesCacheEntry = texturesCache[index];
  20372. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20373. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20374. texturesCacheEntry.incrementReferences();
  20375. return texturesCacheEntry;
  20376. }
  20377. }
  20378. }
  20379. return null;
  20380. };
  20381. BaseTexture.prototype._rebuild = function () {
  20382. };
  20383. BaseTexture.prototype.delayLoad = function () {
  20384. };
  20385. BaseTexture.prototype.clone = function () {
  20386. return null;
  20387. };
  20388. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20389. get: function () {
  20390. if (!this._texture) {
  20391. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20392. }
  20393. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20394. },
  20395. enumerable: true,
  20396. configurable: true
  20397. });
  20398. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20399. get: function () {
  20400. if (!this._texture) {
  20401. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20402. }
  20403. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20404. },
  20405. enumerable: true,
  20406. configurable: true
  20407. });
  20408. BaseTexture.prototype.readPixels = function (faceIndex) {
  20409. if (faceIndex === void 0) { faceIndex = 0; }
  20410. if (!this._texture) {
  20411. return null;
  20412. }
  20413. var size = this.getSize();
  20414. var engine = this.getScene().getEngine();
  20415. if (this._texture.isCube) {
  20416. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20417. }
  20418. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20419. };
  20420. BaseTexture.prototype.releaseInternalTexture = function () {
  20421. if (this._texture) {
  20422. this._texture.dispose();
  20423. this._texture = null;
  20424. }
  20425. };
  20426. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20427. get: function () {
  20428. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20429. return null;
  20430. }
  20431. if (!this._texture._sphericalPolynomial) {
  20432. this._texture._sphericalPolynomial =
  20433. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20434. }
  20435. return this._texture._sphericalPolynomial;
  20436. },
  20437. set: function (value) {
  20438. if (this._texture) {
  20439. this._texture._sphericalPolynomial = value;
  20440. }
  20441. },
  20442. enumerable: true,
  20443. configurable: true
  20444. });
  20445. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20446. get: function () {
  20447. if (this._texture) {
  20448. return this._texture._lodTextureHigh;
  20449. }
  20450. return null;
  20451. },
  20452. enumerable: true,
  20453. configurable: true
  20454. });
  20455. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20456. get: function () {
  20457. if (this._texture) {
  20458. return this._texture._lodTextureMid;
  20459. }
  20460. return null;
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20466. get: function () {
  20467. if (this._texture) {
  20468. return this._texture._lodTextureLow;
  20469. }
  20470. return null;
  20471. },
  20472. enumerable: true,
  20473. configurable: true
  20474. });
  20475. BaseTexture.prototype.dispose = function () {
  20476. // Animations
  20477. this.getScene().stopAnimation(this);
  20478. // Remove from scene
  20479. this._scene._removePendingData(this);
  20480. var index = this._scene.textures.indexOf(this);
  20481. if (index >= 0) {
  20482. this._scene.textures.splice(index, 1);
  20483. }
  20484. if (this._texture === undefined) {
  20485. return;
  20486. }
  20487. // Release
  20488. this.releaseInternalTexture();
  20489. // Callback
  20490. this.onDisposeObservable.notifyObservers(this);
  20491. this.onDisposeObservable.clear();
  20492. };
  20493. BaseTexture.prototype.serialize = function () {
  20494. if (!this.name) {
  20495. return null;
  20496. }
  20497. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20498. // Animations
  20499. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20500. return serializationObject;
  20501. };
  20502. BaseTexture.WhenAllReady = function (textures, callback) {
  20503. var numRemaining = textures.length;
  20504. if (numRemaining === 0) {
  20505. callback();
  20506. return;
  20507. }
  20508. var _loop_1 = function () {
  20509. texture = textures[i];
  20510. if (texture.isReady()) {
  20511. if (--numRemaining === 0) {
  20512. callback();
  20513. }
  20514. }
  20515. else {
  20516. onLoadObservable = texture.onLoadObservable;
  20517. var onLoadCallback_1 = function () {
  20518. onLoadObservable.removeCallback(onLoadCallback_1);
  20519. if (--numRemaining === 0) {
  20520. callback();
  20521. }
  20522. };
  20523. onLoadObservable.add(onLoadCallback_1);
  20524. }
  20525. };
  20526. var texture, onLoadObservable;
  20527. for (var i = 0; i < textures.length; i++) {
  20528. _loop_1();
  20529. }
  20530. };
  20531. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20532. __decorate([
  20533. BABYLON.serialize()
  20534. ], BaseTexture.prototype, "name", void 0);
  20535. __decorate([
  20536. BABYLON.serialize("hasAlpha")
  20537. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20538. __decorate([
  20539. BABYLON.serialize()
  20540. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20541. __decorate([
  20542. BABYLON.serialize()
  20543. ], BaseTexture.prototype, "level", void 0);
  20544. __decorate([
  20545. BABYLON.serialize()
  20546. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20547. __decorate([
  20548. BABYLON.serialize("coordinatesMode")
  20549. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20550. __decorate([
  20551. BABYLON.serialize()
  20552. ], BaseTexture.prototype, "wrapU", void 0);
  20553. __decorate([
  20554. BABYLON.serialize()
  20555. ], BaseTexture.prototype, "wrapV", void 0);
  20556. __decorate([
  20557. BABYLON.serialize()
  20558. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20559. __decorate([
  20560. BABYLON.serialize()
  20561. ], BaseTexture.prototype, "isCube", void 0);
  20562. __decorate([
  20563. BABYLON.serialize()
  20564. ], BaseTexture.prototype, "gammaSpace", void 0);
  20565. __decorate([
  20566. BABYLON.serialize()
  20567. ], BaseTexture.prototype, "invertZ", void 0);
  20568. __decorate([
  20569. BABYLON.serialize()
  20570. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20571. __decorate([
  20572. BABYLON.serialize()
  20573. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20574. __decorate([
  20575. BABYLON.serialize()
  20576. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20577. __decorate([
  20578. BABYLON.serialize()
  20579. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20580. return BaseTexture;
  20581. }());
  20582. BABYLON.BaseTexture = BaseTexture;
  20583. })(BABYLON || (BABYLON = {}));
  20584. //# sourceMappingURL=babylon.baseTexture.js.map
  20585. var BABYLON;
  20586. (function (BABYLON) {
  20587. var Texture = (function (_super) {
  20588. __extends(Texture, _super);
  20589. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20590. if (noMipmap === void 0) { noMipmap = false; }
  20591. if (invertY === void 0) { invertY = true; }
  20592. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20593. if (onLoad === void 0) { onLoad = null; }
  20594. if (onError === void 0) { onError = null; }
  20595. if (buffer === void 0) { buffer = null; }
  20596. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20597. var _this = _super.call(this, scene) || this;
  20598. _this.uOffset = 0;
  20599. _this.vOffset = 0;
  20600. _this.uScale = 1.0;
  20601. _this.vScale = 1.0;
  20602. _this.uAng = 0;
  20603. _this.vAng = 0;
  20604. _this.wAng = 0;
  20605. _this._isBlocking = true;
  20606. _this.name = url;
  20607. _this.url = url;
  20608. _this._noMipmap = noMipmap;
  20609. _this._invertY = invertY;
  20610. _this._samplingMode = samplingMode;
  20611. _this._buffer = buffer;
  20612. _this._deleteBuffer = deleteBuffer;
  20613. _this._format = format;
  20614. scene = _this.getScene();
  20615. var load = function () {
  20616. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20617. _this.onLoadObservable.notifyObservers(_this);
  20618. }
  20619. if (onLoad) {
  20620. onLoad();
  20621. }
  20622. if (!_this.isBlocking) {
  20623. scene.resetCachedMaterial();
  20624. }
  20625. };
  20626. if (!url) {
  20627. _this._delayedOnLoad = load;
  20628. _this._delayedOnError = onError;
  20629. return _this;
  20630. }
  20631. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20632. if (!_this._texture) {
  20633. if (!scene.useDelayedTextureLoading) {
  20634. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20635. if (deleteBuffer) {
  20636. delete _this._buffer;
  20637. }
  20638. }
  20639. else {
  20640. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20641. _this._delayedOnLoad = load;
  20642. _this._delayedOnError = onError;
  20643. }
  20644. }
  20645. else {
  20646. if (_this._texture.isReady) {
  20647. BABYLON.Tools.SetImmediate(function () { return load(); });
  20648. }
  20649. else {
  20650. _this._texture.onLoadedObservable.add(load);
  20651. }
  20652. }
  20653. return _this;
  20654. }
  20655. Object.defineProperty(Texture.prototype, "noMipmap", {
  20656. get: function () {
  20657. return this._noMipmap;
  20658. },
  20659. enumerable: true,
  20660. configurable: true
  20661. });
  20662. Object.defineProperty(Texture.prototype, "isBlocking", {
  20663. get: function () {
  20664. return this._isBlocking;
  20665. },
  20666. set: function (value) {
  20667. this._isBlocking = value;
  20668. },
  20669. enumerable: true,
  20670. configurable: true
  20671. });
  20672. Object.defineProperty(Texture.prototype, "samplingMode", {
  20673. get: function () {
  20674. return this._samplingMode;
  20675. },
  20676. enumerable: true,
  20677. configurable: true
  20678. });
  20679. Texture.prototype.updateURL = function (url) {
  20680. this.url = url;
  20681. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20682. this.delayLoad();
  20683. };
  20684. Texture.prototype.delayLoad = function () {
  20685. var _this = this;
  20686. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20687. return;
  20688. }
  20689. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20690. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20691. if (!this._texture) {
  20692. 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);
  20693. if (this._deleteBuffer) {
  20694. delete this._buffer;
  20695. }
  20696. }
  20697. else {
  20698. if (this._texture.isReady) {
  20699. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20700. }
  20701. else {
  20702. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20703. }
  20704. }
  20705. };
  20706. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20707. if (!this._texture) {
  20708. return;
  20709. }
  20710. this._samplingMode = samplingMode;
  20711. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20712. };
  20713. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20714. x *= this.uScale;
  20715. y *= this.vScale;
  20716. x -= 0.5 * this.uScale;
  20717. y -= 0.5 * this.vScale;
  20718. z -= 0.5;
  20719. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20720. t.x += 0.5 * this.uScale + this.uOffset;
  20721. t.y += 0.5 * this.vScale + this.vOffset;
  20722. t.z += 0.5;
  20723. };
  20724. Texture.prototype.getTextureMatrix = function () {
  20725. var _this = this;
  20726. if (this.uOffset === this._cachedUOffset &&
  20727. this.vOffset === this._cachedVOffset &&
  20728. this.uScale === this._cachedUScale &&
  20729. this.vScale === this._cachedVScale &&
  20730. this.uAng === this._cachedUAng &&
  20731. this.vAng === this._cachedVAng &&
  20732. this.wAng === this._cachedWAng) {
  20733. return this._cachedTextureMatrix;
  20734. }
  20735. this._cachedUOffset = this.uOffset;
  20736. this._cachedVOffset = this.vOffset;
  20737. this._cachedUScale = this.uScale;
  20738. this._cachedVScale = this.vScale;
  20739. this._cachedUAng = this.uAng;
  20740. this._cachedVAng = this.vAng;
  20741. this._cachedWAng = this.wAng;
  20742. if (!this._cachedTextureMatrix) {
  20743. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20744. this._rowGenerationMatrix = new BABYLON.Matrix();
  20745. this._t0 = BABYLON.Vector3.Zero();
  20746. this._t1 = BABYLON.Vector3.Zero();
  20747. this._t2 = BABYLON.Vector3.Zero();
  20748. }
  20749. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20750. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20751. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20752. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20753. this._t1.subtractInPlace(this._t0);
  20754. this._t2.subtractInPlace(this._t0);
  20755. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20756. this._cachedTextureMatrix.m[0] = this._t1.x;
  20757. this._cachedTextureMatrix.m[1] = this._t1.y;
  20758. this._cachedTextureMatrix.m[2] = this._t1.z;
  20759. this._cachedTextureMatrix.m[4] = this._t2.x;
  20760. this._cachedTextureMatrix.m[5] = this._t2.y;
  20761. this._cachedTextureMatrix.m[6] = this._t2.z;
  20762. this._cachedTextureMatrix.m[8] = this._t0.x;
  20763. this._cachedTextureMatrix.m[9] = this._t0.y;
  20764. this._cachedTextureMatrix.m[10] = this._t0.z;
  20765. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20766. return mat.hasTexture(_this);
  20767. });
  20768. return this._cachedTextureMatrix;
  20769. };
  20770. Texture.prototype.getReflectionTextureMatrix = function () {
  20771. var _this = this;
  20772. var scene = this.getScene();
  20773. if (this.uOffset === this._cachedUOffset &&
  20774. this.vOffset === this._cachedVOffset &&
  20775. this.uScale === this._cachedUScale &&
  20776. this.vScale === this._cachedVScale &&
  20777. this.coordinatesMode === this._cachedCoordinatesMode) {
  20778. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20779. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20780. return this._cachedTextureMatrix;
  20781. }
  20782. }
  20783. else {
  20784. return this._cachedTextureMatrix;
  20785. }
  20786. }
  20787. if (!this._cachedTextureMatrix) {
  20788. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20789. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20790. }
  20791. this._cachedUOffset = this.uOffset;
  20792. this._cachedVOffset = this.vOffset;
  20793. this._cachedUScale = this.uScale;
  20794. this._cachedVScale = this.vScale;
  20795. this._cachedCoordinatesMode = this.coordinatesMode;
  20796. switch (this.coordinatesMode) {
  20797. case Texture.PLANAR_MODE:
  20798. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20799. this._cachedTextureMatrix[0] = this.uScale;
  20800. this._cachedTextureMatrix[5] = this.vScale;
  20801. this._cachedTextureMatrix[12] = this.uOffset;
  20802. this._cachedTextureMatrix[13] = this.vOffset;
  20803. break;
  20804. case Texture.PROJECTION_MODE:
  20805. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20806. this._projectionModeMatrix.m[0] = 0.5;
  20807. this._projectionModeMatrix.m[5] = -0.5;
  20808. this._projectionModeMatrix.m[10] = 0.0;
  20809. this._projectionModeMatrix.m[12] = 0.5;
  20810. this._projectionModeMatrix.m[13] = 0.5;
  20811. this._projectionModeMatrix.m[14] = 1.0;
  20812. this._projectionModeMatrix.m[15] = 1.0;
  20813. var projectionMatrix = scene.getProjectionMatrix();
  20814. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20815. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20816. break;
  20817. default:
  20818. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20819. break;
  20820. }
  20821. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20822. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20823. });
  20824. return this._cachedTextureMatrix;
  20825. };
  20826. Texture.prototype.clone = function () {
  20827. var _this = this;
  20828. return BABYLON.SerializationHelper.Clone(function () {
  20829. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20830. }, this);
  20831. };
  20832. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20833. get: function () {
  20834. if (!this._onLoadObservable) {
  20835. this._onLoadObservable = new BABYLON.Observable();
  20836. }
  20837. return this._onLoadObservable;
  20838. },
  20839. enumerable: true,
  20840. configurable: true
  20841. });
  20842. Texture.prototype.serialize = function () {
  20843. var serializationObject = _super.prototype.serialize.call(this);
  20844. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20845. serializationObject.base64String = this._buffer;
  20846. serializationObject.name = serializationObject.name.replace("data:", "");
  20847. }
  20848. return serializationObject;
  20849. };
  20850. Texture.prototype.getClassName = function () {
  20851. return "Texture";
  20852. };
  20853. Texture.prototype.dispose = function () {
  20854. _super.prototype.dispose.call(this);
  20855. if (this.onLoadObservable) {
  20856. this.onLoadObservable.clear();
  20857. this._onLoadObservable = null;
  20858. }
  20859. this._delayedOnLoad = null;
  20860. this._delayedOnError = null;
  20861. };
  20862. // Statics
  20863. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20864. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20865. if (onLoad === void 0) { onLoad = null; }
  20866. if (onError === void 0) { onError = null; }
  20867. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20868. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20869. };
  20870. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20871. if (parsedTexture.customType) {
  20872. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20873. // Update Sampling Mode
  20874. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20875. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20876. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20877. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20878. }
  20879. }
  20880. return parsedCustomTexture;
  20881. }
  20882. if (parsedTexture.isCube) {
  20883. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20884. }
  20885. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20886. return null;
  20887. }
  20888. var texture = BABYLON.SerializationHelper.Parse(function () {
  20889. if (parsedTexture.mirrorPlane) {
  20890. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20891. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20892. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20893. return mirrorTexture;
  20894. }
  20895. else if (parsedTexture.isRenderTarget) {
  20896. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20897. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20898. return renderTargetTexture;
  20899. }
  20900. else {
  20901. var texture;
  20902. if (parsedTexture.base64String) {
  20903. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20904. }
  20905. else {
  20906. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20907. }
  20908. return texture;
  20909. }
  20910. }, parsedTexture, scene);
  20911. // Update Sampling Mode
  20912. if (parsedTexture.samplingMode) {
  20913. var sampling = parsedTexture.samplingMode;
  20914. if (texture._samplingMode !== sampling) {
  20915. texture.updateSamplingMode(sampling);
  20916. }
  20917. }
  20918. // Animations
  20919. if (parsedTexture.animations) {
  20920. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20921. var parsedAnimation = parsedTexture.animations[animationIndex];
  20922. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20923. }
  20924. }
  20925. return texture;
  20926. };
  20927. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20928. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20929. if (noMipmap === void 0) { noMipmap = false; }
  20930. if (invertY === void 0) { invertY = true; }
  20931. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20932. if (onLoad === void 0) { onLoad = null; }
  20933. if (onError === void 0) { onError = null; }
  20934. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20935. if (name.substr(0, 5) !== "data:") {
  20936. name = "data:" + name;
  20937. }
  20938. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20939. };
  20940. // Constants
  20941. Texture.NEAREST_SAMPLINGMODE = 1;
  20942. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20943. Texture.BILINEAR_SAMPLINGMODE = 2;
  20944. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20945. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20946. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20947. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20948. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20949. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20950. Texture.NEAREST_LINEAR = 7;
  20951. Texture.NEAREST_NEAREST = 8;
  20952. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20953. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20954. Texture.LINEAR_LINEAR = 11;
  20955. Texture.LINEAR_NEAREST = 12;
  20956. Texture.EXPLICIT_MODE = 0;
  20957. Texture.SPHERICAL_MODE = 1;
  20958. Texture.PLANAR_MODE = 2;
  20959. Texture.CUBIC_MODE = 3;
  20960. Texture.PROJECTION_MODE = 4;
  20961. Texture.SKYBOX_MODE = 5;
  20962. Texture.INVCUBIC_MODE = 6;
  20963. Texture.EQUIRECTANGULAR_MODE = 7;
  20964. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20965. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20966. Texture.CLAMP_ADDRESSMODE = 0;
  20967. Texture.WRAP_ADDRESSMODE = 1;
  20968. Texture.MIRROR_ADDRESSMODE = 2;
  20969. __decorate([
  20970. BABYLON.serialize()
  20971. ], Texture.prototype, "url", void 0);
  20972. __decorate([
  20973. BABYLON.serialize()
  20974. ], Texture.prototype, "uOffset", void 0);
  20975. __decorate([
  20976. BABYLON.serialize()
  20977. ], Texture.prototype, "vOffset", void 0);
  20978. __decorate([
  20979. BABYLON.serialize()
  20980. ], Texture.prototype, "uScale", void 0);
  20981. __decorate([
  20982. BABYLON.serialize()
  20983. ], Texture.prototype, "vScale", void 0);
  20984. __decorate([
  20985. BABYLON.serialize()
  20986. ], Texture.prototype, "uAng", void 0);
  20987. __decorate([
  20988. BABYLON.serialize()
  20989. ], Texture.prototype, "vAng", void 0);
  20990. __decorate([
  20991. BABYLON.serialize()
  20992. ], Texture.prototype, "wAng", void 0);
  20993. __decorate([
  20994. BABYLON.serialize()
  20995. ], Texture.prototype, "isBlocking", null);
  20996. return Texture;
  20997. }(BABYLON.BaseTexture));
  20998. BABYLON.Texture = Texture;
  20999. })(BABYLON || (BABYLON = {}));
  21000. //# sourceMappingURL=babylon.texture.js.map
  21001. var BABYLON;
  21002. (function (BABYLON) {
  21003. var _InstancesBatch = (function () {
  21004. function _InstancesBatch() {
  21005. this.mustReturn = false;
  21006. this.visibleInstances = new Array();
  21007. this.renderSelf = new Array();
  21008. }
  21009. return _InstancesBatch;
  21010. }());
  21011. BABYLON._InstancesBatch = _InstancesBatch;
  21012. var Mesh = (function (_super) {
  21013. __extends(Mesh, _super);
  21014. /**
  21015. * @constructor
  21016. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21017. * @param {Scene} scene The scene to add this mesh to.
  21018. * @param {Node} parent The parent of this mesh, if it has one
  21019. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21020. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21021. * When false, achieved by calling a clone(), also passing False.
  21022. * This will make creation of children, recursive.
  21023. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21024. */
  21025. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21026. if (parent === void 0) { parent = null; }
  21027. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21028. var _this = _super.call(this, name, scene) || this;
  21029. // Events
  21030. /**
  21031. * An event triggered before rendering the mesh
  21032. * @type {BABYLON.Observable}
  21033. */
  21034. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21035. /**
  21036. * An event triggered after rendering the mesh
  21037. * @type {BABYLON.Observable}
  21038. */
  21039. _this.onAfterRenderObservable = new BABYLON.Observable();
  21040. /**
  21041. * An event triggered before drawing the mesh
  21042. * @type {BABYLON.Observable}
  21043. */
  21044. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21045. // Members
  21046. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21047. _this.instances = new Array();
  21048. _this._LODLevels = new Array();
  21049. _this._visibleInstances = {};
  21050. _this._renderIdForInstances = new Array();
  21051. _this._batchCache = new _InstancesBatch();
  21052. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21053. _this._sideOrientation = Mesh._DEFAULTSIDE;
  21054. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21055. // Will be used to save a source mesh reference, If any
  21056. _this._source = null;
  21057. if (source) {
  21058. // Source mesh
  21059. _this._source = source;
  21060. // Geometry
  21061. if (source._geometry) {
  21062. source._geometry.applyToMesh(_this);
  21063. }
  21064. // Deep copy
  21065. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21066. // Parent
  21067. _this.parent = source.parent;
  21068. // Pivot
  21069. _this.setPivotMatrix(source.getPivotMatrix());
  21070. _this.id = name + "." + source.id;
  21071. // Material
  21072. _this.material = source.material;
  21073. var index;
  21074. if (!doNotCloneChildren) {
  21075. // Children
  21076. for (index = 0; index < scene.meshes.length; index++) {
  21077. var mesh = scene.meshes[index];
  21078. if (mesh.parent === source) {
  21079. // doNotCloneChildren is always going to be False
  21080. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21081. }
  21082. }
  21083. }
  21084. // Physics clone
  21085. var physicsEngine = _this.getScene().getPhysicsEngine();
  21086. if (clonePhysicsImpostor && physicsEngine) {
  21087. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21088. if (impostor) {
  21089. _this.physicsImpostor = impostor.clone(_this);
  21090. }
  21091. }
  21092. // Particles
  21093. for (index = 0; index < scene.particleSystems.length; index++) {
  21094. var system = scene.particleSystems[index];
  21095. if (system.emitter === source) {
  21096. system.clone(system.name, _this);
  21097. }
  21098. }
  21099. _this.computeWorldMatrix(true);
  21100. }
  21101. // Parent
  21102. if (parent !== null) {
  21103. _this.parent = parent;
  21104. }
  21105. return _this;
  21106. }
  21107. Object.defineProperty(Mesh, "FRONTSIDE", {
  21108. /**
  21109. * Mesh side orientation : usually the external or front surface
  21110. */
  21111. get: function () {
  21112. return Mesh._FRONTSIDE;
  21113. },
  21114. enumerable: true,
  21115. configurable: true
  21116. });
  21117. Object.defineProperty(Mesh, "BACKSIDE", {
  21118. /**
  21119. * Mesh side orientation : usually the internal or back surface
  21120. */
  21121. get: function () {
  21122. return Mesh._BACKSIDE;
  21123. },
  21124. enumerable: true,
  21125. configurable: true
  21126. });
  21127. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21128. /**
  21129. * Mesh side orientation : both internal and external or front and back surfaces
  21130. */
  21131. get: function () {
  21132. return Mesh._DOUBLESIDE;
  21133. },
  21134. enumerable: true,
  21135. configurable: true
  21136. });
  21137. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21138. /**
  21139. * Mesh side orientation : by default, `FRONTSIDE`
  21140. */
  21141. get: function () {
  21142. return Mesh._DEFAULTSIDE;
  21143. },
  21144. enumerable: true,
  21145. configurable: true
  21146. });
  21147. Object.defineProperty(Mesh, "NO_CAP", {
  21148. /**
  21149. * Mesh cap setting : no cap
  21150. */
  21151. get: function () {
  21152. return Mesh._NO_CAP;
  21153. },
  21154. enumerable: true,
  21155. configurable: true
  21156. });
  21157. Object.defineProperty(Mesh, "CAP_START", {
  21158. /**
  21159. * Mesh cap setting : one cap at the beginning of the mesh
  21160. */
  21161. get: function () {
  21162. return Mesh._CAP_START;
  21163. },
  21164. enumerable: true,
  21165. configurable: true
  21166. });
  21167. Object.defineProperty(Mesh, "CAP_END", {
  21168. /**
  21169. * Mesh cap setting : one cap at the end of the mesh
  21170. */
  21171. get: function () {
  21172. return Mesh._CAP_END;
  21173. },
  21174. enumerable: true,
  21175. configurable: true
  21176. });
  21177. Object.defineProperty(Mesh, "CAP_ALL", {
  21178. /**
  21179. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21180. */
  21181. get: function () {
  21182. return Mesh._CAP_ALL;
  21183. },
  21184. enumerable: true,
  21185. configurable: true
  21186. });
  21187. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21188. set: function (callback) {
  21189. if (this._onBeforeDrawObserver) {
  21190. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21191. }
  21192. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21193. },
  21194. enumerable: true,
  21195. configurable: true
  21196. });
  21197. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21198. get: function () {
  21199. return this._morphTargetManager;
  21200. },
  21201. set: function (value) {
  21202. if (this._morphTargetManager === value) {
  21203. return;
  21204. }
  21205. this._morphTargetManager = value;
  21206. this._syncGeometryWithMorphTargetManager();
  21207. },
  21208. enumerable: true,
  21209. configurable: true
  21210. });
  21211. Object.defineProperty(Mesh.prototype, "source", {
  21212. get: function () {
  21213. return this._source;
  21214. },
  21215. enumerable: true,
  21216. configurable: true
  21217. });
  21218. // Methods
  21219. /**
  21220. * Returns the string "Mesh".
  21221. */
  21222. Mesh.prototype.getClassName = function () {
  21223. return "Mesh";
  21224. };
  21225. /**
  21226. * Returns a string.
  21227. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21228. */
  21229. Mesh.prototype.toString = function (fullDetails) {
  21230. var ret = _super.prototype.toString.call(this, fullDetails);
  21231. ret += ", n vertices: " + this.getTotalVertices();
  21232. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21233. if (this.animations) {
  21234. for (var i = 0; i < this.animations.length; i++) {
  21235. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21236. }
  21237. }
  21238. if (fullDetails) {
  21239. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21240. }
  21241. return ret;
  21242. };
  21243. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21244. /**
  21245. * True if the mesh has some Levels Of Details (LOD).
  21246. * Returns a boolean.
  21247. */
  21248. get: function () {
  21249. return this._LODLevels.length > 0;
  21250. },
  21251. enumerable: true,
  21252. configurable: true
  21253. });
  21254. Mesh.prototype._sortLODLevels = function () {
  21255. this._LODLevels.sort(function (a, b) {
  21256. if (a.distance < b.distance) {
  21257. return 1;
  21258. }
  21259. if (a.distance > b.distance) {
  21260. return -1;
  21261. }
  21262. return 0;
  21263. });
  21264. };
  21265. /**
  21266. * Add a mesh as LOD level triggered at the given distance.
  21267. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21268. * @param {number} distance The distance from the center of the object to show this level
  21269. * @param {Mesh} mesh The mesh to be added as LOD level
  21270. * @return {Mesh} This mesh (for chaining)
  21271. */
  21272. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21273. if (mesh && mesh._masterMesh) {
  21274. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21275. return this;
  21276. }
  21277. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21278. this._LODLevels.push(level);
  21279. if (mesh) {
  21280. mesh._masterMesh = this;
  21281. }
  21282. this._sortLODLevels();
  21283. return this;
  21284. };
  21285. /**
  21286. * Returns the LOD level mesh at the passed distance or null if not found.
  21287. * It is related to the method `addLODLevel(distance, mesh)`.
  21288. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21289. * Returns an object Mesh or `null`.
  21290. */
  21291. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21292. for (var index = 0; index < this._LODLevels.length; index++) {
  21293. var level = this._LODLevels[index];
  21294. if (level.distance === distance) {
  21295. return level.mesh;
  21296. }
  21297. }
  21298. return null;
  21299. };
  21300. /**
  21301. * Remove a mesh from the LOD array
  21302. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21303. * @param {Mesh} mesh The mesh to be removed.
  21304. * @return {Mesh} This mesh (for chaining)
  21305. */
  21306. Mesh.prototype.removeLODLevel = function (mesh) {
  21307. for (var index = 0; index < this._LODLevels.length; index++) {
  21308. if (this._LODLevels[index].mesh === mesh) {
  21309. this._LODLevels.splice(index, 1);
  21310. if (mesh) {
  21311. mesh._masterMesh = null;
  21312. }
  21313. }
  21314. }
  21315. this._sortLODLevels();
  21316. return this;
  21317. };
  21318. /**
  21319. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21320. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21321. */
  21322. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21323. if (!this._LODLevels || this._LODLevels.length === 0) {
  21324. return this;
  21325. }
  21326. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21327. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21328. if (this.onLODLevelSelection) {
  21329. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21330. }
  21331. return this;
  21332. }
  21333. for (var index = 0; index < this._LODLevels.length; index++) {
  21334. var level = this._LODLevels[index];
  21335. if (level.distance < distanceToCamera) {
  21336. if (level.mesh) {
  21337. level.mesh._preActivate();
  21338. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21339. }
  21340. if (this.onLODLevelSelection) {
  21341. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21342. }
  21343. return level.mesh;
  21344. }
  21345. }
  21346. if (this.onLODLevelSelection) {
  21347. this.onLODLevelSelection(distanceToCamera, this, this);
  21348. }
  21349. return this;
  21350. };
  21351. Object.defineProperty(Mesh.prototype, "geometry", {
  21352. /**
  21353. * Returns the mesh internal Geometry object.
  21354. */
  21355. get: function () {
  21356. return this._geometry;
  21357. },
  21358. enumerable: true,
  21359. configurable: true
  21360. });
  21361. /**
  21362. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21363. */
  21364. Mesh.prototype.getTotalVertices = function () {
  21365. if (!this._geometry) {
  21366. return 0;
  21367. }
  21368. return this._geometry.getTotalVertices();
  21369. };
  21370. /**
  21371. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21372. * 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.
  21373. * You can force the copy with forceCopy === true
  21374. * Returns null if the mesh has no geometry or no vertex buffer.
  21375. * Possible `kind` values :
  21376. * - BABYLON.VertexBuffer.PositionKind
  21377. * - BABYLON.VertexBuffer.UVKind
  21378. * - BABYLON.VertexBuffer.UV2Kind
  21379. * - BABYLON.VertexBuffer.UV3Kind
  21380. * - BABYLON.VertexBuffer.UV4Kind
  21381. * - BABYLON.VertexBuffer.UV5Kind
  21382. * - BABYLON.VertexBuffer.UV6Kind
  21383. * - BABYLON.VertexBuffer.ColorKind
  21384. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21385. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21386. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21387. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21388. */
  21389. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21390. if (!this._geometry) {
  21391. return null;
  21392. }
  21393. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21394. };
  21395. /**
  21396. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21397. * Returns `undefined` if the mesh has no geometry.
  21398. * Possible `kind` values :
  21399. * - BABYLON.VertexBuffer.PositionKind
  21400. * - BABYLON.VertexBuffer.UVKind
  21401. * - BABYLON.VertexBuffer.UV2Kind
  21402. * - BABYLON.VertexBuffer.UV3Kind
  21403. * - BABYLON.VertexBuffer.UV4Kind
  21404. * - BABYLON.VertexBuffer.UV5Kind
  21405. * - BABYLON.VertexBuffer.UV6Kind
  21406. * - BABYLON.VertexBuffer.ColorKind
  21407. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21408. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21409. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21410. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21411. */
  21412. Mesh.prototype.getVertexBuffer = function (kind) {
  21413. if (!this._geometry) {
  21414. return undefined;
  21415. }
  21416. return this._geometry.getVertexBuffer(kind);
  21417. };
  21418. /**
  21419. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21420. * Possible `kind` values :
  21421. * - BABYLON.VertexBuffer.PositionKind
  21422. * - BABYLON.VertexBuffer.UVKind
  21423. * - BABYLON.VertexBuffer.UV2Kind
  21424. * - BABYLON.VertexBuffer.UV3Kind
  21425. * - BABYLON.VertexBuffer.UV4Kind
  21426. * - BABYLON.VertexBuffer.UV5Kind
  21427. * - BABYLON.VertexBuffer.UV6Kind
  21428. * - BABYLON.VertexBuffer.ColorKind
  21429. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21430. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21431. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21432. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21433. */
  21434. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21435. if (!this._geometry) {
  21436. if (this._delayInfo) {
  21437. return this._delayInfo.indexOf(kind) !== -1;
  21438. }
  21439. return false;
  21440. }
  21441. return this._geometry.isVerticesDataPresent(kind);
  21442. };
  21443. /**
  21444. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21445. * Possible `kind` values :
  21446. * - BABYLON.VertexBuffer.PositionKind
  21447. * - BABYLON.VertexBuffer.UVKind
  21448. * - BABYLON.VertexBuffer.UV2Kind
  21449. * - BABYLON.VertexBuffer.UV3Kind
  21450. * - BABYLON.VertexBuffer.UV4Kind
  21451. * - BABYLON.VertexBuffer.UV5Kind
  21452. * - BABYLON.VertexBuffer.UV6Kind
  21453. * - BABYLON.VertexBuffer.ColorKind
  21454. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21455. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21456. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21457. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21458. */
  21459. Mesh.prototype.getVerticesDataKinds = function () {
  21460. if (!this._geometry) {
  21461. var result = [];
  21462. if (this._delayInfo) {
  21463. this._delayInfo.forEach(function (kind, index, array) {
  21464. result.push(kind);
  21465. });
  21466. }
  21467. return result;
  21468. }
  21469. return this._geometry.getVerticesDataKinds();
  21470. };
  21471. /**
  21472. * Returns a positive integer : the total number of indices in this mesh geometry.
  21473. * Returns zero if the mesh has no geometry.
  21474. */
  21475. Mesh.prototype.getTotalIndices = function () {
  21476. if (!this._geometry) {
  21477. return 0;
  21478. }
  21479. return this._geometry.getTotalIndices();
  21480. };
  21481. /**
  21482. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21483. * 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.
  21484. * Returns an empty array if the mesh has no geometry.
  21485. */
  21486. Mesh.prototype.getIndices = function (copyWhenShared) {
  21487. if (!this._geometry) {
  21488. return [];
  21489. }
  21490. return this._geometry.getIndices(copyWhenShared);
  21491. };
  21492. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21493. get: function () {
  21494. return this._masterMesh !== null && this._masterMesh !== undefined;
  21495. },
  21496. enumerable: true,
  21497. configurable: true
  21498. });
  21499. /**
  21500. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21501. */
  21502. Mesh.prototype.isReady = function () {
  21503. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21504. return false;
  21505. }
  21506. return _super.prototype.isReady.call(this);
  21507. };
  21508. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21509. get: function () {
  21510. return this._sideOrientation;
  21511. },
  21512. /**
  21513. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21514. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21515. */
  21516. set: function (sideO) {
  21517. this._sideOrientation = sideO;
  21518. },
  21519. enumerable: true,
  21520. configurable: true
  21521. });
  21522. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21523. /**
  21524. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21525. * This property is pertinent only for updatable parametric shapes.
  21526. */
  21527. get: function () {
  21528. return this._areNormalsFrozen;
  21529. },
  21530. enumerable: true,
  21531. configurable: true
  21532. });
  21533. /**
  21534. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21535. * It has no effect at all on other shapes.
  21536. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21537. * Returns the Mesh.
  21538. */
  21539. Mesh.prototype.freezeNormals = function () {
  21540. this._areNormalsFrozen = true;
  21541. return this;
  21542. };
  21543. /**
  21544. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21545. * It has no effect at all on other shapes.
  21546. * It reactivates the mesh normals computation if it was previously frozen.
  21547. * Returns the Mesh.
  21548. */
  21549. Mesh.prototype.unfreezeNormals = function () {
  21550. this._areNormalsFrozen = false;
  21551. return this;
  21552. };
  21553. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21554. /**
  21555. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21556. */
  21557. set: function (count) {
  21558. this._overridenInstanceCount = count;
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. // Methods
  21564. Mesh.prototype._preActivate = function () {
  21565. var sceneRenderId = this.getScene().getRenderId();
  21566. if (this._preActivateId === sceneRenderId) {
  21567. return this;
  21568. }
  21569. this._preActivateId = sceneRenderId;
  21570. this._visibleInstances = null;
  21571. return this;
  21572. };
  21573. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21574. if (this._visibleInstances) {
  21575. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21576. }
  21577. return this;
  21578. };
  21579. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21580. if (!this._visibleInstances) {
  21581. this._visibleInstances = {};
  21582. this._visibleInstances.defaultRenderId = renderId;
  21583. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21584. }
  21585. if (!this._visibleInstances[renderId]) {
  21586. this._visibleInstances[renderId] = new Array();
  21587. }
  21588. this._visibleInstances[renderId].push(instance);
  21589. return this;
  21590. };
  21591. /**
  21592. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21593. * This means the mesh underlying bounding box and sphere are recomputed.
  21594. * Returns the Mesh.
  21595. */
  21596. Mesh.prototype.refreshBoundingInfo = function () {
  21597. if (this._boundingInfo.isLocked) {
  21598. return;
  21599. }
  21600. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21601. if (data) {
  21602. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21603. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21604. }
  21605. if (this.subMeshes) {
  21606. for (var index = 0; index < this.subMeshes.length; index++) {
  21607. this.subMeshes[index].refreshBoundingInfo();
  21608. }
  21609. }
  21610. this._updateBoundingInfo();
  21611. return this;
  21612. };
  21613. Mesh.prototype._createGlobalSubMesh = function (force) {
  21614. var totalVertices = this.getTotalVertices();
  21615. if (!totalVertices || !this.getIndices()) {
  21616. return null;
  21617. }
  21618. // Check if we need to recreate the submeshes
  21619. if (this.subMeshes && this.subMeshes.length > 0) {
  21620. var totalIndices = this.getIndices().length;
  21621. var needToRecreate = false;
  21622. if (force) {
  21623. needToRecreate = true;
  21624. }
  21625. else {
  21626. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21627. var submesh = _a[_i];
  21628. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21629. needToRecreate = true;
  21630. break;
  21631. }
  21632. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21633. needToRecreate = true;
  21634. break;
  21635. }
  21636. }
  21637. }
  21638. if (!needToRecreate) {
  21639. return;
  21640. }
  21641. }
  21642. this.releaseSubMeshes();
  21643. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21644. };
  21645. Mesh.prototype.subdivide = function (count) {
  21646. if (count < 1) {
  21647. return;
  21648. }
  21649. var totalIndices = this.getTotalIndices();
  21650. var subdivisionSize = (totalIndices / count) | 0;
  21651. var offset = 0;
  21652. // Ensure that subdivisionSize is a multiple of 3
  21653. while (subdivisionSize % 3 !== 0) {
  21654. subdivisionSize++;
  21655. }
  21656. this.releaseSubMeshes();
  21657. for (var index = 0; index < count; index++) {
  21658. if (offset >= totalIndices) {
  21659. break;
  21660. }
  21661. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21662. offset += subdivisionSize;
  21663. }
  21664. this.synchronizeInstances();
  21665. };
  21666. /**
  21667. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21668. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21669. * The `data` are either a numeric array either a Float32Array.
  21670. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21671. * 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).
  21672. * Note that a new underlying VertexBuffer object is created each call.
  21673. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21674. *
  21675. * Possible `kind` values :
  21676. * - BABYLON.VertexBuffer.PositionKind
  21677. * - BABYLON.VertexBuffer.UVKind
  21678. * - BABYLON.VertexBuffer.UV2Kind
  21679. * - BABYLON.VertexBuffer.UV3Kind
  21680. * - BABYLON.VertexBuffer.UV4Kind
  21681. * - BABYLON.VertexBuffer.UV5Kind
  21682. * - BABYLON.VertexBuffer.UV6Kind
  21683. * - BABYLON.VertexBuffer.ColorKind
  21684. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21685. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21686. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21687. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21688. *
  21689. * Returns the Mesh.
  21690. */
  21691. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21692. if (!this._geometry) {
  21693. var vertexData = new BABYLON.VertexData();
  21694. vertexData.set(data, kind);
  21695. var scene = this.getScene();
  21696. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21697. }
  21698. else {
  21699. this._geometry.setVerticesData(kind, data, updatable, stride);
  21700. }
  21701. return this;
  21702. };
  21703. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21704. if (updatable === void 0) { updatable = true; }
  21705. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21706. return;
  21707. }
  21708. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21709. };
  21710. /**
  21711. * Sets the mesh VertexBuffer.
  21712. * Returns the Mesh.
  21713. */
  21714. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21715. if (!this._geometry) {
  21716. var scene = this.getScene();
  21717. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21718. }
  21719. this._geometry.setVerticesBuffer(buffer);
  21720. return this;
  21721. };
  21722. /**
  21723. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21724. * If the mesh has no geometry, it is simply returned as it is.
  21725. * The `data` are either a numeric array either a Float32Array.
  21726. * No new underlying VertexBuffer object is created.
  21727. * 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.
  21728. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21729. *
  21730. * Possible `kind` values :
  21731. * - BABYLON.VertexBuffer.PositionKind
  21732. * - BABYLON.VertexBuffer.UVKind
  21733. * - BABYLON.VertexBuffer.UV2Kind
  21734. * - BABYLON.VertexBuffer.UV3Kind
  21735. * - BABYLON.VertexBuffer.UV4Kind
  21736. * - BABYLON.VertexBuffer.UV5Kind
  21737. * - BABYLON.VertexBuffer.UV6Kind
  21738. * - BABYLON.VertexBuffer.ColorKind
  21739. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21740. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21741. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21742. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21743. *
  21744. * Returns the Mesh.
  21745. */
  21746. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21747. if (!this._geometry) {
  21748. return;
  21749. }
  21750. if (!makeItUnique) {
  21751. this._geometry.updateVerticesData(kind, data, updateExtends);
  21752. }
  21753. else {
  21754. this.makeGeometryUnique();
  21755. this.updateVerticesData(kind, data, updateExtends, false);
  21756. }
  21757. return this;
  21758. };
  21759. /**
  21760. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21761. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21762. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21763. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21764. * Returns the Mesh.
  21765. */
  21766. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21767. if (computeNormals === void 0) { computeNormals = true; }
  21768. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21769. positionFunction(positions);
  21770. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21771. if (computeNormals) {
  21772. var indices = this.getIndices();
  21773. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21774. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21775. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21776. }
  21777. return this;
  21778. };
  21779. /**
  21780. * Creates a un-shared specific occurence of the geometry for the mesh.
  21781. * Returns the Mesh.
  21782. */
  21783. Mesh.prototype.makeGeometryUnique = function () {
  21784. if (!this._geometry) {
  21785. return;
  21786. }
  21787. var oldGeometry = this._geometry;
  21788. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21789. oldGeometry.releaseForMesh(this, true);
  21790. geometry.applyToMesh(this);
  21791. return this;
  21792. };
  21793. /**
  21794. * Sets the mesh indices.
  21795. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21796. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21797. * This method creates a new index buffer each call.
  21798. * Returns the Mesh.
  21799. */
  21800. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21801. if (!this._geometry) {
  21802. var vertexData = new BABYLON.VertexData();
  21803. vertexData.indices = indices;
  21804. var scene = this.getScene();
  21805. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21806. }
  21807. else {
  21808. this._geometry.setIndices(indices, totalVertices);
  21809. }
  21810. return this;
  21811. };
  21812. /**
  21813. * Invert the geometry to move from a right handed system to a left handed one.
  21814. * Returns the Mesh.
  21815. */
  21816. Mesh.prototype.toLeftHanded = function () {
  21817. if (!this._geometry) {
  21818. return;
  21819. }
  21820. this._geometry.toLeftHanded();
  21821. return this;
  21822. };
  21823. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21824. var engine = this.getScene().getEngine();
  21825. // Wireframe
  21826. var indexToBind;
  21827. if (this._unIndexed) {
  21828. indexToBind = null;
  21829. }
  21830. else {
  21831. switch (fillMode) {
  21832. case BABYLON.Material.PointFillMode:
  21833. indexToBind = null;
  21834. break;
  21835. case BABYLON.Material.WireFrameFillMode:
  21836. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21837. break;
  21838. default:
  21839. case BABYLON.Material.TriangleFillMode:
  21840. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21841. break;
  21842. }
  21843. }
  21844. // VBOs
  21845. this._geometry._bind(effect, indexToBind);
  21846. return this;
  21847. };
  21848. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21849. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21850. return this;
  21851. }
  21852. this.onBeforeDrawObservable.notifyObservers(this);
  21853. var engine = this.getScene().getEngine();
  21854. // Draw order
  21855. switch (fillMode) {
  21856. case BABYLON.Material.PointFillMode:
  21857. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21858. break;
  21859. case BABYLON.Material.WireFrameFillMode:
  21860. if (this._unIndexed) {
  21861. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21862. }
  21863. else {
  21864. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  21865. }
  21866. break;
  21867. default:
  21868. if (this._unIndexed) {
  21869. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21870. }
  21871. else {
  21872. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21873. }
  21874. }
  21875. return this;
  21876. };
  21877. /**
  21878. * Registers for this mesh a javascript function called just before the rendering process.
  21879. * This function is passed the current mesh.
  21880. * Return the Mesh.
  21881. */
  21882. Mesh.prototype.registerBeforeRender = function (func) {
  21883. this.onBeforeRenderObservable.add(func);
  21884. return this;
  21885. };
  21886. /**
  21887. * Disposes a previously registered javascript function called before the rendering.
  21888. * This function is passed the current mesh.
  21889. * Returns the Mesh.
  21890. */
  21891. Mesh.prototype.unregisterBeforeRender = function (func) {
  21892. this.onBeforeRenderObservable.removeCallback(func);
  21893. return this;
  21894. };
  21895. /**
  21896. * Registers for this mesh a javascript function called just after the rendering is complete.
  21897. * This function is passed the current mesh.
  21898. * Returns the Mesh.
  21899. */
  21900. Mesh.prototype.registerAfterRender = function (func) {
  21901. this.onAfterRenderObservable.add(func);
  21902. return this;
  21903. };
  21904. /**
  21905. * Disposes a previously registered javascript function called after the rendering.
  21906. * This function is passed the current mesh.
  21907. * Return the Mesh.
  21908. */
  21909. Mesh.prototype.unregisterAfterRender = function (func) {
  21910. this.onAfterRenderObservable.removeCallback(func);
  21911. return this;
  21912. };
  21913. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21914. var scene = this.getScene();
  21915. this._batchCache.mustReturn = false;
  21916. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21917. this._batchCache.visibleInstances[subMeshId] = null;
  21918. if (this._visibleInstances) {
  21919. var currentRenderId = scene.getRenderId();
  21920. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21921. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21922. var selfRenderId = this._renderId;
  21923. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21924. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21925. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21926. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21927. }
  21928. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21929. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21930. this._batchCache.mustReturn = true;
  21931. return this._batchCache;
  21932. }
  21933. if (currentRenderId !== selfRenderId) {
  21934. this._batchCache.renderSelf[subMeshId] = false;
  21935. }
  21936. }
  21937. this._renderIdForInstances[subMeshId] = currentRenderId;
  21938. }
  21939. return this._batchCache;
  21940. };
  21941. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21942. var visibleInstances = batch.visibleInstances[subMesh._id];
  21943. var matricesCount = visibleInstances.length + 1;
  21944. var bufferSize = matricesCount * 16 * 4;
  21945. var currentInstancesBufferSize = this._instancesBufferSize;
  21946. var instancesBuffer = this._instancesBuffer;
  21947. while (this._instancesBufferSize < bufferSize) {
  21948. this._instancesBufferSize *= 2;
  21949. }
  21950. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21951. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21952. }
  21953. var offset = 0;
  21954. var instancesCount = 0;
  21955. var world = this.getWorldMatrix();
  21956. if (batch.renderSelf[subMesh._id]) {
  21957. world.copyToArray(this._instancesData, offset);
  21958. offset += 16;
  21959. instancesCount++;
  21960. }
  21961. if (visibleInstances) {
  21962. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21963. var instance = visibleInstances[instanceIndex];
  21964. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21965. offset += 16;
  21966. instancesCount++;
  21967. }
  21968. }
  21969. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21970. if (instancesBuffer) {
  21971. instancesBuffer.dispose();
  21972. }
  21973. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21974. this._instancesBuffer = instancesBuffer;
  21975. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21976. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21977. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21978. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21979. }
  21980. else {
  21981. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21982. }
  21983. this._bind(subMesh, effect, fillMode);
  21984. this._draw(subMesh, fillMode, instancesCount);
  21985. engine.unbindInstanceAttributes();
  21986. return this;
  21987. };
  21988. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21989. var scene = this.getScene();
  21990. var engine = scene.getEngine();
  21991. if (hardwareInstancedRendering) {
  21992. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21993. }
  21994. else {
  21995. if (batch.renderSelf[subMesh._id]) {
  21996. // Draw
  21997. if (onBeforeDraw) {
  21998. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21999. }
  22000. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22001. }
  22002. if (batch.visibleInstances[subMesh._id]) {
  22003. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22004. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22005. // World
  22006. var world = instance.getWorldMatrix();
  22007. if (onBeforeDraw) {
  22008. onBeforeDraw(true, world, effectiveMaterial);
  22009. }
  22010. // Draw
  22011. this._draw(subMesh, fillMode);
  22012. }
  22013. }
  22014. }
  22015. return this;
  22016. };
  22017. /**
  22018. * Triggers the draw call for the mesh.
  22019. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22020. * Returns the Mesh.
  22021. */
  22022. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22023. this.checkOcclusionQuery();
  22024. if (this._isOccluded) {
  22025. return;
  22026. }
  22027. var scene = this.getScene();
  22028. // Managing instances
  22029. var batch = this._getInstancesRenderList(subMesh._id);
  22030. if (batch.mustReturn) {
  22031. return this;
  22032. }
  22033. // Checking geometry state
  22034. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22035. return this;
  22036. }
  22037. var callbackIndex;
  22038. this.onBeforeRenderObservable.notifyObservers(this);
  22039. var engine = scene.getEngine();
  22040. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22041. // Material
  22042. var effectiveMaterial = subMesh.getMaterial();
  22043. if (!effectiveMaterial) {
  22044. return this;
  22045. }
  22046. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22047. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22048. return this;
  22049. }
  22050. }
  22051. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22052. return this;
  22053. }
  22054. // Alpha mode
  22055. if (enableAlphaMode) {
  22056. engine.setAlphaMode(effectiveMaterial.alphaMode);
  22057. }
  22058. // Outline - step 1
  22059. var savedDepthWrite = engine.getDepthWrite();
  22060. if (this.renderOutline) {
  22061. engine.setDepthWrite(false);
  22062. scene.getOutlineRenderer().render(subMesh, batch);
  22063. engine.setDepthWrite(savedDepthWrite);
  22064. }
  22065. var effect;
  22066. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22067. effect = subMesh.effect;
  22068. }
  22069. else {
  22070. effect = effectiveMaterial.getEffect();
  22071. }
  22072. effectiveMaterial._preBind(effect);
  22073. // Bind
  22074. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  22075. if (!hardwareInstancedRendering) {
  22076. this._bind(subMesh, effect, fillMode);
  22077. }
  22078. var world = this.getWorldMatrix();
  22079. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22080. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22081. }
  22082. else {
  22083. effectiveMaterial.bind(world, this);
  22084. }
  22085. // Draw
  22086. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  22087. // Unbind
  22088. effectiveMaterial.unbind();
  22089. // Outline - step 2
  22090. if (this.renderOutline && savedDepthWrite) {
  22091. engine.setDepthWrite(true);
  22092. engine.setColorWrite(false);
  22093. scene.getOutlineRenderer().render(subMesh, batch);
  22094. engine.setColorWrite(true);
  22095. }
  22096. // Overlay
  22097. if (this.renderOverlay) {
  22098. var currentMode = engine.getAlphaMode();
  22099. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22100. scene.getOutlineRenderer().render(subMesh, batch, true);
  22101. engine.setAlphaMode(currentMode);
  22102. }
  22103. this.onAfterRenderObservable.notifyObservers(this);
  22104. return this;
  22105. };
  22106. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22107. if (isInstance) {
  22108. effectiveMaterial.bindOnlyWorldMatrix(world);
  22109. }
  22110. return this;
  22111. };
  22112. /**
  22113. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22114. */
  22115. Mesh.prototype.getEmittedParticleSystems = function () {
  22116. var results = new Array();
  22117. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22118. var particleSystem = this.getScene().particleSystems[index];
  22119. if (particleSystem.emitter === this) {
  22120. results.push(particleSystem);
  22121. }
  22122. }
  22123. return results;
  22124. };
  22125. /**
  22126. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22127. */
  22128. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22129. var results = new Array();
  22130. var descendants = this.getDescendants();
  22131. descendants.push(this);
  22132. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22133. var particleSystem = this.getScene().particleSystems[index];
  22134. var emitter = particleSystem.emitter;
  22135. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22136. results.push(particleSystem);
  22137. }
  22138. }
  22139. return results;
  22140. };
  22141. Mesh.prototype._checkDelayState = function () {
  22142. var scene = this.getScene();
  22143. if (this._geometry) {
  22144. this._geometry.load(scene);
  22145. }
  22146. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22147. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22148. this._queueLoad(this, scene);
  22149. }
  22150. return this;
  22151. };
  22152. Mesh.prototype._queueLoad = function (mesh, scene) {
  22153. var _this = this;
  22154. scene._addPendingData(mesh);
  22155. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22156. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22157. if (data instanceof ArrayBuffer) {
  22158. _this._delayLoadingFunction(data, _this);
  22159. }
  22160. else {
  22161. _this._delayLoadingFunction(JSON.parse(data), _this);
  22162. }
  22163. _this.instances.forEach(function (instance) {
  22164. instance._syncSubMeshes();
  22165. });
  22166. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22167. scene._removePendingData(_this);
  22168. }, function () { }, scene.database, getBinaryData);
  22169. return this;
  22170. };
  22171. /**
  22172. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22173. */
  22174. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22175. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22176. return false;
  22177. }
  22178. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22179. return false;
  22180. }
  22181. this._checkDelayState();
  22182. return true;
  22183. };
  22184. /**
  22185. * Sets the mesh material by the material or multiMaterial `id` property.
  22186. * The material `id` is a string identifying the material or the multiMaterial.
  22187. * This method returns the Mesh.
  22188. */
  22189. Mesh.prototype.setMaterialByID = function (id) {
  22190. var materials = this.getScene().materials;
  22191. var index;
  22192. for (index = materials.length - 1; index > -1; index--) {
  22193. if (materials[index].id === id) {
  22194. this.material = materials[index];
  22195. return this;
  22196. }
  22197. }
  22198. // Multi
  22199. var multiMaterials = this.getScene().multiMaterials;
  22200. for (index = multiMaterials.length - 1; index > -1; index--) {
  22201. if (multiMaterials[index].id === id) {
  22202. this.material = multiMaterials[index];
  22203. return this;
  22204. }
  22205. }
  22206. return this;
  22207. };
  22208. /**
  22209. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22210. */
  22211. Mesh.prototype.getAnimatables = function () {
  22212. var results = [];
  22213. if (this.material) {
  22214. results.push(this.material);
  22215. }
  22216. if (this.skeleton) {
  22217. results.push(this.skeleton);
  22218. }
  22219. return results;
  22220. };
  22221. /**
  22222. * Modifies the mesh geometry according to the passed transformation matrix.
  22223. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22224. * The mesh normals are modified accordingly the same transformation.
  22225. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22226. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22227. * Returns the Mesh.
  22228. */
  22229. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22230. // Position
  22231. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22232. return this;
  22233. }
  22234. var submeshes = this.subMeshes.splice(0);
  22235. this._resetPointsArrayCache();
  22236. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22237. var temp = [];
  22238. var index;
  22239. for (index = 0; index < data.length; index += 3) {
  22240. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22241. }
  22242. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22243. // Normals
  22244. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22245. return this;
  22246. }
  22247. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22248. temp = [];
  22249. for (index = 0; index < data.length; index += 3) {
  22250. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22251. }
  22252. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22253. // flip faces?
  22254. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22255. this.flipFaces();
  22256. }
  22257. // Restore submeshes
  22258. this.releaseSubMeshes();
  22259. this.subMeshes = submeshes;
  22260. return this;
  22261. };
  22262. /**
  22263. * Modifies the mesh geometry according to its own current World Matrix.
  22264. * The mesh World Matrix is then reset.
  22265. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22266. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22267. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22268. * Returns the Mesh.
  22269. */
  22270. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22271. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22272. this.scaling.copyFromFloats(1, 1, 1);
  22273. this.position.copyFromFloats(0, 0, 0);
  22274. this.rotation.copyFromFloats(0, 0, 0);
  22275. //only if quaternion is already set
  22276. if (this.rotationQuaternion) {
  22277. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22278. }
  22279. this._worldMatrix = BABYLON.Matrix.Identity();
  22280. return this;
  22281. };
  22282. Object.defineProperty(Mesh.prototype, "_positions", {
  22283. // Cache
  22284. get: function () {
  22285. if (this._geometry) {
  22286. return this._geometry._positions;
  22287. }
  22288. return null;
  22289. },
  22290. enumerable: true,
  22291. configurable: true
  22292. });
  22293. Mesh.prototype._resetPointsArrayCache = function () {
  22294. if (this._geometry) {
  22295. this._geometry._resetPointsArrayCache();
  22296. }
  22297. return this;
  22298. };
  22299. Mesh.prototype._generatePointsArray = function () {
  22300. if (this._geometry) {
  22301. return this._geometry._generatePointsArray();
  22302. }
  22303. return false;
  22304. };
  22305. /**
  22306. * Returns a new Mesh object generated from the current mesh properties.
  22307. * This method must not get confused with createInstance().
  22308. * The parameter `name` is a string, the name given to the new mesh.
  22309. * The optional parameter `newParent` can be any Node object (default `null`).
  22310. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22311. * 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.
  22312. */
  22313. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22314. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22315. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22316. };
  22317. /**
  22318. * Disposes the mesh.
  22319. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22320. */
  22321. Mesh.prototype.dispose = function (doNotRecurse) {
  22322. var _this = this;
  22323. this.morphTargetManager = undefined;
  22324. if (this._geometry) {
  22325. this._geometry.releaseForMesh(this, true);
  22326. }
  22327. // Sources
  22328. var meshes = this.getScene().meshes;
  22329. meshes.forEach(function (mesh) {
  22330. if (mesh._source && mesh._source === _this) {
  22331. mesh._source = null;
  22332. }
  22333. });
  22334. this._source = null;
  22335. // Instances
  22336. if (this._instancesBuffer) {
  22337. this._instancesBuffer.dispose();
  22338. this._instancesBuffer = null;
  22339. }
  22340. while (this.instances.length) {
  22341. this.instances[0].dispose();
  22342. }
  22343. // Highlight layers.
  22344. var highlightLayers = this.getScene().highlightLayers;
  22345. for (var i = 0; i < highlightLayers.length; i++) {
  22346. var highlightLayer = highlightLayers[i];
  22347. if (highlightLayer) {
  22348. highlightLayer.removeMesh(this);
  22349. highlightLayer.removeExcludedMesh(this);
  22350. }
  22351. }
  22352. _super.prototype.dispose.call(this, doNotRecurse);
  22353. };
  22354. /**
  22355. * Modifies the mesh geometry according to a displacement map.
  22356. * 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.
  22357. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22358. * This method returns nothing.
  22359. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22360. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22361. * 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.
  22362. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22363. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22364. *
  22365. * Returns the Mesh.
  22366. */
  22367. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22368. var _this = this;
  22369. var scene = this.getScene();
  22370. var onload = function (img) {
  22371. // Getting height map data
  22372. var canvas = document.createElement("canvas");
  22373. var context = canvas.getContext("2d");
  22374. var heightMapWidth = img.width;
  22375. var heightMapHeight = img.height;
  22376. canvas.width = heightMapWidth;
  22377. canvas.height = heightMapHeight;
  22378. context.drawImage(img, 0, 0);
  22379. // Create VertexData from map data
  22380. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22381. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22382. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22383. //execute success callback, if set
  22384. if (onSuccess) {
  22385. onSuccess(_this);
  22386. }
  22387. };
  22388. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22389. return this;
  22390. };
  22391. /**
  22392. * Modifies the mesh geometry according to a displacementMap buffer.
  22393. * 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.
  22394. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22395. * This method returns nothing.
  22396. * 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.
  22397. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22398. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22399. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22400. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22401. *
  22402. * Returns the Mesh.
  22403. */
  22404. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22405. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22406. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22407. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22408. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22409. return this;
  22410. }
  22411. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22412. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22413. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22414. var position = BABYLON.Vector3.Zero();
  22415. var normal = BABYLON.Vector3.Zero();
  22416. var uv = BABYLON.Vector2.Zero();
  22417. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22418. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22419. for (var index = 0; index < positions.length; index += 3) {
  22420. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22421. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22422. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22423. // Compute height
  22424. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22425. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22426. var pos = (u + v * heightMapWidth) * 4;
  22427. var r = buffer[pos] / 255.0;
  22428. var g = buffer[pos + 1] / 255.0;
  22429. var b = buffer[pos + 2] / 255.0;
  22430. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22431. normal.normalize();
  22432. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22433. position = position.add(normal);
  22434. position.toArray(positions, index);
  22435. }
  22436. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22437. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22438. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22439. return this;
  22440. };
  22441. /**
  22442. * Modify the mesh to get a flat shading rendering.
  22443. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22444. * This method returns the Mesh.
  22445. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22446. */
  22447. Mesh.prototype.convertToFlatShadedMesh = function () {
  22448. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22449. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22450. var kinds = this.getVerticesDataKinds();
  22451. var vbs = [];
  22452. var data = [];
  22453. var newdata = [];
  22454. var updatableNormals = false;
  22455. var kindIndex;
  22456. var kind;
  22457. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22458. kind = kinds[kindIndex];
  22459. var vertexBuffer = this.getVertexBuffer(kind);
  22460. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22461. updatableNormals = vertexBuffer.isUpdatable();
  22462. kinds.splice(kindIndex, 1);
  22463. kindIndex--;
  22464. continue;
  22465. }
  22466. vbs[kind] = vertexBuffer;
  22467. data[kind] = vbs[kind].getData();
  22468. newdata[kind] = [];
  22469. }
  22470. // Save previous submeshes
  22471. var previousSubmeshes = this.subMeshes.slice(0);
  22472. var indices = this.getIndices();
  22473. var totalIndices = this.getTotalIndices();
  22474. // Generating unique vertices per face
  22475. var index;
  22476. for (index = 0; index < totalIndices; index++) {
  22477. var vertexIndex = indices[index];
  22478. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22479. kind = kinds[kindIndex];
  22480. var stride = vbs[kind].getStrideSize();
  22481. for (var offset = 0; offset < stride; offset++) {
  22482. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22483. }
  22484. }
  22485. }
  22486. // Updating faces & normal
  22487. var normals = [];
  22488. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22489. for (index = 0; index < totalIndices; index += 3) {
  22490. indices[index] = index;
  22491. indices[index + 1] = index + 1;
  22492. indices[index + 2] = index + 2;
  22493. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22494. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22495. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22496. var p1p2 = p1.subtract(p2);
  22497. var p3p2 = p3.subtract(p2);
  22498. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22499. // Store same normals for every vertex
  22500. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22501. normals.push(normal.x);
  22502. normals.push(normal.y);
  22503. normals.push(normal.z);
  22504. }
  22505. }
  22506. this.setIndices(indices);
  22507. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22508. // Updating vertex buffers
  22509. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22510. kind = kinds[kindIndex];
  22511. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22512. }
  22513. // Updating submeshes
  22514. this.releaseSubMeshes();
  22515. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22516. var previousOne = previousSubmeshes[submeshIndex];
  22517. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22518. }
  22519. this.synchronizeInstances();
  22520. return this;
  22521. };
  22522. /**
  22523. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22524. * In other words, more vertices, no more indices and a single bigger VBO.
  22525. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22526. * Returns the Mesh.
  22527. */
  22528. Mesh.prototype.convertToUnIndexedMesh = function () {
  22529. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22530. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22531. var kinds = this.getVerticesDataKinds();
  22532. var vbs = [];
  22533. var data = [];
  22534. var newdata = [];
  22535. var updatableNormals = false;
  22536. var kindIndex;
  22537. var kind;
  22538. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22539. kind = kinds[kindIndex];
  22540. var vertexBuffer = this.getVertexBuffer(kind);
  22541. vbs[kind] = vertexBuffer;
  22542. data[kind] = vbs[kind].getData();
  22543. newdata[kind] = [];
  22544. }
  22545. // Save previous submeshes
  22546. var previousSubmeshes = this.subMeshes.slice(0);
  22547. var indices = this.getIndices();
  22548. var totalIndices = this.getTotalIndices();
  22549. // Generating unique vertices per face
  22550. var index;
  22551. for (index = 0; index < totalIndices; index++) {
  22552. var vertexIndex = indices[index];
  22553. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22554. kind = kinds[kindIndex];
  22555. var stride = vbs[kind].getStrideSize();
  22556. for (var offset = 0; offset < stride; offset++) {
  22557. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22558. }
  22559. }
  22560. }
  22561. // Updating indices
  22562. for (index = 0; index < totalIndices; index += 3) {
  22563. indices[index] = index;
  22564. indices[index + 1] = index + 1;
  22565. indices[index + 2] = index + 2;
  22566. }
  22567. this.setIndices(indices);
  22568. // Updating vertex buffers
  22569. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22570. kind = kinds[kindIndex];
  22571. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22572. }
  22573. // Updating submeshes
  22574. this.releaseSubMeshes();
  22575. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22576. var previousOne = previousSubmeshes[submeshIndex];
  22577. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22578. }
  22579. this._unIndexed = true;
  22580. this.synchronizeInstances();
  22581. return this;
  22582. };
  22583. /**
  22584. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22585. * This method returns the Mesh.
  22586. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22587. */
  22588. Mesh.prototype.flipFaces = function (flipNormals) {
  22589. if (flipNormals === void 0) { flipNormals = false; }
  22590. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22591. var i;
  22592. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22593. for (i = 0; i < vertex_data.normals.length; i++) {
  22594. vertex_data.normals[i] *= -1;
  22595. }
  22596. }
  22597. var temp;
  22598. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22599. // reassign indices
  22600. temp = vertex_data.indices[i + 1];
  22601. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22602. vertex_data.indices[i + 2] = temp;
  22603. }
  22604. vertex_data.applyToMesh(this);
  22605. return this;
  22606. };
  22607. // Instances
  22608. /**
  22609. * Creates a new InstancedMesh object from the mesh model.
  22610. * An instance shares the same properties and the same material than its model.
  22611. * Only these properties of each instance can then be set individually :
  22612. * - position
  22613. * - rotation
  22614. * - rotationQuaternion
  22615. * - setPivotMatrix
  22616. * - scaling
  22617. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22618. * Warning : this method is not supported for Line mesh and LineSystem
  22619. */
  22620. Mesh.prototype.createInstance = function (name) {
  22621. return new BABYLON.InstancedMesh(name, this);
  22622. };
  22623. /**
  22624. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22625. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22626. * This method returns the Mesh.
  22627. */
  22628. Mesh.prototype.synchronizeInstances = function () {
  22629. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22630. var instance = this.instances[instanceIndex];
  22631. instance._syncSubMeshes();
  22632. }
  22633. return this;
  22634. };
  22635. /**
  22636. * Simplify the mesh according to the given array of settings.
  22637. * Function will return immediately and will simplify async. It returns the Mesh.
  22638. * @param settings a collection of simplification settings.
  22639. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22640. * @param type the type of simplification to run.
  22641. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22642. */
  22643. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22644. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22645. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22646. this.getScene().simplificationQueue.addTask({
  22647. settings: settings,
  22648. parallelProcessing: parallelProcessing,
  22649. mesh: this,
  22650. simplificationType: simplificationType,
  22651. successCallback: successCallback
  22652. });
  22653. return this;
  22654. };
  22655. /**
  22656. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22657. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22658. * This should be used together with the simplification to avoid disappearing triangles.
  22659. * Returns the Mesh.
  22660. * @param successCallback an optional success callback to be called after the optimization finished.
  22661. */
  22662. Mesh.prototype.optimizeIndices = function (successCallback) {
  22663. var _this = this;
  22664. var indices = this.getIndices();
  22665. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22666. var vectorPositions = [];
  22667. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22668. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22669. }
  22670. var dupes = [];
  22671. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22672. var realPos = vectorPositions.length - 1 - iteration;
  22673. var testedPosition = vectorPositions[realPos];
  22674. for (var j = 0; j < realPos; ++j) {
  22675. var againstPosition = vectorPositions[j];
  22676. if (testedPosition.equals(againstPosition)) {
  22677. dupes[realPos] = j;
  22678. break;
  22679. }
  22680. }
  22681. }, function () {
  22682. for (var i = 0; i < indices.length; ++i) {
  22683. indices[i] = dupes[indices[i]] || indices[i];
  22684. }
  22685. //indices are now reordered
  22686. var originalSubMeshes = _this.subMeshes.slice(0);
  22687. _this.setIndices(indices);
  22688. _this.subMeshes = originalSubMeshes;
  22689. if (successCallback) {
  22690. successCallback(_this);
  22691. }
  22692. });
  22693. return this;
  22694. };
  22695. Mesh.prototype.serialize = function (serializationObject) {
  22696. serializationObject.name = this.name;
  22697. serializationObject.id = this.id;
  22698. serializationObject.type = this.getClassName();
  22699. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22700. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22701. }
  22702. serializationObject.position = this.position.asArray();
  22703. if (this.rotationQuaternion) {
  22704. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22705. }
  22706. else if (this.rotation) {
  22707. serializationObject.rotation = this.rotation.asArray();
  22708. }
  22709. serializationObject.scaling = this.scaling.asArray();
  22710. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22711. serializationObject.isEnabled = this.isEnabled();
  22712. serializationObject.isVisible = this.isVisible;
  22713. serializationObject.infiniteDistance = this.infiniteDistance;
  22714. serializationObject.pickable = this.isPickable;
  22715. serializationObject.receiveShadows = this.receiveShadows;
  22716. serializationObject.billboardMode = this.billboardMode;
  22717. serializationObject.visibility = this.visibility;
  22718. serializationObject.checkCollisions = this.checkCollisions;
  22719. serializationObject.isBlocker = this.isBlocker;
  22720. // Parent
  22721. if (this.parent) {
  22722. serializationObject.parentId = this.parent.id;
  22723. }
  22724. // Geometry
  22725. var geometry = this._geometry;
  22726. if (geometry) {
  22727. var geometryId = geometry.id;
  22728. serializationObject.geometryId = geometryId;
  22729. // SubMeshes
  22730. serializationObject.subMeshes = [];
  22731. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22732. var subMesh = this.subMeshes[subIndex];
  22733. serializationObject.subMeshes.push({
  22734. materialIndex: subMesh.materialIndex,
  22735. verticesStart: subMesh.verticesStart,
  22736. verticesCount: subMesh.verticesCount,
  22737. indexStart: subMesh.indexStart,
  22738. indexCount: subMesh.indexCount
  22739. });
  22740. }
  22741. }
  22742. // Material
  22743. if (this.material) {
  22744. serializationObject.materialId = this.material.id;
  22745. }
  22746. else {
  22747. this.material = null;
  22748. }
  22749. // Morph targets
  22750. if (this.morphTargetManager) {
  22751. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22752. }
  22753. // Skeleton
  22754. if (this.skeleton) {
  22755. serializationObject.skeletonId = this.skeleton.id;
  22756. }
  22757. // Physics
  22758. //TODO implement correct serialization for physics impostors.
  22759. if (this.getPhysicsImpostor()) {
  22760. var impostor = this.getPhysicsImpostor();
  22761. serializationObject.physicsMass = impostor.getParam("mass");
  22762. serializationObject.physicsFriction = impostor.getParam("friction");
  22763. serializationObject.physicsRestitution = impostor.getParam("mass");
  22764. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22765. }
  22766. // Metadata
  22767. if (this.metadata) {
  22768. serializationObject.metadata = this.metadata;
  22769. }
  22770. // Instances
  22771. serializationObject.instances = [];
  22772. for (var index = 0; index < this.instances.length; index++) {
  22773. var instance = this.instances[index];
  22774. var serializationInstance = {
  22775. name: instance.name,
  22776. position: instance.position.asArray(),
  22777. scaling: instance.scaling.asArray()
  22778. };
  22779. if (instance.rotationQuaternion) {
  22780. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22781. }
  22782. else if (instance.rotation) {
  22783. serializationInstance.rotation = instance.rotation.asArray();
  22784. }
  22785. serializationObject.instances.push(serializationInstance);
  22786. // Animations
  22787. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22788. serializationInstance.ranges = instance.serializeAnimationRanges();
  22789. }
  22790. //
  22791. // Animations
  22792. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22793. serializationObject.ranges = this.serializeAnimationRanges();
  22794. // Layer mask
  22795. serializationObject.layerMask = this.layerMask;
  22796. // Alpha
  22797. serializationObject.alphaIndex = this.alphaIndex;
  22798. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22799. // Overlay
  22800. serializationObject.overlayAlpha = this.overlayAlpha;
  22801. serializationObject.overlayColor = this.overlayColor.asArray();
  22802. serializationObject.renderOverlay = this.renderOverlay;
  22803. // Fog
  22804. serializationObject.applyFog = this.applyFog;
  22805. // Action Manager
  22806. if (this.actionManager) {
  22807. serializationObject.actions = this.actionManager.serialize(this.name);
  22808. }
  22809. };
  22810. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22811. if (!this.geometry) {
  22812. return;
  22813. }
  22814. this._markSubMeshesAsAttributesDirty();
  22815. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22816. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22817. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22818. this.morphTargetManager = undefined;
  22819. return;
  22820. }
  22821. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22822. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22823. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22824. if (morphTarget.hasNormals) {
  22825. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22826. }
  22827. if (morphTarget.hasTangents) {
  22828. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22829. }
  22830. }
  22831. }
  22832. else {
  22833. var index = 0;
  22834. // Positions
  22835. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22836. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22837. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22838. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22839. }
  22840. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22841. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22842. }
  22843. index++;
  22844. }
  22845. }
  22846. };
  22847. // Statics
  22848. /**
  22849. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22850. * The parameter `parsedMesh` is the mesh to be copied.
  22851. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22852. */
  22853. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22854. var mesh;
  22855. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22856. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22857. }
  22858. else {
  22859. mesh = new Mesh(parsedMesh.name, scene);
  22860. }
  22861. mesh.id = parsedMesh.id;
  22862. if (BABYLON.Tags) {
  22863. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22864. }
  22865. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22866. if (parsedMesh.metadata !== undefined) {
  22867. mesh.metadata = parsedMesh.metadata;
  22868. }
  22869. if (parsedMesh.rotationQuaternion) {
  22870. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22871. }
  22872. else if (parsedMesh.rotation) {
  22873. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22874. }
  22875. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22876. if (parsedMesh.localMatrix) {
  22877. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22878. }
  22879. else if (parsedMesh.pivotMatrix) {
  22880. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22881. }
  22882. mesh.setEnabled(parsedMesh.isEnabled);
  22883. mesh.isVisible = parsedMesh.isVisible;
  22884. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22885. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22886. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22887. if (parsedMesh.applyFog !== undefined) {
  22888. mesh.applyFog = parsedMesh.applyFog;
  22889. }
  22890. if (parsedMesh.pickable !== undefined) {
  22891. mesh.isPickable = parsedMesh.pickable;
  22892. }
  22893. if (parsedMesh.alphaIndex !== undefined) {
  22894. mesh.alphaIndex = parsedMesh.alphaIndex;
  22895. }
  22896. mesh.receiveShadows = parsedMesh.receiveShadows;
  22897. mesh.billboardMode = parsedMesh.billboardMode;
  22898. if (parsedMesh.visibility !== undefined) {
  22899. mesh.visibility = parsedMesh.visibility;
  22900. }
  22901. mesh.checkCollisions = parsedMesh.checkCollisions;
  22902. if (parsedMesh.isBlocker !== undefined) {
  22903. mesh.isBlocker = parsedMesh.isBlocker;
  22904. }
  22905. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22906. // freezeWorldMatrix
  22907. if (parsedMesh.freezeWorldMatrix) {
  22908. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22909. }
  22910. // Parent
  22911. if (parsedMesh.parentId) {
  22912. mesh._waitingParentId = parsedMesh.parentId;
  22913. }
  22914. // Actions
  22915. if (parsedMesh.actions !== undefined) {
  22916. mesh._waitingActions = parsedMesh.actions;
  22917. }
  22918. // Overlay
  22919. if (parsedMesh.overlayAlpha !== undefined) {
  22920. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22921. }
  22922. if (parsedMesh.overlayColor !== undefined) {
  22923. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22924. }
  22925. if (parsedMesh.renderOverlay !== undefined) {
  22926. mesh.renderOverlay = parsedMesh.renderOverlay;
  22927. }
  22928. // Geometry
  22929. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22930. if (parsedMesh.delayLoadingFile) {
  22931. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22932. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22933. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22934. if (parsedMesh._binaryInfo) {
  22935. mesh._binaryInfo = parsedMesh._binaryInfo;
  22936. }
  22937. mesh._delayInfo = [];
  22938. if (parsedMesh.hasUVs) {
  22939. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22940. }
  22941. if (parsedMesh.hasUVs2) {
  22942. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22943. }
  22944. if (parsedMesh.hasUVs3) {
  22945. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22946. }
  22947. if (parsedMesh.hasUVs4) {
  22948. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22949. }
  22950. if (parsedMesh.hasUVs5) {
  22951. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22952. }
  22953. if (parsedMesh.hasUVs6) {
  22954. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22955. }
  22956. if (parsedMesh.hasColors) {
  22957. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22958. }
  22959. if (parsedMesh.hasMatricesIndices) {
  22960. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22961. }
  22962. if (parsedMesh.hasMatricesWeights) {
  22963. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22964. }
  22965. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22966. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22967. mesh._checkDelayState();
  22968. }
  22969. }
  22970. else {
  22971. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22972. }
  22973. // Material
  22974. if (parsedMesh.materialId) {
  22975. mesh.setMaterialByID(parsedMesh.materialId);
  22976. }
  22977. else {
  22978. mesh.material = null;
  22979. }
  22980. // Morph targets
  22981. if (parsedMesh.morphTargetManagerId > -1) {
  22982. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22983. }
  22984. // Skeleton
  22985. if (parsedMesh.skeletonId > -1) {
  22986. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22987. if (parsedMesh.numBoneInfluencers) {
  22988. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22989. }
  22990. }
  22991. // Animations
  22992. if (parsedMesh.animations) {
  22993. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22994. var parsedAnimation = parsedMesh.animations[animationIndex];
  22995. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22996. }
  22997. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22998. }
  22999. if (parsedMesh.autoAnimate) {
  23000. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23001. }
  23002. // Layer Mask
  23003. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23004. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23005. }
  23006. else {
  23007. mesh.layerMask = 0x0FFFFFFF;
  23008. }
  23009. // Physics
  23010. if (parsedMesh.physicsImpostor) {
  23011. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23012. mass: parsedMesh.physicsMass,
  23013. friction: parsedMesh.physicsFriction,
  23014. restitution: parsedMesh.physicsRestitution
  23015. }, scene);
  23016. }
  23017. // Instances
  23018. if (parsedMesh.instances) {
  23019. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23020. var parsedInstance = parsedMesh.instances[index];
  23021. var instance = mesh.createInstance(parsedInstance.name);
  23022. if (BABYLON.Tags) {
  23023. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23024. }
  23025. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23026. if (parsedInstance.parentId) {
  23027. instance._waitingParentId = parsedInstance.parentId;
  23028. }
  23029. if (parsedInstance.rotationQuaternion) {
  23030. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23031. }
  23032. else if (parsedInstance.rotation) {
  23033. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23034. }
  23035. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23036. instance.checkCollisions = mesh.checkCollisions;
  23037. if (parsedMesh.animations) {
  23038. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23039. parsedAnimation = parsedMesh.animations[animationIndex];
  23040. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23041. }
  23042. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23043. }
  23044. }
  23045. }
  23046. return mesh;
  23047. };
  23048. /**
  23049. * Creates a ribbon mesh.
  23050. * Please consider using the same method from the MeshBuilder class instead.
  23051. * 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.
  23052. *
  23053. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23054. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23055. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23056. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23057. * 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.
  23058. * 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.
  23059. * 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
  23060. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23061. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23062. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23063. */
  23064. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23065. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23066. pathArray: pathArray,
  23067. closeArray: closeArray,
  23068. closePath: closePath,
  23069. offset: offset,
  23070. updatable: updatable,
  23071. sideOrientation: sideOrientation,
  23072. instance: instance
  23073. }, scene);
  23074. };
  23075. /**
  23076. * Creates a plane polygonal mesh. By default, this is a disc.
  23077. * Please consider using the same method from the MeshBuilder class instead.
  23078. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23079. * 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.
  23080. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23081. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23082. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23083. */
  23084. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23085. var options = {
  23086. radius: radius,
  23087. tessellation: tessellation,
  23088. sideOrientation: sideOrientation,
  23089. updatable: updatable
  23090. };
  23091. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23092. };
  23093. /**
  23094. * Creates a box mesh.
  23095. * Please consider using the same method from the MeshBuilder class instead.
  23096. * The parameter `size` sets the size (float) of each box side (default 1).
  23097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23098. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23100. */
  23101. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23102. var options = {
  23103. size: size,
  23104. sideOrientation: sideOrientation,
  23105. updatable: updatable
  23106. };
  23107. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23108. };
  23109. /**
  23110. * Creates a sphere mesh.
  23111. * Please consider using the same method from the MeshBuilder class instead.
  23112. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23113. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23114. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23115. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23116. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23117. */
  23118. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23119. var options = {
  23120. segments: segments,
  23121. diameterX: diameter,
  23122. diameterY: diameter,
  23123. diameterZ: diameter,
  23124. sideOrientation: sideOrientation,
  23125. updatable: updatable
  23126. };
  23127. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23128. };
  23129. /**
  23130. * Creates a cylinder or a cone mesh.
  23131. * Please consider using the same method from the MeshBuilder class instead.
  23132. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23133. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23134. * 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.
  23135. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23136. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23137. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23138. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23139. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23140. */
  23141. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23142. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23143. if (scene !== undefined) {
  23144. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23145. updatable = scene;
  23146. }
  23147. scene = subdivisions;
  23148. subdivisions = 1;
  23149. }
  23150. var options = {
  23151. height: height,
  23152. diameterTop: diameterTop,
  23153. diameterBottom: diameterBottom,
  23154. tessellation: tessellation,
  23155. subdivisions: subdivisions,
  23156. sideOrientation: sideOrientation,
  23157. updatable: updatable
  23158. };
  23159. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23160. };
  23161. // Torus (Code from SharpDX.org)
  23162. /**
  23163. * Creates a torus mesh.
  23164. * Please consider using the same method from the MeshBuilder class instead.
  23165. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23166. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23167. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23168. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23169. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23170. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23171. */
  23172. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23173. var options = {
  23174. diameter: diameter,
  23175. thickness: thickness,
  23176. tessellation: tessellation,
  23177. sideOrientation: sideOrientation,
  23178. updatable: updatable
  23179. };
  23180. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23181. };
  23182. /**
  23183. * Creates a torus knot mesh.
  23184. * Please consider using the same method from the MeshBuilder class instead.
  23185. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23186. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23187. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23188. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23189. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23190. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23192. */
  23193. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23194. var options = {
  23195. radius: radius,
  23196. tube: tube,
  23197. radialSegments: radialSegments,
  23198. tubularSegments: tubularSegments,
  23199. p: p,
  23200. q: q,
  23201. sideOrientation: sideOrientation,
  23202. updatable: updatable
  23203. };
  23204. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23205. };
  23206. /**
  23207. * Creates a line mesh.
  23208. * Please consider using the same method from the MeshBuilder class instead.
  23209. * 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.
  23210. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23211. * The parameter `points` is an array successive Vector3.
  23212. * 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
  23213. * When updating an instance, remember that only point positions can change, not the number of points.
  23214. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23215. */
  23216. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23217. var options = {
  23218. points: points,
  23219. updatable: updatable,
  23220. instance: instance
  23221. };
  23222. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23223. };
  23224. /**
  23225. * Creates a dashed line mesh.
  23226. * Please consider using the same method from the MeshBuilder class instead.
  23227. * 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.
  23228. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23229. * The parameter `points` is an array successive Vector3.
  23230. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23231. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23232. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23233. * 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
  23234. * When updating an instance, remember that only point positions can change, not the number of points.
  23235. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23236. */
  23237. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23238. var options = {
  23239. points: points,
  23240. dashSize: dashSize,
  23241. gapSize: gapSize,
  23242. dashNb: dashNb,
  23243. updatable: updatable,
  23244. instance: instance
  23245. };
  23246. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23247. };
  23248. /**
  23249. * Creates a polygon mesh.
  23250. * Please consider using the same method from the MeshBuilder class instead.
  23251. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23252. * 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.
  23253. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23254. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23255. * Remember you can only change the shape positions, not their number when updating a polygon.
  23256. */
  23257. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23258. var options = {
  23259. shape: shape,
  23260. holes: holes,
  23261. updatable: updatable,
  23262. sideOrientation: sideOrientation
  23263. };
  23264. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23265. };
  23266. /**
  23267. * Creates an extruded polygon mesh, with depth in the Y direction.
  23268. * Please consider using the same method from the MeshBuilder class instead.
  23269. */
  23270. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23271. var options = {
  23272. shape: shape,
  23273. holes: holes,
  23274. depth: depth,
  23275. updatable: updatable,
  23276. sideOrientation: sideOrientation
  23277. };
  23278. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23279. };
  23280. /**
  23281. * Creates an extruded shape mesh.
  23282. * 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.
  23283. * Please consider using the same method from the MeshBuilder class instead.
  23284. *
  23285. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23286. * 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
  23287. * extruded along the Z axis.
  23288. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23289. * 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.
  23290. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23291. * 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
  23292. * 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
  23293. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23294. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23295. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23296. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23297. */
  23298. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23299. var options = {
  23300. shape: shape,
  23301. path: path,
  23302. scale: scale,
  23303. rotation: rotation,
  23304. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23305. sideOrientation: sideOrientation,
  23306. instance: instance,
  23307. updatable: updatable
  23308. };
  23309. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23310. };
  23311. /**
  23312. * Creates an custom extruded shape mesh.
  23313. * 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.
  23314. * Please consider using the same method from the MeshBuilder class instead.
  23315. *
  23316. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23317. * 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
  23318. * extruded along the Z axis.
  23319. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23320. * 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
  23321. * and the distance of this point from the begining of the path :
  23322. * ```javascript
  23323. * var rotationFunction = function(i, distance) {
  23324. * // do things
  23325. * return rotationValue; }
  23326. * ```
  23327. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23328. * 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
  23329. * and the distance of this point from the begining of the path :
  23330. * ```javascript
  23331. * var scaleFunction = function(i, distance) {
  23332. * // do things
  23333. * return scaleValue;}
  23334. * ```
  23335. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23336. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23337. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23338. * 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
  23339. * 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
  23340. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23342. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23344. */
  23345. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23346. var options = {
  23347. shape: shape,
  23348. path: path,
  23349. scaleFunction: scaleFunction,
  23350. rotationFunction: rotationFunction,
  23351. ribbonCloseArray: ribbonCloseArray,
  23352. ribbonClosePath: ribbonClosePath,
  23353. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23354. sideOrientation: sideOrientation,
  23355. instance: instance,
  23356. updatable: updatable
  23357. };
  23358. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23359. };
  23360. /**
  23361. * Creates lathe mesh.
  23362. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23363. * Please consider using the same method from the MeshBuilder class instead.
  23364. * 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
  23365. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23366. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23367. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23368. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23369. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23370. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23371. */
  23372. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23373. var options = {
  23374. shape: shape,
  23375. radius: radius,
  23376. tessellation: tessellation,
  23377. sideOrientation: sideOrientation,
  23378. updatable: updatable
  23379. };
  23380. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23381. };
  23382. /**
  23383. * Creates a plane mesh.
  23384. * Please consider using the same method from the MeshBuilder class instead.
  23385. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23386. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23387. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23388. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23389. */
  23390. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23391. var options = {
  23392. size: size,
  23393. width: size,
  23394. height: size,
  23395. sideOrientation: sideOrientation,
  23396. updatable: updatable
  23397. };
  23398. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23399. };
  23400. /**
  23401. * Creates a ground mesh.
  23402. * Please consider using the same method from the MeshBuilder class instead.
  23403. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23404. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23405. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23406. */
  23407. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23408. var options = {
  23409. width: width,
  23410. height: height,
  23411. subdivisions: subdivisions,
  23412. updatable: updatable
  23413. };
  23414. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23415. };
  23416. /**
  23417. * Creates a tiled ground mesh.
  23418. * Please consider using the same method from the MeshBuilder class instead.
  23419. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23420. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23421. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23422. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23423. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23424. * numbers of subdivisions on the ground width and height of each tile.
  23425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23426. */
  23427. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23428. var options = {
  23429. xmin: xmin,
  23430. zmin: zmin,
  23431. xmax: xmax,
  23432. zmax: zmax,
  23433. subdivisions: subdivisions,
  23434. precision: precision,
  23435. updatable: updatable
  23436. };
  23437. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23438. };
  23439. /**
  23440. * Creates a ground mesh from a height map.
  23441. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23442. * Please consider using the same method from the MeshBuilder class instead.
  23443. * The parameter `url` sets the URL of the height map image resource.
  23444. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23445. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23446. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23447. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23448. * 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).
  23449. * This function is passed the newly built mesh :
  23450. * ```javascript
  23451. * function(mesh) { // do things
  23452. * return; }
  23453. * ```
  23454. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23455. */
  23456. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23457. var options = {
  23458. width: width,
  23459. height: height,
  23460. subdivisions: subdivisions,
  23461. minHeight: minHeight,
  23462. maxHeight: maxHeight,
  23463. updatable: updatable,
  23464. onReady: onReady
  23465. };
  23466. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23467. };
  23468. /**
  23469. * Creates a tube mesh.
  23470. * 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.
  23471. * Please consider using the same method from the MeshBuilder class instead.
  23472. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23473. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23474. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23475. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23476. * 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.
  23477. * It must return a radius value (positive float) :
  23478. * ```javascript
  23479. * var radiusFunction = function(i, distance) {
  23480. * // do things
  23481. * return radius; }
  23482. * ```
  23483. * 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
  23484. * 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
  23485. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23486. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23487. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23488. */
  23489. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23490. var options = {
  23491. path: path,
  23492. radius: radius,
  23493. tessellation: tessellation,
  23494. radiusFunction: radiusFunction,
  23495. arc: 1,
  23496. cap: cap,
  23497. updatable: updatable,
  23498. sideOrientation: sideOrientation,
  23499. instance: instance
  23500. };
  23501. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23502. };
  23503. /**
  23504. * Creates a polyhedron mesh.
  23505. * Please consider using the same method from the MeshBuilder class instead.
  23506. * 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
  23507. * to choose the wanted type.
  23508. * The parameter `size` (positive float, default 1) sets the polygon size.
  23509. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23510. * 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`.
  23511. * 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
  23512. * 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)`).
  23513. * 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
  23514. * 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.
  23515. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23516. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23518. */
  23519. Mesh.CreatePolyhedron = function (name, options, scene) {
  23520. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23521. };
  23522. /**
  23523. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23524. * Please consider using the same method from the MeshBuilder class instead.
  23525. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23526. * 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`).
  23527. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23528. * 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.
  23529. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23530. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23531. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23532. */
  23533. Mesh.CreateIcoSphere = function (name, options, scene) {
  23534. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23535. };
  23536. /**
  23537. * Creates a decal mesh.
  23538. * Please consider using the same method from the MeshBuilder class instead.
  23539. * 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.
  23540. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23541. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23542. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23543. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23544. */
  23545. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23546. var options = {
  23547. position: position,
  23548. normal: normal,
  23549. size: size,
  23550. angle: angle
  23551. };
  23552. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23553. };
  23554. // Skeletons
  23555. /**
  23556. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23557. */
  23558. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23559. var source;
  23560. if (!this._sourcePositions) {
  23561. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23562. this._sourcePositions = new Float32Array(source);
  23563. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23564. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23565. }
  23566. }
  23567. return this._sourcePositions;
  23568. };
  23569. /**
  23570. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23571. */
  23572. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23573. var source;
  23574. if (!this._sourceNormals) {
  23575. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23576. this._sourceNormals = new Float32Array(source);
  23577. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23578. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23579. }
  23580. }
  23581. return this._sourceNormals;
  23582. };
  23583. /**
  23584. * Updates the vertex buffer by applying transformation from the bones.
  23585. * Returns the Mesh.
  23586. *
  23587. * @param {skeleton} skeleton to apply
  23588. */
  23589. Mesh.prototype.applySkeleton = function (skeleton) {
  23590. if (!this.geometry) {
  23591. return this;
  23592. }
  23593. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23594. return this;
  23595. }
  23596. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23597. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23598. return this;
  23599. }
  23600. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23601. return this;
  23602. }
  23603. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23604. return this;
  23605. }
  23606. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23607. return this;
  23608. }
  23609. if (!this._sourcePositions) {
  23610. var submeshes = this.subMeshes.slice();
  23611. this.setPositionsForCPUSkinning();
  23612. this.subMeshes = submeshes;
  23613. }
  23614. if (!this._sourceNormals) {
  23615. this.setNormalsForCPUSkinning();
  23616. }
  23617. // positionsData checks for not being Float32Array will only pass at most once
  23618. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23619. if (!(positionsData instanceof Float32Array)) {
  23620. positionsData = new Float32Array(positionsData);
  23621. }
  23622. // normalsData checks for not being Float32Array will only pass at most once
  23623. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23624. if (!(normalsData instanceof Float32Array)) {
  23625. normalsData = new Float32Array(normalsData);
  23626. }
  23627. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23628. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23629. var needExtras = this.numBoneInfluencers > 4;
  23630. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23631. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23632. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23633. var tempVector3 = BABYLON.Vector3.Zero();
  23634. var finalMatrix = new BABYLON.Matrix();
  23635. var tempMatrix = new BABYLON.Matrix();
  23636. var matWeightIdx = 0;
  23637. var inf;
  23638. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23639. var weight;
  23640. for (inf = 0; inf < 4; inf++) {
  23641. weight = matricesWeightsData[matWeightIdx + inf];
  23642. if (weight > 0) {
  23643. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23644. finalMatrix.addToSelf(tempMatrix);
  23645. }
  23646. else
  23647. break;
  23648. }
  23649. if (needExtras) {
  23650. for (inf = 0; inf < 4; inf++) {
  23651. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23652. if (weight > 0) {
  23653. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23654. finalMatrix.addToSelf(tempMatrix);
  23655. }
  23656. else
  23657. break;
  23658. }
  23659. }
  23660. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23661. tempVector3.toArray(positionsData, index);
  23662. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23663. tempVector3.toArray(normalsData, index);
  23664. finalMatrix.reset();
  23665. }
  23666. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23667. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23668. return this;
  23669. };
  23670. // Tools
  23671. /**
  23672. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23673. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23674. */
  23675. Mesh.MinMax = function (meshes) {
  23676. var minVector = null;
  23677. var maxVector = null;
  23678. meshes.forEach(function (mesh, index, array) {
  23679. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23680. if (!minVector) {
  23681. minVector = boundingBox.minimumWorld;
  23682. maxVector = boundingBox.maximumWorld;
  23683. }
  23684. else {
  23685. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23686. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23687. }
  23688. });
  23689. return {
  23690. min: minVector,
  23691. max: maxVector
  23692. };
  23693. };
  23694. /**
  23695. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23696. */
  23697. Mesh.Center = function (meshesOrMinMaxVector) {
  23698. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23699. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23700. };
  23701. /**
  23702. * Merge the array of meshes into a single mesh for performance reasons.
  23703. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23704. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23705. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23706. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23707. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23708. */
  23709. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23710. if (disposeSource === void 0) { disposeSource = true; }
  23711. var index;
  23712. if (!allow32BitsIndices) {
  23713. var totalVertices = 0;
  23714. // Counting vertices
  23715. for (index = 0; index < meshes.length; index++) {
  23716. if (meshes[index]) {
  23717. totalVertices += meshes[index].getTotalVertices();
  23718. if (totalVertices > 65536) {
  23719. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23720. return null;
  23721. }
  23722. }
  23723. }
  23724. }
  23725. // Merge
  23726. var vertexData;
  23727. var otherVertexData;
  23728. var indiceArray = new Array();
  23729. var source;
  23730. for (index = 0; index < meshes.length; index++) {
  23731. if (meshes[index]) {
  23732. meshes[index].computeWorldMatrix(true);
  23733. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23734. otherVertexData.transform(meshes[index].getWorldMatrix());
  23735. if (vertexData) {
  23736. vertexData.merge(otherVertexData);
  23737. }
  23738. else {
  23739. vertexData = otherVertexData;
  23740. source = meshes[index];
  23741. }
  23742. if (subdivideWithSubMeshes) {
  23743. indiceArray.push(meshes[index].getTotalIndices());
  23744. }
  23745. }
  23746. }
  23747. if (!meshSubclass) {
  23748. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23749. }
  23750. vertexData.applyToMesh(meshSubclass);
  23751. // Setting properties
  23752. meshSubclass.material = source.material;
  23753. meshSubclass.checkCollisions = source.checkCollisions;
  23754. // Cleaning
  23755. if (disposeSource) {
  23756. for (index = 0; index < meshes.length; index++) {
  23757. if (meshes[index]) {
  23758. meshes[index].dispose();
  23759. }
  23760. }
  23761. }
  23762. // Subdivide
  23763. if (subdivideWithSubMeshes) {
  23764. //-- Suppresions du submesh global
  23765. meshSubclass.releaseSubMeshes();
  23766. index = 0;
  23767. var offset = 0;
  23768. //-- aplique la subdivision en fonction du tableau d'indices
  23769. while (index < indiceArray.length) {
  23770. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23771. offset += indiceArray[index];
  23772. index++;
  23773. }
  23774. }
  23775. return meshSubclass;
  23776. };
  23777. // Consts
  23778. Mesh._FRONTSIDE = 0;
  23779. Mesh._BACKSIDE = 1;
  23780. Mesh._DOUBLESIDE = 2;
  23781. Mesh._DEFAULTSIDE = 0;
  23782. Mesh._NO_CAP = 0;
  23783. Mesh._CAP_START = 1;
  23784. Mesh._CAP_END = 2;
  23785. Mesh._CAP_ALL = 3;
  23786. return Mesh;
  23787. }(BABYLON.AbstractMesh));
  23788. BABYLON.Mesh = Mesh;
  23789. })(BABYLON || (BABYLON = {}));
  23790. //# sourceMappingURL=babylon.mesh.js.map
  23791. var BABYLON;
  23792. (function (BABYLON) {
  23793. var BaseSubMesh = (function () {
  23794. function BaseSubMesh() {
  23795. }
  23796. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23797. get: function () {
  23798. return this._materialEffect;
  23799. },
  23800. enumerable: true,
  23801. configurable: true
  23802. });
  23803. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23804. if (this._materialEffect === effect) {
  23805. if (!effect) {
  23806. this._materialDefines = undefined;
  23807. }
  23808. return;
  23809. }
  23810. this._materialDefines = defines;
  23811. this._materialEffect = effect;
  23812. };
  23813. return BaseSubMesh;
  23814. }());
  23815. BABYLON.BaseSubMesh = BaseSubMesh;
  23816. var SubMesh = (function (_super) {
  23817. __extends(SubMesh, _super);
  23818. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23819. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23820. var _this = _super.call(this) || this;
  23821. _this.materialIndex = materialIndex;
  23822. _this.verticesStart = verticesStart;
  23823. _this.verticesCount = verticesCount;
  23824. _this.indexStart = indexStart;
  23825. _this.indexCount = indexCount;
  23826. _this._renderId = 0;
  23827. _this._mesh = mesh;
  23828. _this._renderingMesh = renderingMesh || mesh;
  23829. mesh.subMeshes.push(_this);
  23830. _this._trianglePlanes = [];
  23831. _this._id = mesh.subMeshes.length - 1;
  23832. if (createBoundingBox) {
  23833. _this.refreshBoundingInfo();
  23834. mesh.computeWorldMatrix(true);
  23835. }
  23836. return _this;
  23837. }
  23838. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23839. get: function () {
  23840. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23841. },
  23842. enumerable: true,
  23843. configurable: true
  23844. });
  23845. /**
  23846. * Returns the submesh BoudingInfo object.
  23847. */
  23848. SubMesh.prototype.getBoundingInfo = function () {
  23849. if (this.IsGlobal) {
  23850. return this._mesh.getBoundingInfo();
  23851. }
  23852. return this._boundingInfo;
  23853. };
  23854. /**
  23855. * Sets the submesh BoundingInfo.
  23856. * Return the SubMesh.
  23857. */
  23858. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23859. this._boundingInfo = boundingInfo;
  23860. return this;
  23861. };
  23862. /**
  23863. * Returns the mesh of the current submesh.
  23864. */
  23865. SubMesh.prototype.getMesh = function () {
  23866. return this._mesh;
  23867. };
  23868. /**
  23869. * Returns the rendering mesh of the submesh.
  23870. */
  23871. SubMesh.prototype.getRenderingMesh = function () {
  23872. return this._renderingMesh;
  23873. };
  23874. /**
  23875. * Returns the submesh material.
  23876. */
  23877. SubMesh.prototype.getMaterial = function () {
  23878. var rootMaterial = this._renderingMesh.material;
  23879. if (rootMaterial && rootMaterial.getSubMaterial) {
  23880. var multiMaterial = rootMaterial;
  23881. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23882. if (this._currentMaterial !== effectiveMaterial) {
  23883. this._currentMaterial = effectiveMaterial;
  23884. this._materialDefines = undefined;
  23885. }
  23886. return effectiveMaterial;
  23887. }
  23888. if (!rootMaterial) {
  23889. return this._mesh.getScene().defaultMaterial;
  23890. }
  23891. return rootMaterial;
  23892. };
  23893. // Methods
  23894. /**
  23895. * Sets a new updated BoundingInfo object to the submesh.
  23896. * Returns the SubMesh.
  23897. */
  23898. SubMesh.prototype.refreshBoundingInfo = function () {
  23899. this._lastColliderWorldVertices = null;
  23900. if (this.IsGlobal) {
  23901. return;
  23902. }
  23903. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23904. if (!data) {
  23905. this._boundingInfo = this._mesh._boundingInfo;
  23906. return;
  23907. }
  23908. var indices = this._renderingMesh.getIndices();
  23909. var extend;
  23910. //is this the only submesh?
  23911. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23912. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23913. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23914. }
  23915. else {
  23916. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23917. }
  23918. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23919. return this;
  23920. };
  23921. SubMesh.prototype._checkCollision = function (collider) {
  23922. return this.getBoundingInfo()._checkCollision(collider);
  23923. };
  23924. /**
  23925. * Updates the submesh BoundingInfo.
  23926. * Returns the Submesh.
  23927. */
  23928. SubMesh.prototype.updateBoundingInfo = function (world) {
  23929. if (!this.getBoundingInfo()) {
  23930. this.refreshBoundingInfo();
  23931. }
  23932. this.getBoundingInfo().update(world);
  23933. return this;
  23934. };
  23935. /**
  23936. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23937. * Boolean returned.
  23938. */
  23939. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23940. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23941. };
  23942. /**
  23943. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23944. * Boolean returned.
  23945. */
  23946. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23947. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23948. };
  23949. /**
  23950. * Renders the submesh.
  23951. * Returns it.
  23952. */
  23953. SubMesh.prototype.render = function (enableAlphaMode) {
  23954. this._renderingMesh.render(this, enableAlphaMode);
  23955. return this;
  23956. };
  23957. /**
  23958. * Returns a new Index Buffer.
  23959. * Type returned : WebGLBuffer.
  23960. */
  23961. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23962. if (!this._linesIndexBuffer) {
  23963. var linesIndices = [];
  23964. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23965. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23966. }
  23967. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23968. this.linesIndexCount = linesIndices.length;
  23969. }
  23970. return this._linesIndexBuffer;
  23971. };
  23972. /**
  23973. * True is the passed Ray intersects the submesh bounding box.
  23974. * Boolean returned.
  23975. */
  23976. SubMesh.prototype.canIntersects = function (ray) {
  23977. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23978. };
  23979. /**
  23980. * Returns an object IntersectionInfo.
  23981. */
  23982. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23983. var intersectInfo = null;
  23984. // LineMesh first as it's also a Mesh...
  23985. if (this._mesh instanceof BABYLON.LinesMesh) {
  23986. var lineMesh = this._mesh;
  23987. // Line test
  23988. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23989. var p0 = positions[indices[index]];
  23990. var p1 = positions[indices[index + 1]];
  23991. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23992. if (length < 0) {
  23993. continue;
  23994. }
  23995. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23996. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23997. if (fastCheck) {
  23998. break;
  23999. }
  24000. }
  24001. }
  24002. }
  24003. else {
  24004. // Triangles test
  24005. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24006. var p0 = positions[indices[index]];
  24007. var p1 = positions[indices[index + 1]];
  24008. var p2 = positions[indices[index + 2]];
  24009. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24010. if (currentIntersectInfo) {
  24011. if (currentIntersectInfo.distance < 0) {
  24012. continue;
  24013. }
  24014. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24015. intersectInfo = currentIntersectInfo;
  24016. intersectInfo.faceId = index / 3;
  24017. if (fastCheck) {
  24018. break;
  24019. }
  24020. }
  24021. }
  24022. }
  24023. }
  24024. return intersectInfo;
  24025. };
  24026. SubMesh.prototype._rebuild = function () {
  24027. if (this._linesIndexBuffer) {
  24028. this._linesIndexBuffer = null;
  24029. }
  24030. };
  24031. // Clone
  24032. /**
  24033. * Creates a new Submesh from the passed Mesh.
  24034. */
  24035. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24036. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24037. if (!this.IsGlobal) {
  24038. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24039. }
  24040. return result;
  24041. };
  24042. // Dispose
  24043. /**
  24044. * Disposes the Submesh.
  24045. * Returns nothing.
  24046. */
  24047. SubMesh.prototype.dispose = function () {
  24048. if (this._linesIndexBuffer) {
  24049. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24050. this._linesIndexBuffer = null;
  24051. }
  24052. // Remove from mesh
  24053. var index = this._mesh.subMeshes.indexOf(this);
  24054. this._mesh.subMeshes.splice(index, 1);
  24055. };
  24056. // Statics
  24057. /**
  24058. * Creates a new Submesh from the passed parameters :
  24059. * - materialIndex (integer) : the index of the main mesh material.
  24060. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24061. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24062. * - mesh (Mesh) : the main mesh to create the submesh from.
  24063. * - renderingMesh (optional Mesh) : rendering mesh.
  24064. */
  24065. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24066. var minVertexIndex = Number.MAX_VALUE;
  24067. var maxVertexIndex = -Number.MAX_VALUE;
  24068. renderingMesh = renderingMesh || mesh;
  24069. var indices = renderingMesh.getIndices();
  24070. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24071. var vertexIndex = indices[index];
  24072. if (vertexIndex < minVertexIndex)
  24073. minVertexIndex = vertexIndex;
  24074. if (vertexIndex > maxVertexIndex)
  24075. maxVertexIndex = vertexIndex;
  24076. }
  24077. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24078. };
  24079. return SubMesh;
  24080. }(BaseSubMesh));
  24081. BABYLON.SubMesh = SubMesh;
  24082. })(BABYLON || (BABYLON = {}));
  24083. //# sourceMappingURL=babylon.subMesh.js.map
  24084. var BABYLON;
  24085. (function (BABYLON) {
  24086. var EffectFallbacks = (function () {
  24087. function EffectFallbacks() {
  24088. this._defines = {};
  24089. this._currentRank = 32;
  24090. this._maxRank = -1;
  24091. }
  24092. EffectFallbacks.prototype.unBindMesh = function () {
  24093. this._mesh = null;
  24094. };
  24095. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24096. if (!this._defines[rank]) {
  24097. if (rank < this._currentRank) {
  24098. this._currentRank = rank;
  24099. }
  24100. if (rank > this._maxRank) {
  24101. this._maxRank = rank;
  24102. }
  24103. this._defines[rank] = new Array();
  24104. }
  24105. this._defines[rank].push(define);
  24106. };
  24107. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24108. this._meshRank = rank;
  24109. this._mesh = mesh;
  24110. if (rank < this._currentRank) {
  24111. this._currentRank = rank;
  24112. }
  24113. if (rank > this._maxRank) {
  24114. this._maxRank = rank;
  24115. }
  24116. };
  24117. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24118. get: function () {
  24119. return this._currentRank <= this._maxRank;
  24120. },
  24121. enumerable: true,
  24122. configurable: true
  24123. });
  24124. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24125. // First we try to switch to CPU skinning
  24126. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24127. this._mesh.computeBonesUsingShaders = false;
  24128. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24129. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24130. var scene = this._mesh.getScene();
  24131. for (var index = 0; index < scene.meshes.length; index++) {
  24132. var otherMesh = scene.meshes[index];
  24133. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24134. otherMesh.computeBonesUsingShaders = false;
  24135. }
  24136. }
  24137. }
  24138. else {
  24139. var currentFallbacks = this._defines[this._currentRank];
  24140. if (currentFallbacks) {
  24141. for (var index = 0; index < currentFallbacks.length; index++) {
  24142. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24143. }
  24144. }
  24145. this._currentRank++;
  24146. }
  24147. return currentDefines;
  24148. };
  24149. return EffectFallbacks;
  24150. }());
  24151. BABYLON.EffectFallbacks = EffectFallbacks;
  24152. var EffectCreationOptions = (function () {
  24153. function EffectCreationOptions() {
  24154. }
  24155. return EffectCreationOptions;
  24156. }());
  24157. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24158. var Effect = (function () {
  24159. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24160. var _this = this;
  24161. this.uniqueId = 0;
  24162. this.onCompileObservable = new BABYLON.Observable();
  24163. this.onErrorObservable = new BABYLON.Observable();
  24164. this.onBindObservable = new BABYLON.Observable();
  24165. this._uniformBuffersNames = {};
  24166. this._isReady = false;
  24167. this._compilationError = "";
  24168. this.name = baseName;
  24169. if (attributesNamesOrOptions.attributes) {
  24170. var options = attributesNamesOrOptions;
  24171. this._engine = uniformsNamesOrEngine;
  24172. this._attributesNames = options.attributes;
  24173. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24174. this._samplers = options.samplers;
  24175. this.defines = options.defines;
  24176. this.onError = options.onError;
  24177. this.onCompiled = options.onCompiled;
  24178. this._fallbacks = options.fallbacks;
  24179. this._indexParameters = options.indexParameters;
  24180. if (options.uniformBuffersNames) {
  24181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24183. }
  24184. }
  24185. }
  24186. else {
  24187. this._engine = engine;
  24188. this.defines = defines;
  24189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24190. this._samplers = samplers;
  24191. this._attributesNames = attributesNamesOrOptions;
  24192. this.onError = onError;
  24193. this.onCompiled = onCompiled;
  24194. this._indexParameters = indexParameters;
  24195. this._fallbacks = fallbacks;
  24196. }
  24197. this.uniqueId = Effect._uniqueIdSeed++;
  24198. var vertexSource;
  24199. var fragmentSource;
  24200. if (baseName.vertexElement) {
  24201. vertexSource = document.getElementById(baseName.vertexElement);
  24202. if (!vertexSource) {
  24203. vertexSource = baseName.vertexElement;
  24204. }
  24205. }
  24206. else {
  24207. vertexSource = baseName.vertex || baseName;
  24208. }
  24209. if (baseName.fragmentElement) {
  24210. fragmentSource = document.getElementById(baseName.fragmentElement);
  24211. if (!fragmentSource) {
  24212. fragmentSource = baseName.fragmentElement;
  24213. }
  24214. }
  24215. else {
  24216. fragmentSource = baseName.fragment || baseName;
  24217. }
  24218. this._loadVertexShader(vertexSource, function (vertexCode) {
  24219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24224. if (baseName) {
  24225. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24226. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24227. }
  24228. else {
  24229. _this._vertexSourceCode = migratedVertexCode;
  24230. _this._fragmentSourceCode = migratedFragmentCode;
  24231. }
  24232. _this._prepareEffect();
  24233. });
  24234. });
  24235. });
  24236. });
  24237. });
  24238. });
  24239. }
  24240. Object.defineProperty(Effect.prototype, "key", {
  24241. get: function () {
  24242. return this._key;
  24243. },
  24244. enumerable: true,
  24245. configurable: true
  24246. });
  24247. // Properties
  24248. Effect.prototype.isReady = function () {
  24249. return this._isReady;
  24250. };
  24251. Effect.prototype.getEngine = function () {
  24252. return this._engine;
  24253. };
  24254. Effect.prototype.getProgram = function () {
  24255. return this._program;
  24256. };
  24257. Effect.prototype.getAttributesNames = function () {
  24258. return this._attributesNames;
  24259. };
  24260. Effect.prototype.getAttributeLocation = function (index) {
  24261. return this._attributes[index];
  24262. };
  24263. Effect.prototype.getAttributeLocationByName = function (name) {
  24264. var index = this._attributesNames.indexOf(name);
  24265. return this._attributes[index];
  24266. };
  24267. Effect.prototype.getAttributesCount = function () {
  24268. return this._attributes.length;
  24269. };
  24270. Effect.prototype.getUniformIndex = function (uniformName) {
  24271. return this._uniformsNames.indexOf(uniformName);
  24272. };
  24273. Effect.prototype.getUniform = function (uniformName) {
  24274. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24275. };
  24276. Effect.prototype.getSamplers = function () {
  24277. return this._samplers;
  24278. };
  24279. Effect.prototype.getCompilationError = function () {
  24280. return this._compilationError;
  24281. };
  24282. // Methods
  24283. Effect.prototype.executeWhenCompiled = function (func) {
  24284. if (this.isReady()) {
  24285. func(this);
  24286. return;
  24287. }
  24288. this.onCompileObservable.add(function (effect) {
  24289. func(effect);
  24290. });
  24291. };
  24292. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24293. // DOM element ?
  24294. if (vertex instanceof HTMLElement) {
  24295. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24296. callback(vertexCode);
  24297. return;
  24298. }
  24299. // Base64 encoded ?
  24300. if (vertex.substr(0, 7) === "base64:") {
  24301. var vertexBinary = window.atob(vertex.substr(7));
  24302. callback(vertexBinary);
  24303. return;
  24304. }
  24305. // Is in local store ?
  24306. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24307. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24308. return;
  24309. }
  24310. var vertexShaderUrl;
  24311. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24312. vertexShaderUrl = vertex;
  24313. }
  24314. else {
  24315. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24316. }
  24317. // Vertex shader
  24318. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24319. };
  24320. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24321. // DOM element ?
  24322. if (fragment instanceof HTMLElement) {
  24323. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24324. callback(fragmentCode);
  24325. return;
  24326. }
  24327. // Base64 encoded ?
  24328. if (fragment.substr(0, 7) === "base64:") {
  24329. var fragmentBinary = window.atob(fragment.substr(7));
  24330. callback(fragmentBinary);
  24331. return;
  24332. }
  24333. // Is in local store ?
  24334. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24335. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24336. return;
  24337. }
  24338. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24339. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24340. return;
  24341. }
  24342. var fragmentShaderUrl;
  24343. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24344. fragmentShaderUrl = fragment;
  24345. }
  24346. else {
  24347. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24348. }
  24349. // Fragment shader
  24350. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24351. };
  24352. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24353. // Rebuild shaders source code
  24354. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24355. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24356. vertexCode = prefix + vertexCode;
  24357. fragmentCode = prefix + fragmentCode;
  24358. // Number lines of shaders source code
  24359. var i = 2;
  24360. var regex = /\n/gm;
  24361. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24362. i = 2;
  24363. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24364. // Dump shaders name and formatted source code
  24365. if (this.name.vertexElement) {
  24366. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24367. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24368. }
  24369. else if (this.name.vertex) {
  24370. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24371. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24372. }
  24373. else {
  24374. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24375. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24376. }
  24377. };
  24378. ;
  24379. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24380. var preparedSourceCode = this._processPrecision(sourceCode);
  24381. if (this._engine.webGLVersion == 1) {
  24382. callback(preparedSourceCode);
  24383. return;
  24384. }
  24385. // Already converted
  24386. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24387. callback(preparedSourceCode.replace("#version 300 es", ""));
  24388. return;
  24389. }
  24390. // Remove extensions
  24391. // #extension GL_OES_standard_derivatives : enable
  24392. // #extension GL_EXT_shader_texture_lod : enable
  24393. // #extension GL_EXT_frag_depth : enable
  24394. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  24395. var result = preparedSourceCode.replace(regex, "");
  24396. // Migrate to GLSL v300
  24397. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24398. result = result.replace(/attribute[ \t]/g, "in ");
  24399. result = result.replace(/[ \t]attribute/g, " in");
  24400. if (isFragment) {
  24401. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24402. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24403. result = result.replace(/texture2D\(/g, "texture(");
  24404. result = result.replace(/textureCube\(/g, "texture(");
  24405. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24406. result = result.replace(/gl_FragColor/g, "glFragColor");
  24407. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  24408. }
  24409. callback(result);
  24410. };
  24411. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24412. var _this = this;
  24413. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24414. var match = regex.exec(sourceCode);
  24415. var returnValue = new String(sourceCode);
  24416. while (match != null) {
  24417. var includeFile = match[1];
  24418. // Uniform declaration
  24419. if (includeFile.indexOf("__decl__") !== -1) {
  24420. includeFile = includeFile.replace(/__decl__/, "");
  24421. if (this._engine.supportsUniformBuffers) {
  24422. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24423. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24424. }
  24425. includeFile = includeFile + "Declaration";
  24426. }
  24427. if (Effect.IncludesShadersStore[includeFile]) {
  24428. // Substitution
  24429. var includeContent = Effect.IncludesShadersStore[includeFile];
  24430. if (match[2]) {
  24431. var splits = match[3].split(",");
  24432. for (var index = 0; index < splits.length; index += 2) {
  24433. var source = new RegExp(splits[index], "g");
  24434. var dest = splits[index + 1];
  24435. includeContent = includeContent.replace(source, dest);
  24436. }
  24437. }
  24438. if (match[4]) {
  24439. var indexString = match[5];
  24440. if (indexString.indexOf("..") !== -1) {
  24441. var indexSplits = indexString.split("..");
  24442. var minIndex = parseInt(indexSplits[0]);
  24443. var maxIndex = parseInt(indexSplits[1]);
  24444. var sourceIncludeContent = includeContent.slice(0);
  24445. includeContent = "";
  24446. if (isNaN(maxIndex)) {
  24447. maxIndex = this._indexParameters[indexSplits[1]];
  24448. }
  24449. for (var i = minIndex; i < maxIndex; i++) {
  24450. if (!this._engine.supportsUniformBuffers) {
  24451. // Ubo replacement
  24452. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24453. return p1 + "{X}";
  24454. });
  24455. }
  24456. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24457. }
  24458. }
  24459. else {
  24460. if (!this._engine.supportsUniformBuffers) {
  24461. // Ubo replacement
  24462. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24463. return p1 + "{X}";
  24464. });
  24465. }
  24466. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24467. }
  24468. }
  24469. // Replace
  24470. returnValue = returnValue.replace(match[0], includeContent);
  24471. }
  24472. else {
  24473. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24474. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24475. Effect.IncludesShadersStore[includeFile] = fileContent;
  24476. _this._processIncludes(returnValue, callback);
  24477. });
  24478. return;
  24479. }
  24480. match = regex.exec(sourceCode);
  24481. }
  24482. callback(returnValue);
  24483. };
  24484. Effect.prototype._processPrecision = function (source) {
  24485. if (source.indexOf("precision highp float") === -1) {
  24486. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24487. source = "precision mediump float;\n" + source;
  24488. }
  24489. else {
  24490. source = "precision highp float;\n" + source;
  24491. }
  24492. }
  24493. else {
  24494. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24495. source = source.replace("precision highp float", "precision mediump float");
  24496. }
  24497. }
  24498. return source;
  24499. };
  24500. Effect.prototype._prepareEffect = function () {
  24501. var attributesNames = this._attributesNames;
  24502. var defines = this.defines;
  24503. var fallbacks = this._fallbacks;
  24504. this._valueCache = {};
  24505. try {
  24506. var engine = this._engine;
  24507. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24508. if (engine.webGLVersion > 1) {
  24509. for (var name in this._uniformBuffersNames) {
  24510. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24511. }
  24512. }
  24513. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24514. this._attributes = engine.getAttributes(this._program, attributesNames);
  24515. var index;
  24516. for (index = 0; index < this._samplers.length; index++) {
  24517. var sampler = this.getUniform(this._samplers[index]);
  24518. if (sampler == null) {
  24519. this._samplers.splice(index, 1);
  24520. index--;
  24521. }
  24522. }
  24523. engine.bindSamplers(this);
  24524. this._compilationError = "";
  24525. this._isReady = true;
  24526. if (this.onCompiled) {
  24527. this.onCompiled(this);
  24528. }
  24529. this.onCompileObservable.notifyObservers(this);
  24530. this.onCompileObservable.clear();
  24531. // Unbind mesh reference in fallbacks
  24532. if (this._fallbacks) {
  24533. this._fallbacks.unBindMesh();
  24534. }
  24535. }
  24536. catch (e) {
  24537. this._compilationError = e.message;
  24538. // Let's go through fallbacks then
  24539. BABYLON.Tools.Error("Unable to compile effect:");
  24540. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24541. return " " + uniform;
  24542. }));
  24543. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24544. return " " + attribute;
  24545. }));
  24546. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24547. BABYLON.Tools.Error("Error: " + this._compilationError);
  24548. if (fallbacks && fallbacks.isMoreFallbacks) {
  24549. BABYLON.Tools.Error("Trying next fallback.");
  24550. this.defines = fallbacks.reduce(this.defines);
  24551. this._prepareEffect();
  24552. }
  24553. else {
  24554. if (this.onError) {
  24555. this.onError(this, this._compilationError);
  24556. }
  24557. this.onErrorObservable.notifyObservers(this);
  24558. this.onErrorObservable.clear();
  24559. // Unbind mesh reference in fallbacks
  24560. if (this._fallbacks) {
  24561. this._fallbacks.unBindMesh();
  24562. }
  24563. }
  24564. }
  24565. };
  24566. Object.defineProperty(Effect.prototype, "isSupported", {
  24567. get: function () {
  24568. return this._compilationError === "";
  24569. },
  24570. enumerable: true,
  24571. configurable: true
  24572. });
  24573. Effect.prototype._bindTexture = function (channel, texture) {
  24574. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24575. };
  24576. Effect.prototype.setTexture = function (channel, texture) {
  24577. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24578. };
  24579. Effect.prototype.setTextureArray = function (channel, textures) {
  24580. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24581. var initialPos = this._samplers.indexOf(channel);
  24582. for (var index = 1; index < textures.length; index++) {
  24583. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24584. }
  24585. }
  24586. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24587. };
  24588. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24589. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24590. };
  24591. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24592. var cache = this._valueCache[uniformName];
  24593. var flag = matrix.updateFlag;
  24594. if (cache !== undefined && cache === flag) {
  24595. return false;
  24596. }
  24597. this._valueCache[uniformName] = flag;
  24598. return true;
  24599. };
  24600. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24601. var cache = this._valueCache[uniformName];
  24602. if (!cache) {
  24603. cache = [x, y];
  24604. this._valueCache[uniformName] = cache;
  24605. return true;
  24606. }
  24607. var changed = false;
  24608. if (cache[0] !== x) {
  24609. cache[0] = x;
  24610. changed = true;
  24611. }
  24612. if (cache[1] !== y) {
  24613. cache[1] = y;
  24614. changed = true;
  24615. }
  24616. return changed;
  24617. };
  24618. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24619. var cache = this._valueCache[uniformName];
  24620. if (!cache) {
  24621. cache = [x, y, z];
  24622. this._valueCache[uniformName] = cache;
  24623. return true;
  24624. }
  24625. var changed = false;
  24626. if (cache[0] !== x) {
  24627. cache[0] = x;
  24628. changed = true;
  24629. }
  24630. if (cache[1] !== y) {
  24631. cache[1] = y;
  24632. changed = true;
  24633. }
  24634. if (cache[2] !== z) {
  24635. cache[2] = z;
  24636. changed = true;
  24637. }
  24638. return changed;
  24639. };
  24640. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24641. var cache = this._valueCache[uniformName];
  24642. if (!cache) {
  24643. cache = [x, y, z, w];
  24644. this._valueCache[uniformName] = cache;
  24645. return true;
  24646. }
  24647. var changed = false;
  24648. if (cache[0] !== x) {
  24649. cache[0] = x;
  24650. changed = true;
  24651. }
  24652. if (cache[1] !== y) {
  24653. cache[1] = y;
  24654. changed = true;
  24655. }
  24656. if (cache[2] !== z) {
  24657. cache[2] = z;
  24658. changed = true;
  24659. }
  24660. if (cache[3] !== w) {
  24661. cache[3] = w;
  24662. changed = true;
  24663. }
  24664. return changed;
  24665. };
  24666. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24667. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24668. return;
  24669. }
  24670. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24671. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24672. };
  24673. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24674. this._engine.bindUniformBlock(this._program, blockName, index);
  24675. };
  24676. Effect.prototype.setIntArray = function (uniformName, array) {
  24677. this._valueCache[uniformName] = null;
  24678. this._engine.setIntArray(this.getUniform(uniformName), array);
  24679. return this;
  24680. };
  24681. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24682. this._valueCache[uniformName] = null;
  24683. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24684. return this;
  24685. };
  24686. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24687. this._valueCache[uniformName] = null;
  24688. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24689. return this;
  24690. };
  24691. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24692. this._valueCache[uniformName] = null;
  24693. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24694. return this;
  24695. };
  24696. Effect.prototype.setFloatArray = function (uniformName, array) {
  24697. this._valueCache[uniformName] = null;
  24698. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24699. return this;
  24700. };
  24701. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24702. this._valueCache[uniformName] = null;
  24703. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24704. return this;
  24705. };
  24706. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24707. this._valueCache[uniformName] = null;
  24708. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24709. return this;
  24710. };
  24711. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24712. this._valueCache[uniformName] = null;
  24713. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24714. return this;
  24715. };
  24716. Effect.prototype.setArray = function (uniformName, array) {
  24717. this._valueCache[uniformName] = null;
  24718. this._engine.setArray(this.getUniform(uniformName), array);
  24719. return this;
  24720. };
  24721. Effect.prototype.setArray2 = function (uniformName, array) {
  24722. this._valueCache[uniformName] = null;
  24723. this._engine.setArray2(this.getUniform(uniformName), array);
  24724. return this;
  24725. };
  24726. Effect.prototype.setArray3 = function (uniformName, array) {
  24727. this._valueCache[uniformName] = null;
  24728. this._engine.setArray3(this.getUniform(uniformName), array);
  24729. return this;
  24730. };
  24731. Effect.prototype.setArray4 = function (uniformName, array) {
  24732. this._valueCache[uniformName] = null;
  24733. this._engine.setArray4(this.getUniform(uniformName), array);
  24734. return this;
  24735. };
  24736. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24737. if (!matrices) {
  24738. return;
  24739. }
  24740. this._valueCache[uniformName] = null;
  24741. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24742. return this;
  24743. };
  24744. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24745. if (this._cacheMatrix(uniformName, matrix)) {
  24746. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24747. }
  24748. return this;
  24749. };
  24750. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24751. this._valueCache[uniformName] = null;
  24752. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24753. return this;
  24754. };
  24755. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24756. this._valueCache[uniformName] = null;
  24757. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24758. return this;
  24759. };
  24760. Effect.prototype.setFloat = function (uniformName, value) {
  24761. var cache = this._valueCache[uniformName];
  24762. if (cache !== undefined && cache === value)
  24763. return this;
  24764. this._valueCache[uniformName] = value;
  24765. this._engine.setFloat(this.getUniform(uniformName), value);
  24766. return this;
  24767. };
  24768. Effect.prototype.setBool = function (uniformName, bool) {
  24769. var cache = this._valueCache[uniformName];
  24770. if (cache !== undefined && cache === bool)
  24771. return this;
  24772. this._valueCache[uniformName] = bool;
  24773. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24774. return this;
  24775. };
  24776. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24777. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24778. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24779. }
  24780. return this;
  24781. };
  24782. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24783. if (this._cacheFloat2(uniformName, x, y)) {
  24784. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24785. }
  24786. return this;
  24787. };
  24788. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24789. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24790. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24791. }
  24792. return this;
  24793. };
  24794. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24795. if (this._cacheFloat3(uniformName, x, y, z)) {
  24796. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24797. }
  24798. return this;
  24799. };
  24800. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24801. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24802. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24803. }
  24804. return this;
  24805. };
  24806. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24807. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24808. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24809. }
  24810. return this;
  24811. };
  24812. Effect.prototype.setColor3 = function (uniformName, color3) {
  24813. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24814. this._engine.setColor3(this.getUniform(uniformName), color3);
  24815. }
  24816. return this;
  24817. };
  24818. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24819. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24820. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24821. }
  24822. return this;
  24823. };
  24824. Effect.ResetCache = function () {
  24825. Effect._baseCache = {};
  24826. };
  24827. Effect._uniqueIdSeed = 0;
  24828. Effect._baseCache = {};
  24829. // Statics
  24830. Effect.ShadersStore = {};
  24831. Effect.IncludesShadersStore = {};
  24832. return Effect;
  24833. }());
  24834. BABYLON.Effect = Effect;
  24835. })(BABYLON || (BABYLON = {}));
  24836. //# sourceMappingURL=babylon.effect.js.map
  24837. var BABYLON;
  24838. (function (BABYLON) {
  24839. var MaterialHelper = (function () {
  24840. function MaterialHelper() {
  24841. }
  24842. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24843. defines._needUVs = true;
  24844. defines[key] = true;
  24845. if (texture.getTextureMatrix().isIdentity(true)) {
  24846. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24847. if (texture.coordinatesIndex === 0) {
  24848. defines["MAINUV1"] = true;
  24849. }
  24850. else {
  24851. defines["MAINUV2"] = true;
  24852. }
  24853. }
  24854. else {
  24855. defines[key + "DIRECTUV"] = 0;
  24856. }
  24857. };
  24858. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24859. var matrix = texture.getTextureMatrix();
  24860. if (!matrix.isIdentity(true)) {
  24861. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24862. }
  24863. };
  24864. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24865. if (defines._areMiscDirty) {
  24866. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24867. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24868. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24869. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24870. }
  24871. };
  24872. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24873. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24874. var changed = false;
  24875. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24876. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24877. changed = true;
  24878. }
  24879. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24880. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24881. changed = true;
  24882. }
  24883. if (defines["INSTANCES"] !== useInstances) {
  24884. defines["INSTANCES"] = useInstances;
  24885. changed = true;
  24886. }
  24887. if (changed) {
  24888. defines.markAsUnprocessed();
  24889. }
  24890. };
  24891. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24892. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24893. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24894. return false;
  24895. }
  24896. defines._normals = defines._needNormals;
  24897. defines._uvs = defines._needUVs;
  24898. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24899. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24900. defines["TANGENT"] = true;
  24901. }
  24902. if (defines._needUVs) {
  24903. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24904. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24905. }
  24906. else {
  24907. defines["UV1"] = false;
  24908. defines["UV2"] = false;
  24909. }
  24910. if (useVertexColor) {
  24911. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24912. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24913. }
  24914. if (useBones) {
  24915. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24916. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24917. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24918. }
  24919. else {
  24920. defines["NUM_BONE_INFLUENCERS"] = 0;
  24921. defines["BonesPerMesh"] = 0;
  24922. }
  24923. }
  24924. if (useMorphTargets) {
  24925. if (mesh.morphTargetManager) {
  24926. var manager = mesh.morphTargetManager;
  24927. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24928. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24929. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24930. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24931. }
  24932. else {
  24933. defines["MORPHTARGETS_TANGENT"] = false;
  24934. defines["MORPHTARGETS_NORMAL"] = false;
  24935. defines["MORPHTARGETS"] = false;
  24936. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24937. }
  24938. }
  24939. return true;
  24940. };
  24941. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24942. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24943. if (disableLighting === void 0) { disableLighting = false; }
  24944. if (!defines._areLightsDirty) {
  24945. return defines._needNormals;
  24946. }
  24947. var lightIndex = 0;
  24948. var needNormals = false;
  24949. var needRebuild = false;
  24950. var lightmapMode = false;
  24951. var shadowEnabled = false;
  24952. var specularEnabled = false;
  24953. if (scene.lightsEnabled && !disableLighting) {
  24954. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24955. var light = _a[_i];
  24956. needNormals = true;
  24957. if (defines["LIGHT" + lightIndex] === undefined) {
  24958. needRebuild = true;
  24959. }
  24960. defines["LIGHT" + lightIndex] = true;
  24961. defines["SPOTLIGHT" + lightIndex] = false;
  24962. defines["HEMILIGHT" + lightIndex] = false;
  24963. defines["POINTLIGHT" + lightIndex] = false;
  24964. defines["DIRLIGHT" + lightIndex] = false;
  24965. var type;
  24966. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24967. type = "SPOTLIGHT" + lightIndex;
  24968. }
  24969. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24970. type = "HEMILIGHT" + lightIndex;
  24971. }
  24972. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24973. type = "POINTLIGHT" + lightIndex;
  24974. }
  24975. else {
  24976. type = "DIRLIGHT" + lightIndex;
  24977. }
  24978. defines[type] = true;
  24979. // Specular
  24980. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24981. specularEnabled = true;
  24982. }
  24983. // Shadows
  24984. defines["SHADOW" + lightIndex] = false;
  24985. defines["SHADOWPCF" + lightIndex] = false;
  24986. defines["SHADOWESM" + lightIndex] = false;
  24987. defines["SHADOWCUBE" + lightIndex] = false;
  24988. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24989. var shadowGenerator = light.getShadowGenerator();
  24990. if (shadowGenerator) {
  24991. shadowEnabled = true;
  24992. shadowGenerator.prepareDefines(defines, lightIndex);
  24993. }
  24994. }
  24995. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24996. lightmapMode = true;
  24997. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24998. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  24999. }
  25000. else {
  25001. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25002. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25003. }
  25004. lightIndex++;
  25005. if (lightIndex === maxSimultaneousLights)
  25006. break;
  25007. }
  25008. }
  25009. defines["SPECULARTERM"] = specularEnabled;
  25010. defines["SHADOWS"] = shadowEnabled;
  25011. // Resetting all other lights if any
  25012. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25013. if (defines["LIGHT" + index] !== undefined) {
  25014. defines["LIGHT" + index] = false;
  25015. defines["HEMILIGHT" + lightIndex] = false;
  25016. defines["POINTLIGHT" + lightIndex] = false;
  25017. defines["DIRLIGHT" + lightIndex] = false;
  25018. defines["SPOTLIGHT" + lightIndex] = false;
  25019. defines["SHADOW" + lightIndex] = false;
  25020. }
  25021. }
  25022. var caps = scene.getEngine().getCaps();
  25023. if (defines["SHADOWFLOAT"] === undefined) {
  25024. needRebuild = true;
  25025. }
  25026. defines["SHADOWFLOAT"] = shadowEnabled &&
  25027. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25028. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25029. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25030. if (needRebuild) {
  25031. defines.rebuild();
  25032. }
  25033. return needNormals;
  25034. };
  25035. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25036. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25037. var uniformsList, uniformBuffersList, samplersList, defines;
  25038. if (uniformsListOrOptions.uniformsNames) {
  25039. var options = uniformsListOrOptions;
  25040. uniformsList = options.uniformsNames;
  25041. uniformBuffersList = options.uniformBuffersNames;
  25042. samplersList = options.samplers;
  25043. defines = options.defines;
  25044. maxSimultaneousLights = options.maxSimultaneousLights;
  25045. }
  25046. else {
  25047. uniformsList = uniformsListOrOptions;
  25048. }
  25049. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25050. if (!defines["LIGHT" + lightIndex]) {
  25051. break;
  25052. }
  25053. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25054. if (uniformBuffersList) {
  25055. uniformBuffersList.push("Light" + lightIndex);
  25056. }
  25057. samplersList.push("shadowSampler" + lightIndex);
  25058. }
  25059. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25060. uniformsList.push("morphTargetInfluences");
  25061. }
  25062. };
  25063. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25064. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25065. if (!defines["SHADOWS"]) {
  25066. return;
  25067. }
  25068. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25069. if (!defines["LIGHT" + lightIndex]) {
  25070. break;
  25071. }
  25072. if (lightIndex > 0) {
  25073. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25074. }
  25075. if (defines["SHADOW" + lightIndex]) {
  25076. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25077. }
  25078. if (defines["SHADOWPCF" + lightIndex]) {
  25079. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25080. }
  25081. if (defines["SHADOWESM" + lightIndex]) {
  25082. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25083. }
  25084. }
  25085. };
  25086. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25087. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25088. if (influencers > 0) {
  25089. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25090. var manager = mesh.morphTargetManager;
  25091. var normal = manager.supportsNormals && defines["NORMAL"];
  25092. var tangent = manager.supportsTangents && defines["TANGENT"];
  25093. for (var index = 0; index < influencers; index++) {
  25094. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25095. if (normal) {
  25096. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25097. }
  25098. if (tangent) {
  25099. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25100. }
  25101. if (attribs.length > maxAttributesCount) {
  25102. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25103. }
  25104. }
  25105. }
  25106. };
  25107. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25108. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25109. fallbacks.addCPUSkinningFallback(0, mesh);
  25110. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25111. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25112. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25113. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25114. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25115. }
  25116. }
  25117. };
  25118. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25119. if (defines["INSTANCES"]) {
  25120. attribs.push("world0");
  25121. attribs.push("world1");
  25122. attribs.push("world2");
  25123. attribs.push("world3");
  25124. }
  25125. };
  25126. // Bindings
  25127. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25128. if (light.shadowEnabled && mesh.receiveShadows) {
  25129. var shadowGenerator = light.getShadowGenerator();
  25130. if (shadowGenerator) {
  25131. shadowGenerator.bindShadowLight(lightIndex, effect);
  25132. }
  25133. }
  25134. };
  25135. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25136. light.transferToEffect(effect, lightIndex + "");
  25137. };
  25138. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25139. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25140. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25141. var lightIndex = 0;
  25142. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25143. var light = _a[_i];
  25144. var scaledIntensity = light.getScaledIntensity();
  25145. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25146. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25147. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25148. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25149. if (defines["SPECULARTERM"]) {
  25150. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25151. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25152. }
  25153. // Shadows
  25154. if (scene.shadowsEnabled) {
  25155. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25156. }
  25157. light._uniformBuffer.update();
  25158. lightIndex++;
  25159. if (lightIndex === maxSimultaneousLights)
  25160. break;
  25161. }
  25162. };
  25163. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25164. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25165. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25166. effect.setColor3("vFogColor", scene.fogColor);
  25167. }
  25168. };
  25169. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25170. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25171. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25172. if (matrices) {
  25173. effect.setMatrices("mBones", matrices);
  25174. }
  25175. }
  25176. };
  25177. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25178. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25179. return;
  25180. }
  25181. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25182. };
  25183. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25184. if (defines["LOGARITHMICDEPTH"]) {
  25185. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25186. }
  25187. };
  25188. MaterialHelper.BindClipPlane = function (effect, scene) {
  25189. if (scene.clipPlane) {
  25190. var clipPlane = scene.clipPlane;
  25191. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25192. }
  25193. };
  25194. return MaterialHelper;
  25195. }());
  25196. BABYLON.MaterialHelper = MaterialHelper;
  25197. })(BABYLON || (BABYLON = {}));
  25198. //# sourceMappingURL=babylon.materialHelper.js.map
  25199. var BABYLON;
  25200. (function (BABYLON) {
  25201. var MaterialDefines = (function () {
  25202. function MaterialDefines() {
  25203. this._isDirty = true;
  25204. this._areLightsDirty = true;
  25205. this._areAttributesDirty = true;
  25206. this._areTexturesDirty = true;
  25207. this._areFresnelDirty = true;
  25208. this._areMiscDirty = true;
  25209. this._areImageProcessingDirty = true;
  25210. this._normals = false;
  25211. this._uvs = false;
  25212. this._needNormals = false;
  25213. this._needUVs = false;
  25214. }
  25215. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25216. get: function () {
  25217. return this._isDirty;
  25218. },
  25219. enumerable: true,
  25220. configurable: true
  25221. });
  25222. MaterialDefines.prototype.markAsProcessed = function () {
  25223. this._isDirty = false;
  25224. this._areAttributesDirty = false;
  25225. this._areTexturesDirty = false;
  25226. this._areFresnelDirty = false;
  25227. this._areLightsDirty = false;
  25228. this._areMiscDirty = false;
  25229. this._areImageProcessingDirty = false;
  25230. };
  25231. MaterialDefines.prototype.markAsUnprocessed = function () {
  25232. this._isDirty = true;
  25233. };
  25234. MaterialDefines.prototype.markAllAsDirty = function () {
  25235. this._areTexturesDirty = true;
  25236. this._areAttributesDirty = true;
  25237. this._areLightsDirty = true;
  25238. this._areFresnelDirty = true;
  25239. this._areMiscDirty = true;
  25240. this._areImageProcessingDirty = true;
  25241. this._isDirty = true;
  25242. };
  25243. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25244. this._areImageProcessingDirty = true;
  25245. this._isDirty = true;
  25246. };
  25247. MaterialDefines.prototype.markAsLightDirty = function () {
  25248. this._areLightsDirty = true;
  25249. this._isDirty = true;
  25250. };
  25251. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25252. this._areAttributesDirty = true;
  25253. this._isDirty = true;
  25254. };
  25255. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25256. this._areTexturesDirty = true;
  25257. this._isDirty = true;
  25258. };
  25259. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25260. this._areFresnelDirty = true;
  25261. this._isDirty = true;
  25262. };
  25263. MaterialDefines.prototype.markAsMiscDirty = function () {
  25264. this._areMiscDirty = true;
  25265. this._isDirty = true;
  25266. };
  25267. MaterialDefines.prototype.rebuild = function () {
  25268. if (this._keys) {
  25269. delete this._keys;
  25270. }
  25271. this._keys = [];
  25272. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25273. var key = _a[_i];
  25274. if (key[0] === "_") {
  25275. continue;
  25276. }
  25277. this._keys.push(key);
  25278. }
  25279. };
  25280. MaterialDefines.prototype.isEqual = function (other) {
  25281. if (this._keys.length !== other._keys.length) {
  25282. return false;
  25283. }
  25284. for (var index = 0; index < this._keys.length; index++) {
  25285. var prop = this._keys[index];
  25286. if (this[prop] !== other[prop]) {
  25287. return false;
  25288. }
  25289. }
  25290. return true;
  25291. };
  25292. MaterialDefines.prototype.cloneTo = function (other) {
  25293. if (this._keys.length !== other._keys.length) {
  25294. other._keys = this._keys.slice(0);
  25295. }
  25296. for (var index = 0; index < this._keys.length; index++) {
  25297. var prop = this._keys[index];
  25298. other[prop] = this[prop];
  25299. }
  25300. };
  25301. MaterialDefines.prototype.reset = function () {
  25302. for (var index = 0; index < this._keys.length; index++) {
  25303. var prop = this._keys[index];
  25304. if (typeof (this[prop]) === "number") {
  25305. this[prop] = 0;
  25306. }
  25307. else {
  25308. this[prop] = false;
  25309. }
  25310. }
  25311. };
  25312. MaterialDefines.prototype.toString = function () {
  25313. var result = "";
  25314. for (var index = 0; index < this._keys.length; index++) {
  25315. var prop = this._keys[index];
  25316. var value = this[prop];
  25317. if (typeof (value) === "number") {
  25318. result += "#define " + prop + " " + this[prop] + "\n";
  25319. }
  25320. else if (value) {
  25321. result += "#define " + prop + "\n";
  25322. }
  25323. }
  25324. return result;
  25325. };
  25326. return MaterialDefines;
  25327. }());
  25328. BABYLON.MaterialDefines = MaterialDefines;
  25329. var Material = (function () {
  25330. function Material(name, scene, doNotAdd) {
  25331. this.checkReadyOnEveryCall = false;
  25332. this.checkReadyOnlyOnce = false;
  25333. this.state = "";
  25334. this.alpha = 1.0;
  25335. this._backFaceCulling = true;
  25336. this.doNotSerialize = false;
  25337. this.storeEffectOnSubMeshes = false;
  25338. /**
  25339. * An event triggered when the material is disposed.
  25340. * @type {BABYLON.Observable}
  25341. */
  25342. this.onDisposeObservable = new BABYLON.Observable();
  25343. /**
  25344. * An event triggered when the material is bound.
  25345. * @type {BABYLON.Observable}
  25346. */
  25347. this.onBindObservable = new BABYLON.Observable();
  25348. /**
  25349. * An event triggered when the material is unbound.
  25350. * @type {BABYLON.Observable}
  25351. */
  25352. this.onUnBindObservable = new BABYLON.Observable();
  25353. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25354. this.disableDepthWrite = false;
  25355. this._fogEnabled = true;
  25356. this.pointSize = 1.0;
  25357. this.zOffset = 0;
  25358. this._wasPreviouslyReady = false;
  25359. this._fillMode = Material.TriangleFillMode;
  25360. this.name = name;
  25361. this.id = name || BABYLON.Tools.RandomId();
  25362. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25363. if (this._scene.useRightHandedSystem) {
  25364. this.sideOrientation = Material.ClockWiseSideOrientation;
  25365. }
  25366. else {
  25367. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25368. }
  25369. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25370. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25371. if (!doNotAdd) {
  25372. this._scene.materials.push(this);
  25373. }
  25374. }
  25375. Object.defineProperty(Material, "TriangleFillMode", {
  25376. get: function () {
  25377. return Material._TriangleFillMode;
  25378. },
  25379. enumerable: true,
  25380. configurable: true
  25381. });
  25382. Object.defineProperty(Material, "WireFrameFillMode", {
  25383. get: function () {
  25384. return Material._WireFrameFillMode;
  25385. },
  25386. enumerable: true,
  25387. configurable: true
  25388. });
  25389. Object.defineProperty(Material, "PointFillMode", {
  25390. get: function () {
  25391. return Material._PointFillMode;
  25392. },
  25393. enumerable: true,
  25394. configurable: true
  25395. });
  25396. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25397. get: function () {
  25398. return Material._ClockWiseSideOrientation;
  25399. },
  25400. enumerable: true,
  25401. configurable: true
  25402. });
  25403. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25404. get: function () {
  25405. return Material._CounterClockWiseSideOrientation;
  25406. },
  25407. enumerable: true,
  25408. configurable: true
  25409. });
  25410. Object.defineProperty(Material, "TextureDirtyFlag", {
  25411. get: function () {
  25412. return Material._TextureDirtyFlag;
  25413. },
  25414. enumerable: true,
  25415. configurable: true
  25416. });
  25417. Object.defineProperty(Material, "LightDirtyFlag", {
  25418. get: function () {
  25419. return Material._LightDirtyFlag;
  25420. },
  25421. enumerable: true,
  25422. configurable: true
  25423. });
  25424. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25425. get: function () {
  25426. return Material._FresnelDirtyFlag;
  25427. },
  25428. enumerable: true,
  25429. configurable: true
  25430. });
  25431. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25432. get: function () {
  25433. return Material._AttributesDirtyFlag;
  25434. },
  25435. enumerable: true,
  25436. configurable: true
  25437. });
  25438. Object.defineProperty(Material, "MiscDirtyFlag", {
  25439. get: function () {
  25440. return Material._MiscDirtyFlag;
  25441. },
  25442. enumerable: true,
  25443. configurable: true
  25444. });
  25445. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25446. get: function () {
  25447. return this._backFaceCulling;
  25448. },
  25449. set: function (value) {
  25450. if (this._backFaceCulling === value) {
  25451. return;
  25452. }
  25453. this._backFaceCulling = value;
  25454. this.markAsDirty(Material.TextureDirtyFlag);
  25455. },
  25456. enumerable: true,
  25457. configurable: true
  25458. });
  25459. Object.defineProperty(Material.prototype, "onDispose", {
  25460. set: function (callback) {
  25461. if (this._onDisposeObserver) {
  25462. this.onDisposeObservable.remove(this._onDisposeObserver);
  25463. }
  25464. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25465. },
  25466. enumerable: true,
  25467. configurable: true
  25468. });
  25469. Object.defineProperty(Material.prototype, "onBind", {
  25470. set: function (callback) {
  25471. if (this._onBindObserver) {
  25472. this.onBindObservable.remove(this._onBindObserver);
  25473. }
  25474. this._onBindObserver = this.onBindObservable.add(callback);
  25475. },
  25476. enumerable: true,
  25477. configurable: true
  25478. });
  25479. Object.defineProperty(Material.prototype, "fogEnabled", {
  25480. get: function () {
  25481. return this._fogEnabled;
  25482. },
  25483. set: function (value) {
  25484. if (this._fogEnabled === value) {
  25485. return;
  25486. }
  25487. this._fogEnabled = value;
  25488. this.markAsDirty(Material.MiscDirtyFlag);
  25489. },
  25490. enumerable: true,
  25491. configurable: true
  25492. });
  25493. Object.defineProperty(Material.prototype, "wireframe", {
  25494. get: function () {
  25495. return this._fillMode === Material.WireFrameFillMode;
  25496. },
  25497. set: function (value) {
  25498. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25499. },
  25500. enumerable: true,
  25501. configurable: true
  25502. });
  25503. Object.defineProperty(Material.prototype, "pointsCloud", {
  25504. get: function () {
  25505. return this._fillMode === Material.PointFillMode;
  25506. },
  25507. set: function (value) {
  25508. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25509. },
  25510. enumerable: true,
  25511. configurable: true
  25512. });
  25513. Object.defineProperty(Material.prototype, "fillMode", {
  25514. get: function () {
  25515. return this._fillMode;
  25516. },
  25517. set: function (value) {
  25518. if (this._fillMode === value) {
  25519. return;
  25520. }
  25521. this._fillMode = value;
  25522. this.markAsDirty(Material.MiscDirtyFlag);
  25523. },
  25524. enumerable: true,
  25525. configurable: true
  25526. });
  25527. /**
  25528. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25529. * subclasses should override adding information pertainent to themselves
  25530. */
  25531. Material.prototype.toString = function (fullDetails) {
  25532. var ret = "Name: " + this.name;
  25533. if (fullDetails) {
  25534. }
  25535. return ret;
  25536. };
  25537. /**
  25538. * Child classes can use it to update shaders
  25539. */
  25540. Material.prototype.getClassName = function () {
  25541. return "Material";
  25542. };
  25543. Object.defineProperty(Material.prototype, "isFrozen", {
  25544. get: function () {
  25545. return this.checkReadyOnlyOnce;
  25546. },
  25547. enumerable: true,
  25548. configurable: true
  25549. });
  25550. Material.prototype.freeze = function () {
  25551. this.checkReadyOnlyOnce = true;
  25552. };
  25553. Material.prototype.unfreeze = function () {
  25554. this.checkReadyOnlyOnce = false;
  25555. };
  25556. Material.prototype.isReady = function (mesh, useInstances) {
  25557. return true;
  25558. };
  25559. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25560. return false;
  25561. };
  25562. Material.prototype.getEffect = function () {
  25563. return this._effect;
  25564. };
  25565. Material.prototype.getScene = function () {
  25566. return this._scene;
  25567. };
  25568. Material.prototype.needAlphaBlending = function () {
  25569. return (this.alpha < 1.0);
  25570. };
  25571. Material.prototype.needAlphaTesting = function () {
  25572. return false;
  25573. };
  25574. Material.prototype.getAlphaTestTexture = function () {
  25575. return null;
  25576. };
  25577. Material.prototype.markDirty = function () {
  25578. this._wasPreviouslyReady = false;
  25579. };
  25580. Material.prototype._preBind = function (effect) {
  25581. var engine = this._scene.getEngine();
  25582. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25583. engine.enableEffect(effect ? effect : this._effect);
  25584. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25585. };
  25586. Material.prototype.bind = function (world, mesh) {
  25587. };
  25588. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25589. };
  25590. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25591. };
  25592. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25593. sceneUbo.bindToEffect(effect, "Scene");
  25594. };
  25595. Material.prototype.bindView = function (effect) {
  25596. if (!this._useUBO) {
  25597. effect.setMatrix("view", this.getScene().getViewMatrix());
  25598. }
  25599. else {
  25600. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25601. }
  25602. };
  25603. Material.prototype.bindViewProjection = function (effect) {
  25604. if (!this._useUBO) {
  25605. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25606. }
  25607. else {
  25608. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25609. }
  25610. };
  25611. Material.prototype._afterBind = function (mesh) {
  25612. this._scene._cachedMaterial = this;
  25613. if (mesh) {
  25614. this._scene._cachedVisibility = mesh.visibility;
  25615. }
  25616. else {
  25617. this._scene._cachedVisibility = 1;
  25618. }
  25619. this.onBindObservable.notifyObservers(mesh);
  25620. if (this.disableDepthWrite) {
  25621. var engine = this._scene.getEngine();
  25622. this._cachedDepthWriteState = engine.getDepthWrite();
  25623. engine.setDepthWrite(false);
  25624. }
  25625. };
  25626. Material.prototype.unbind = function () {
  25627. this.onUnBindObservable.notifyObservers(this);
  25628. if (this.disableDepthWrite) {
  25629. var engine = this._scene.getEngine();
  25630. engine.setDepthWrite(this._cachedDepthWriteState);
  25631. }
  25632. };
  25633. Material.prototype.getActiveTextures = function () {
  25634. return [];
  25635. };
  25636. Material.prototype.hasTexture = function (texture) {
  25637. return false;
  25638. };
  25639. Material.prototype.clone = function (name) {
  25640. return null;
  25641. };
  25642. Material.prototype.getBindedMeshes = function () {
  25643. var result = new Array();
  25644. for (var index = 0; index < this._scene.meshes.length; index++) {
  25645. var mesh = this._scene.meshes[index];
  25646. if (mesh.material === this) {
  25647. result.push(mesh);
  25648. }
  25649. }
  25650. return result;
  25651. };
  25652. /**
  25653. * Force shader compilation including textures ready check
  25654. */
  25655. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25656. var _this = this;
  25657. var subMesh = new BABYLON.BaseSubMesh();
  25658. var scene = this.getScene();
  25659. var engine = scene.getEngine();
  25660. var checkReady = function () {
  25661. if (!_this._scene || !_this._scene.getEngine()) {
  25662. return;
  25663. }
  25664. if (subMesh._materialDefines) {
  25665. subMesh._materialDefines._renderId = -1;
  25666. }
  25667. var alphaTestState = engine.getAlphaTesting();
  25668. var clipPlaneState = scene.clipPlane;
  25669. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25670. if (options && options.clipPlane) {
  25671. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25672. }
  25673. if (_this.storeEffectOnSubMeshes) {
  25674. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25675. if (onCompiled) {
  25676. onCompiled(_this);
  25677. }
  25678. }
  25679. else {
  25680. setTimeout(checkReady, 16);
  25681. }
  25682. }
  25683. else {
  25684. if (_this.isReady(mesh)) {
  25685. if (onCompiled) {
  25686. onCompiled(_this);
  25687. }
  25688. }
  25689. else {
  25690. setTimeout(checkReady, 16);
  25691. }
  25692. }
  25693. engine.setAlphaTesting(alphaTestState);
  25694. if (options && options.clipPlane) {
  25695. scene.clipPlane = clipPlaneState;
  25696. }
  25697. };
  25698. checkReady();
  25699. };
  25700. Material.prototype.markAsDirty = function (flag) {
  25701. if (flag & Material.TextureDirtyFlag) {
  25702. this._markAllSubMeshesAsTexturesDirty();
  25703. }
  25704. if (flag & Material.LightDirtyFlag) {
  25705. this._markAllSubMeshesAsLightsDirty();
  25706. }
  25707. if (flag & Material.FresnelDirtyFlag) {
  25708. this._markAllSubMeshesAsFresnelDirty();
  25709. }
  25710. if (flag & Material.AttributesDirtyFlag) {
  25711. this._markAllSubMeshesAsAttributesDirty();
  25712. }
  25713. if (flag & Material.MiscDirtyFlag) {
  25714. this._markAllSubMeshesAsMiscDirty();
  25715. }
  25716. this.getScene().resetCachedMaterial();
  25717. };
  25718. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25719. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25720. var mesh = _a[_i];
  25721. if (!mesh.subMeshes) {
  25722. continue;
  25723. }
  25724. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25725. var subMesh = _c[_b];
  25726. if (subMesh.getMaterial() !== this) {
  25727. continue;
  25728. }
  25729. if (!subMesh._materialDefines) {
  25730. continue;
  25731. }
  25732. func(subMesh._materialDefines);
  25733. }
  25734. }
  25735. };
  25736. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25737. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25738. };
  25739. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25740. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25741. };
  25742. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25743. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25744. };
  25745. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25746. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25747. };
  25748. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25749. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25750. };
  25751. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25752. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25753. };
  25754. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25755. // Animations
  25756. this.getScene().stopAnimation(this);
  25757. // Remove from scene
  25758. var index = this._scene.materials.indexOf(this);
  25759. if (index >= 0) {
  25760. this._scene.materials.splice(index, 1);
  25761. }
  25762. // Remove from meshes
  25763. for (index = 0; index < this._scene.meshes.length; index++) {
  25764. var mesh = this._scene.meshes[index];
  25765. if (mesh.material === this) {
  25766. mesh.material = null;
  25767. if (mesh.geometry) {
  25768. var geometry = mesh.geometry;
  25769. if (this.storeEffectOnSubMeshes) {
  25770. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25771. var subMesh = _a[_i];
  25772. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25773. }
  25774. }
  25775. else {
  25776. geometry._releaseVertexArrayObject(this._effect);
  25777. }
  25778. }
  25779. }
  25780. }
  25781. this._uniformBuffer.dispose();
  25782. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25783. if (forceDisposeEffect && this._effect) {
  25784. if (this.storeEffectOnSubMeshes) {
  25785. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25786. var subMesh = _c[_b];
  25787. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25788. }
  25789. }
  25790. else {
  25791. this._scene.getEngine()._releaseEffect(this._effect);
  25792. }
  25793. this._effect = null;
  25794. }
  25795. // Callback
  25796. this.onDisposeObservable.notifyObservers(this);
  25797. this.onDisposeObservable.clear();
  25798. this.onBindObservable.clear();
  25799. this.onUnBindObservable.clear();
  25800. };
  25801. Material.prototype.serialize = function () {
  25802. return BABYLON.SerializationHelper.Serialize(this);
  25803. };
  25804. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25805. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25806. multiMaterial.id = parsedMultiMaterial.id;
  25807. if (BABYLON.Tags) {
  25808. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25809. }
  25810. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25811. var subMatId = parsedMultiMaterial.materials[matIndex];
  25812. if (subMatId) {
  25813. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25814. }
  25815. else {
  25816. multiMaterial.subMaterials.push(null);
  25817. }
  25818. }
  25819. return multiMaterial;
  25820. };
  25821. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25822. if (!parsedMaterial.customType) {
  25823. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25824. }
  25825. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25826. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25827. if (!BABYLON.LegacyPBRMaterial) {
  25828. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25829. return;
  25830. }
  25831. }
  25832. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25833. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25834. ;
  25835. };
  25836. Material._TriangleFillMode = 0;
  25837. Material._WireFrameFillMode = 1;
  25838. Material._PointFillMode = 2;
  25839. Material._ClockWiseSideOrientation = 0;
  25840. Material._CounterClockWiseSideOrientation = 1;
  25841. Material._TextureDirtyFlag = 1;
  25842. Material._LightDirtyFlag = 2;
  25843. Material._FresnelDirtyFlag = 4;
  25844. Material._AttributesDirtyFlag = 8;
  25845. Material._MiscDirtyFlag = 16;
  25846. __decorate([
  25847. BABYLON.serialize()
  25848. ], Material.prototype, "id", void 0);
  25849. __decorate([
  25850. BABYLON.serialize()
  25851. ], Material.prototype, "name", void 0);
  25852. __decorate([
  25853. BABYLON.serialize()
  25854. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25855. __decorate([
  25856. BABYLON.serialize()
  25857. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25858. __decorate([
  25859. BABYLON.serialize()
  25860. ], Material.prototype, "state", void 0);
  25861. __decorate([
  25862. BABYLON.serialize()
  25863. ], Material.prototype, "alpha", void 0);
  25864. __decorate([
  25865. BABYLON.serialize("backFaceCulling")
  25866. ], Material.prototype, "_backFaceCulling", void 0);
  25867. __decorate([
  25868. BABYLON.serialize()
  25869. ], Material.prototype, "sideOrientation", void 0);
  25870. __decorate([
  25871. BABYLON.serialize()
  25872. ], Material.prototype, "alphaMode", void 0);
  25873. __decorate([
  25874. BABYLON.serialize()
  25875. ], Material.prototype, "disableDepthWrite", void 0);
  25876. __decorate([
  25877. BABYLON.serialize("fogEnabled")
  25878. ], Material.prototype, "_fogEnabled", void 0);
  25879. __decorate([
  25880. BABYLON.serialize()
  25881. ], Material.prototype, "pointSize", void 0);
  25882. __decorate([
  25883. BABYLON.serialize()
  25884. ], Material.prototype, "zOffset", void 0);
  25885. __decorate([
  25886. BABYLON.serialize()
  25887. ], Material.prototype, "wireframe", null);
  25888. __decorate([
  25889. BABYLON.serialize()
  25890. ], Material.prototype, "pointsCloud", null);
  25891. __decorate([
  25892. BABYLON.serialize()
  25893. ], Material.prototype, "fillMode", null);
  25894. return Material;
  25895. }());
  25896. BABYLON.Material = Material;
  25897. })(BABYLON || (BABYLON = {}));
  25898. //# sourceMappingURL=babylon.material.js.map
  25899. var BABYLON;
  25900. (function (BABYLON) {
  25901. var UniformBuffer = (function () {
  25902. /**
  25903. * Uniform buffer objects.
  25904. *
  25905. * Handles blocks of uniform on the GPU.
  25906. *
  25907. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25908. *
  25909. * For more information, please refer to :
  25910. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25911. */
  25912. function UniformBuffer(engine, data, dynamic) {
  25913. this._engine = engine;
  25914. this._noUBO = !engine.supportsUniformBuffers;
  25915. this._dynamic = dynamic;
  25916. this._data = data || [];
  25917. this._uniformLocations = {};
  25918. this._uniformSizes = {};
  25919. this._uniformLocationPointer = 0;
  25920. this._needSync = false;
  25921. if (this._noUBO) {
  25922. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25923. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25924. this.updateFloat = this._updateFloatForEffect;
  25925. this.updateFloat2 = this._updateFloat2ForEffect;
  25926. this.updateFloat3 = this._updateFloat3ForEffect;
  25927. this.updateFloat4 = this._updateFloat4ForEffect;
  25928. this.updateMatrix = this._updateMatrixForEffect;
  25929. this.updateVector3 = this._updateVector3ForEffect;
  25930. this.updateVector4 = this._updateVector4ForEffect;
  25931. this.updateColor3 = this._updateColor3ForEffect;
  25932. this.updateColor4 = this._updateColor4ForEffect;
  25933. }
  25934. else {
  25935. this._engine._uniformBuffers.push(this);
  25936. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25937. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25938. this.updateFloat = this._updateFloatForUniform;
  25939. this.updateFloat2 = this._updateFloat2ForUniform;
  25940. this.updateFloat3 = this._updateFloat3ForUniform;
  25941. this.updateFloat4 = this._updateFloat4ForUniform;
  25942. this.updateMatrix = this._updateMatrixForUniform;
  25943. this.updateVector3 = this._updateVector3ForUniform;
  25944. this.updateVector4 = this._updateVector4ForUniform;
  25945. this.updateColor3 = this._updateColor3ForUniform;
  25946. this.updateColor4 = this._updateColor4ForUniform;
  25947. }
  25948. }
  25949. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25950. // Properties
  25951. /**
  25952. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25953. * or just falling back on setUniformXXX calls.
  25954. */
  25955. get: function () {
  25956. return !this._noUBO;
  25957. },
  25958. enumerable: true,
  25959. configurable: true
  25960. });
  25961. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25962. /**
  25963. * Indicates if the WebGL underlying uniform buffer is in sync
  25964. * with the javascript cache data.
  25965. */
  25966. get: function () {
  25967. return !this._needSync;
  25968. },
  25969. enumerable: true,
  25970. configurable: true
  25971. });
  25972. /**
  25973. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25974. * Also, a dynamic UniformBuffer will disable cache verification and always
  25975. * update the underlying WebGL uniform buffer to the GPU.
  25976. */
  25977. UniformBuffer.prototype.isDynamic = function () {
  25978. return this._dynamic;
  25979. };
  25980. /**
  25981. * The data cache on JS side.
  25982. */
  25983. UniformBuffer.prototype.getData = function () {
  25984. return this._bufferData;
  25985. };
  25986. /**
  25987. * The underlying WebGL Uniform buffer.
  25988. */
  25989. UniformBuffer.prototype.getBuffer = function () {
  25990. return this._buffer;
  25991. };
  25992. /**
  25993. * std140 layout specifies how to align data within an UBO structure.
  25994. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25995. * for specs.
  25996. */
  25997. UniformBuffer.prototype._fillAlignment = function (size) {
  25998. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  25999. // and 4x4 matrices
  26000. // TODO : change if other types are used
  26001. var alignment;
  26002. if (size <= 2) {
  26003. alignment = size;
  26004. }
  26005. else {
  26006. alignment = 4;
  26007. }
  26008. if ((this._uniformLocationPointer % alignment) !== 0) {
  26009. var oldPointer = this._uniformLocationPointer;
  26010. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26011. var diff = this._uniformLocationPointer - oldPointer;
  26012. for (var i = 0; i < diff; i++) {
  26013. this._data.push(0);
  26014. }
  26015. }
  26016. };
  26017. /**
  26018. * Adds an uniform in the buffer.
  26019. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26020. * for the layout to be correct !
  26021. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26022. * @param {number|number[]} size Data size, or data directly.
  26023. */
  26024. UniformBuffer.prototype.addUniform = function (name, size) {
  26025. if (this._noUBO) {
  26026. return;
  26027. }
  26028. if (this._uniformLocations[name] !== undefined) {
  26029. // Already existing uniform
  26030. return;
  26031. }
  26032. // This function must be called in the order of the shader layout !
  26033. // size can be the size of the uniform, or data directly
  26034. var data;
  26035. if (size instanceof Array) {
  26036. data = size;
  26037. size = data.length;
  26038. }
  26039. else {
  26040. size = size;
  26041. data = [];
  26042. // Fill with zeros
  26043. for (var i = 0; i < size; i++) {
  26044. data.push(0);
  26045. }
  26046. }
  26047. this._fillAlignment(size);
  26048. this._uniformSizes[name] = size;
  26049. this._uniformLocations[name] = this._uniformLocationPointer;
  26050. this._uniformLocationPointer += size;
  26051. for (var i = 0; i < size; i++) {
  26052. this._data.push(data[i]);
  26053. }
  26054. this._needSync = true;
  26055. };
  26056. /**
  26057. * Wrapper for addUniform.
  26058. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26059. * @param {Matrix} mat A 4x4 matrix.
  26060. */
  26061. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26062. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26063. };
  26064. /**
  26065. * Wrapper for addUniform.
  26066. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26067. * @param {number} x
  26068. * @param {number} y
  26069. */
  26070. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26071. var temp = [x, y];
  26072. this.addUniform(name, temp);
  26073. };
  26074. /**
  26075. * Wrapper for addUniform.
  26076. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26077. * @param {number} x
  26078. * @param {number} y
  26079. * @param {number} z
  26080. */
  26081. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26082. var temp = [x, y, z];
  26083. this.addUniform(name, temp);
  26084. };
  26085. /**
  26086. * Wrapper for addUniform.
  26087. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26088. * @param {Color3} color
  26089. */
  26090. UniformBuffer.prototype.addColor3 = function (name, color) {
  26091. var temp = [];
  26092. color.toArray(temp);
  26093. this.addUniform(name, temp);
  26094. };
  26095. /**
  26096. * Wrapper for addUniform.
  26097. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26098. * @param {Color3} color
  26099. * @param {number} alpha
  26100. */
  26101. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26102. var temp = [];
  26103. color.toArray(temp);
  26104. temp.push(alpha);
  26105. this.addUniform(name, temp);
  26106. };
  26107. /**
  26108. * Wrapper for addUniform.
  26109. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26110. * @param {Vector3} vector
  26111. */
  26112. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26113. var temp = [];
  26114. vector.toArray(temp);
  26115. this.addUniform(name, temp);
  26116. };
  26117. /**
  26118. * Wrapper for addUniform.
  26119. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26120. */
  26121. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26122. this.addUniform(name, 12);
  26123. };
  26124. /**
  26125. * Wrapper for addUniform.
  26126. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26127. */
  26128. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26129. this.addUniform(name, 8);
  26130. };
  26131. /**
  26132. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26133. */
  26134. UniformBuffer.prototype.create = function () {
  26135. if (this._noUBO) {
  26136. return;
  26137. }
  26138. if (this._buffer) {
  26139. return; // nothing to do
  26140. }
  26141. // See spec, alignment must be filled as a vec4
  26142. this._fillAlignment(4);
  26143. this._bufferData = new Float32Array(this._data);
  26144. this._rebuild();
  26145. this._needSync = true;
  26146. };
  26147. UniformBuffer.prototype._rebuild = function () {
  26148. if (this._noUBO) {
  26149. return;
  26150. }
  26151. if (this._dynamic) {
  26152. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26153. }
  26154. else {
  26155. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26156. }
  26157. };
  26158. /**
  26159. * Updates the WebGL Uniform Buffer on the GPU.
  26160. * If the `dynamic` flag is set to true, no cache comparison is done.
  26161. * Otherwise, the buffer will be updated only if the cache differs.
  26162. */
  26163. UniformBuffer.prototype.update = function () {
  26164. if (!this._buffer) {
  26165. this.create();
  26166. return;
  26167. }
  26168. if (!this._dynamic && !this._needSync) {
  26169. return;
  26170. }
  26171. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26172. this._needSync = false;
  26173. };
  26174. /**
  26175. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26176. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26177. * @param {number[]|Float32Array} data Flattened data
  26178. * @param {number} size Size of the data.
  26179. */
  26180. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26181. var location = this._uniformLocations[uniformName];
  26182. if (location === undefined) {
  26183. if (this._buffer) {
  26184. // Cannot add an uniform if the buffer is already created
  26185. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26186. return;
  26187. }
  26188. this.addUniform(uniformName, size);
  26189. location = this._uniformLocations[uniformName];
  26190. }
  26191. if (!this._buffer) {
  26192. this.create();
  26193. }
  26194. if (!this._dynamic) {
  26195. // Cache for static uniform buffers
  26196. var changed = false;
  26197. for (var i = 0; i < size; i++) {
  26198. if (this._bufferData[location + i] !== data[i]) {
  26199. changed = true;
  26200. this._bufferData[location + i] = data[i];
  26201. }
  26202. }
  26203. this._needSync = this._needSync || changed;
  26204. }
  26205. else {
  26206. // No cache for dynamic
  26207. for (var i = 0; i < size; i++) {
  26208. this._bufferData[location + i] = data[i];
  26209. }
  26210. }
  26211. };
  26212. // Update methods
  26213. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26214. // To match std140, matrix must be realigned
  26215. for (var i = 0; i < 3; i++) {
  26216. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26217. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26218. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26219. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26220. }
  26221. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26222. };
  26223. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26224. this._currentEffect.setMatrix3x3(name, matrix);
  26225. };
  26226. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26227. this._currentEffect.setMatrix2x2(name, matrix);
  26228. };
  26229. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26230. // To match std140, matrix must be realigned
  26231. for (var i = 0; i < 2; i++) {
  26232. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26233. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26234. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26235. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26236. }
  26237. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26238. };
  26239. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26240. this._currentEffect.setFloat(name, x);
  26241. };
  26242. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26243. UniformBuffer._tempBuffer[0] = x;
  26244. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26245. };
  26246. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26247. if (suffix === void 0) { suffix = ""; }
  26248. this._currentEffect.setFloat2(name + suffix, x, y);
  26249. };
  26250. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26251. if (suffix === void 0) { suffix = ""; }
  26252. UniformBuffer._tempBuffer[0] = x;
  26253. UniformBuffer._tempBuffer[1] = y;
  26254. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26255. };
  26256. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26257. if (suffix === void 0) { suffix = ""; }
  26258. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26259. };
  26260. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26261. if (suffix === void 0) { suffix = ""; }
  26262. UniformBuffer._tempBuffer[0] = x;
  26263. UniformBuffer._tempBuffer[1] = y;
  26264. UniformBuffer._tempBuffer[2] = z;
  26265. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26266. };
  26267. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26268. if (suffix === void 0) { suffix = ""; }
  26269. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26270. };
  26271. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26272. if (suffix === void 0) { suffix = ""; }
  26273. UniformBuffer._tempBuffer[0] = x;
  26274. UniformBuffer._tempBuffer[1] = y;
  26275. UniformBuffer._tempBuffer[2] = z;
  26276. UniformBuffer._tempBuffer[3] = w;
  26277. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26278. };
  26279. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26280. this._currentEffect.setMatrix(name, mat);
  26281. };
  26282. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26283. this.updateUniform(name, mat.toArray(), 16);
  26284. };
  26285. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26286. this._currentEffect.setVector3(name, vector);
  26287. };
  26288. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26289. vector.toArray(UniformBuffer._tempBuffer);
  26290. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26291. };
  26292. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26293. this._currentEffect.setVector4(name, vector);
  26294. };
  26295. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26296. vector.toArray(UniformBuffer._tempBuffer);
  26297. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26298. };
  26299. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26300. if (suffix === void 0) { suffix = ""; }
  26301. this._currentEffect.setColor3(name + suffix, color);
  26302. };
  26303. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26304. if (suffix === void 0) { suffix = ""; }
  26305. color.toArray(UniformBuffer._tempBuffer);
  26306. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26307. };
  26308. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26309. if (suffix === void 0) { suffix = ""; }
  26310. this._currentEffect.setColor4(name + suffix, color, alpha);
  26311. };
  26312. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26313. if (suffix === void 0) { suffix = ""; }
  26314. color.toArray(UniformBuffer._tempBuffer);
  26315. UniformBuffer._tempBuffer[3] = alpha;
  26316. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26317. };
  26318. /**
  26319. * Sets a sampler uniform on the effect.
  26320. * @param {string} name Name of the sampler.
  26321. * @param {Texture} texture
  26322. */
  26323. UniformBuffer.prototype.setTexture = function (name, texture) {
  26324. this._currentEffect.setTexture(name, texture);
  26325. };
  26326. /**
  26327. * Directly updates the value of the uniform in the cache AND on the GPU.
  26328. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26329. * @param {number[]|Float32Array} data Flattened data
  26330. */
  26331. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26332. this.updateUniform(uniformName, data, data.length);
  26333. this.update();
  26334. };
  26335. /**
  26336. * Binds this uniform buffer to an effect.
  26337. * @param {Effect} effect
  26338. * @param {string} name Name of the uniform block in the shader.
  26339. */
  26340. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26341. this._currentEffect = effect;
  26342. if (this._noUBO) {
  26343. return;
  26344. }
  26345. effect.bindUniformBuffer(this._buffer, name);
  26346. };
  26347. /**
  26348. * Disposes the uniform buffer.
  26349. */
  26350. UniformBuffer.prototype.dispose = function () {
  26351. if (this._noUBO) {
  26352. return;
  26353. }
  26354. var index = this._engine._uniformBuffers.indexOf(this);
  26355. if (index !== -1) {
  26356. this._engine._uniformBuffers.splice(index, 1);
  26357. }
  26358. if (!this._buffer) {
  26359. return;
  26360. }
  26361. if (this._engine._releaseBuffer(this._buffer)) {
  26362. this._buffer = null;
  26363. }
  26364. };
  26365. // Pool for avoiding memory leaks
  26366. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26367. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26368. return UniformBuffer;
  26369. }());
  26370. BABYLON.UniformBuffer = UniformBuffer;
  26371. })(BABYLON || (BABYLON = {}));
  26372. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26373. var BABYLON;
  26374. (function (BABYLON) {
  26375. var PushMaterial = (function (_super) {
  26376. __extends(PushMaterial, _super);
  26377. function PushMaterial(name, scene) {
  26378. var _this = _super.call(this, name, scene) || this;
  26379. _this.storeEffectOnSubMeshes = true;
  26380. return _this;
  26381. }
  26382. PushMaterial.prototype.getEffect = function () {
  26383. return this._activeEffect;
  26384. };
  26385. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26386. if (!mesh) {
  26387. return false;
  26388. }
  26389. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26390. return true;
  26391. }
  26392. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26393. };
  26394. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26395. this._activeEffect.setMatrix("world", world);
  26396. };
  26397. PushMaterial.prototype.bind = function (world, mesh) {
  26398. if (!mesh) {
  26399. return;
  26400. }
  26401. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26402. };
  26403. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26404. _super.prototype._afterBind.call(this, mesh);
  26405. this.getScene()._cachedEffect = effect;
  26406. };
  26407. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26408. if (visibility === void 0) { visibility = 1; }
  26409. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26410. };
  26411. return PushMaterial;
  26412. }(BABYLON.Material));
  26413. BABYLON.PushMaterial = PushMaterial;
  26414. })(BABYLON || (BABYLON = {}));
  26415. //# sourceMappingURL=babylon.pushMaterial.js.map
  26416. var BABYLON;
  26417. (function (BABYLON) {
  26418. var VertexData = (function () {
  26419. function VertexData() {
  26420. }
  26421. VertexData.prototype.set = function (data, kind) {
  26422. switch (kind) {
  26423. case BABYLON.VertexBuffer.PositionKind:
  26424. this.positions = data;
  26425. break;
  26426. case BABYLON.VertexBuffer.NormalKind:
  26427. this.normals = data;
  26428. break;
  26429. case BABYLON.VertexBuffer.TangentKind:
  26430. this.tangents = data;
  26431. break;
  26432. case BABYLON.VertexBuffer.UVKind:
  26433. this.uvs = data;
  26434. break;
  26435. case BABYLON.VertexBuffer.UV2Kind:
  26436. this.uvs2 = data;
  26437. break;
  26438. case BABYLON.VertexBuffer.UV3Kind:
  26439. this.uvs3 = data;
  26440. break;
  26441. case BABYLON.VertexBuffer.UV4Kind:
  26442. this.uvs4 = data;
  26443. break;
  26444. case BABYLON.VertexBuffer.UV5Kind:
  26445. this.uvs5 = data;
  26446. break;
  26447. case BABYLON.VertexBuffer.UV6Kind:
  26448. this.uvs6 = data;
  26449. break;
  26450. case BABYLON.VertexBuffer.ColorKind:
  26451. this.colors = data;
  26452. break;
  26453. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26454. this.matricesIndices = data;
  26455. break;
  26456. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26457. this.matricesWeights = data;
  26458. break;
  26459. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26460. this.matricesIndicesExtra = data;
  26461. break;
  26462. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26463. this.matricesWeightsExtra = data;
  26464. break;
  26465. }
  26466. };
  26467. /**
  26468. * Associates the vertexData to the passed Mesh.
  26469. * Sets it as updatable or not (default `false`).
  26470. * Returns the VertexData.
  26471. */
  26472. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26473. this._applyTo(mesh, updatable);
  26474. return this;
  26475. };
  26476. /**
  26477. * Associates the vertexData to the passed Geometry.
  26478. * Sets it as updatable or not (default `false`).
  26479. * Returns the VertexData.
  26480. */
  26481. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26482. this._applyTo(geometry, updatable);
  26483. return this;
  26484. };
  26485. /**
  26486. * Updates the associated mesh.
  26487. * Returns the VertexData.
  26488. */
  26489. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26490. this._update(mesh);
  26491. return this;
  26492. };
  26493. /**
  26494. * Updates the associated geometry.
  26495. * Returns the VertexData.
  26496. */
  26497. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26498. this._update(geometry);
  26499. return this;
  26500. };
  26501. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26502. if (this.positions) {
  26503. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26504. }
  26505. if (this.normals) {
  26506. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26507. }
  26508. if (this.tangents) {
  26509. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26510. }
  26511. if (this.uvs) {
  26512. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26513. }
  26514. if (this.uvs2) {
  26515. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26516. }
  26517. if (this.uvs3) {
  26518. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26519. }
  26520. if (this.uvs4) {
  26521. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26522. }
  26523. if (this.uvs5) {
  26524. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26525. }
  26526. if (this.uvs6) {
  26527. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26528. }
  26529. if (this.colors) {
  26530. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26531. }
  26532. if (this.matricesIndices) {
  26533. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26534. }
  26535. if (this.matricesWeights) {
  26536. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26537. }
  26538. if (this.matricesIndicesExtra) {
  26539. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26540. }
  26541. if (this.matricesWeightsExtra) {
  26542. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26543. }
  26544. if (this.indices) {
  26545. meshOrGeometry.setIndices(this.indices);
  26546. }
  26547. return this;
  26548. };
  26549. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26550. if (this.positions) {
  26551. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26552. }
  26553. if (this.normals) {
  26554. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26555. }
  26556. if (this.tangents) {
  26557. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26558. }
  26559. if (this.uvs) {
  26560. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26561. }
  26562. if (this.uvs2) {
  26563. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26564. }
  26565. if (this.uvs3) {
  26566. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26567. }
  26568. if (this.uvs4) {
  26569. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26570. }
  26571. if (this.uvs5) {
  26572. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26573. }
  26574. if (this.uvs6) {
  26575. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26576. }
  26577. if (this.colors) {
  26578. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26579. }
  26580. if (this.matricesIndices) {
  26581. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26582. }
  26583. if (this.matricesWeights) {
  26584. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26585. }
  26586. if (this.matricesIndicesExtra) {
  26587. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26588. }
  26589. if (this.matricesWeightsExtra) {
  26590. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26591. }
  26592. if (this.indices) {
  26593. meshOrGeometry.setIndices(this.indices);
  26594. }
  26595. return this;
  26596. };
  26597. /**
  26598. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26599. * Returns the VertexData.
  26600. */
  26601. VertexData.prototype.transform = function (matrix) {
  26602. var transformed = BABYLON.Vector3.Zero();
  26603. var index;
  26604. if (this.positions) {
  26605. var position = BABYLON.Vector3.Zero();
  26606. for (index = 0; index < this.positions.length; index += 3) {
  26607. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26608. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26609. this.positions[index] = transformed.x;
  26610. this.positions[index + 1] = transformed.y;
  26611. this.positions[index + 2] = transformed.z;
  26612. }
  26613. }
  26614. if (this.normals) {
  26615. var normal = BABYLON.Vector3.Zero();
  26616. for (index = 0; index < this.normals.length; index += 3) {
  26617. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26618. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26619. this.normals[index] = transformed.x;
  26620. this.normals[index + 1] = transformed.y;
  26621. this.normals[index + 2] = transformed.z;
  26622. }
  26623. }
  26624. if (this.tangents) {
  26625. var tangent = BABYLON.Vector4.Zero();
  26626. var tangentTransformed = BABYLON.Vector4.Zero();
  26627. for (index = 0; index < this.tangents.length; index += 4) {
  26628. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26629. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26630. this.tangents[index] = tangentTransformed.x;
  26631. this.tangents[index + 1] = tangentTransformed.y;
  26632. this.tangents[index + 2] = tangentTransformed.z;
  26633. this.tangents[index + 3] = tangentTransformed.w;
  26634. }
  26635. }
  26636. return this;
  26637. };
  26638. /**
  26639. * Merges the passed VertexData into the current one.
  26640. * Returns the modified VertexData.
  26641. */
  26642. VertexData.prototype.merge = function (other) {
  26643. if (other.indices) {
  26644. if (!this.indices) {
  26645. this.indices = [];
  26646. }
  26647. var offset = this.positions ? this.positions.length / 3 : 0;
  26648. for (var index = 0; index < other.indices.length; index++) {
  26649. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26650. this.indices.push(other.indices[index] + offset);
  26651. }
  26652. }
  26653. this.positions = this._mergeElement(this.positions, other.positions);
  26654. this.normals = this._mergeElement(this.normals, other.normals);
  26655. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26656. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26657. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26658. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26659. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26660. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26661. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26662. this.colors = this._mergeElement(this.colors, other.colors);
  26663. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26664. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26665. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26666. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26667. return this;
  26668. };
  26669. VertexData.prototype._mergeElement = function (source, other) {
  26670. if (!other)
  26671. return source;
  26672. if (!source)
  26673. return other;
  26674. var len = other.length + source.length;
  26675. var isSrcTypedArray = source instanceof Float32Array;
  26676. var isOthTypedArray = other instanceof Float32Array;
  26677. // use non-loop method when the source is Float32Array
  26678. if (isSrcTypedArray) {
  26679. var ret32 = new Float32Array(len);
  26680. ret32.set(source);
  26681. ret32.set(other, source.length);
  26682. return ret32;
  26683. // source is number[], when other is also use concat
  26684. }
  26685. else if (!isOthTypedArray) {
  26686. return source.concat(other);
  26687. // source is a number[], but other is a Float32Array, loop required
  26688. }
  26689. else {
  26690. var ret = source.slice(0); // copy source to a separate array
  26691. for (var i = 0, len = other.length; i < len; i++) {
  26692. ret.push(other[i]);
  26693. }
  26694. return ret;
  26695. }
  26696. };
  26697. /**
  26698. * Serializes the VertexData.
  26699. * Returns a serialized object.
  26700. */
  26701. VertexData.prototype.serialize = function () {
  26702. var serializationObject = this.serialize();
  26703. if (this.positions) {
  26704. serializationObject.positions = this.positions;
  26705. }
  26706. if (this.normals) {
  26707. serializationObject.normals = this.normals;
  26708. }
  26709. if (this.tangents) {
  26710. serializationObject.tangents = this.tangents;
  26711. }
  26712. if (this.uvs) {
  26713. serializationObject.uvs = this.uvs;
  26714. }
  26715. if (this.uvs2) {
  26716. serializationObject.uvs2 = this.uvs2;
  26717. }
  26718. if (this.uvs3) {
  26719. serializationObject.uvs3 = this.uvs3;
  26720. }
  26721. if (this.uvs4) {
  26722. serializationObject.uvs4 = this.uvs4;
  26723. }
  26724. if (this.uvs5) {
  26725. serializationObject.uvs5 = this.uvs5;
  26726. }
  26727. if (this.uvs6) {
  26728. serializationObject.uvs6 = this.uvs6;
  26729. }
  26730. if (this.colors) {
  26731. serializationObject.colors = this.colors;
  26732. }
  26733. if (this.matricesIndices) {
  26734. serializationObject.matricesIndices = this.matricesIndices;
  26735. serializationObject.matricesIndices._isExpanded = true;
  26736. }
  26737. if (this.matricesWeights) {
  26738. serializationObject.matricesWeights = this.matricesWeights;
  26739. }
  26740. if (this.matricesIndicesExtra) {
  26741. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26742. serializationObject.matricesIndicesExtra._isExpanded = true;
  26743. }
  26744. if (this.matricesWeightsExtra) {
  26745. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26746. }
  26747. serializationObject.indices = this.indices;
  26748. return serializationObject;
  26749. };
  26750. // Statics
  26751. /**
  26752. * Returns the object VertexData associated to the passed mesh.
  26753. */
  26754. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26755. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26756. };
  26757. /**
  26758. * Returns the object VertexData associated to the passed geometry.
  26759. */
  26760. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26761. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26762. };
  26763. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26764. var result = new VertexData();
  26765. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26766. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26767. }
  26768. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26769. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26770. }
  26771. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26772. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26773. }
  26774. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26775. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26776. }
  26777. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26778. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26779. }
  26780. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26781. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26782. }
  26783. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26784. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26785. }
  26786. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26787. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26788. }
  26789. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26790. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26791. }
  26792. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26793. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26794. }
  26795. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26796. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26797. }
  26798. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26799. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26800. }
  26801. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26802. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26803. }
  26804. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26805. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26806. }
  26807. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26808. return result;
  26809. };
  26810. /**
  26811. * Creates the vertexData of the Ribbon.
  26812. */
  26813. VertexData.CreateRibbon = function (options) {
  26814. var pathArray = options.pathArray;
  26815. var closeArray = options.closeArray || false;
  26816. var closePath = options.closePath || false;
  26817. var invertUV = options.invertUV || false;
  26818. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26819. var offset = options.offset || defaultOffset;
  26820. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26821. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26822. var customUV = options.uvs;
  26823. var customColors = options.colors;
  26824. var positions = [];
  26825. var indices = [];
  26826. var normals = [];
  26827. var uvs = [];
  26828. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26829. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26830. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26831. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26832. var minlg; // minimal length among all paths from pathArray
  26833. var lg = []; // array of path lengths : nb of vertex per path
  26834. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26835. var p; // path iterator
  26836. var i; // point iterator
  26837. var j; // point iterator
  26838. // if single path in pathArray
  26839. if (pathArray.length < 2) {
  26840. var ar1 = [];
  26841. var ar2 = [];
  26842. for (i = 0; i < pathArray[0].length - offset; i++) {
  26843. ar1.push(pathArray[0][i]);
  26844. ar2.push(pathArray[0][i + offset]);
  26845. }
  26846. pathArray = [ar1, ar2];
  26847. }
  26848. // positions and horizontal distances (u)
  26849. var idc = 0;
  26850. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26851. var path;
  26852. var l;
  26853. minlg = pathArray[0].length;
  26854. var vectlg;
  26855. var dist;
  26856. for (p = 0; p < pathArray.length; p++) {
  26857. uTotalDistance[p] = 0;
  26858. us[p] = [0];
  26859. path = pathArray[p];
  26860. l = path.length;
  26861. minlg = (minlg < l) ? minlg : l;
  26862. j = 0;
  26863. while (j < l) {
  26864. positions.push(path[j].x, path[j].y, path[j].z);
  26865. if (j > 0) {
  26866. vectlg = path[j].subtract(path[j - 1]).length();
  26867. dist = vectlg + uTotalDistance[p];
  26868. us[p].push(dist);
  26869. uTotalDistance[p] = dist;
  26870. }
  26871. j++;
  26872. }
  26873. if (closePath) {
  26874. j--;
  26875. positions.push(path[0].x, path[0].y, path[0].z);
  26876. vectlg = path[j].subtract(path[0]).length();
  26877. dist = vectlg + uTotalDistance[p];
  26878. us[p].push(dist);
  26879. uTotalDistance[p] = dist;
  26880. }
  26881. lg[p] = l + closePathCorr;
  26882. idx[p] = idc;
  26883. idc += (l + closePathCorr);
  26884. }
  26885. // vertical distances (v)
  26886. var path1;
  26887. var path2;
  26888. var vertex1;
  26889. var vertex2;
  26890. for (i = 0; i < minlg + closePathCorr; i++) {
  26891. vTotalDistance[i] = 0;
  26892. vs[i] = [0];
  26893. for (p = 0; p < pathArray.length - 1; p++) {
  26894. path1 = pathArray[p];
  26895. path2 = pathArray[p + 1];
  26896. if (i === minlg) {
  26897. vertex1 = path1[0];
  26898. vertex2 = path2[0];
  26899. }
  26900. else {
  26901. vertex1 = path1[i];
  26902. vertex2 = path2[i];
  26903. }
  26904. vectlg = vertex2.subtract(vertex1).length();
  26905. dist = vectlg + vTotalDistance[i];
  26906. vs[i].push(dist);
  26907. vTotalDistance[i] = dist;
  26908. }
  26909. if (closeArray) {
  26910. path1 = pathArray[p];
  26911. path2 = pathArray[0];
  26912. if (i === minlg) {
  26913. vertex2 = path2[0];
  26914. }
  26915. vectlg = vertex2.subtract(vertex1).length();
  26916. dist = vectlg + vTotalDistance[i];
  26917. vTotalDistance[i] = dist;
  26918. }
  26919. }
  26920. // uvs
  26921. var u;
  26922. var v;
  26923. if (customUV) {
  26924. for (p = 0; p < customUV.length; p++) {
  26925. uvs.push(customUV[p].x, customUV[p].y);
  26926. }
  26927. }
  26928. else {
  26929. for (p = 0; p < pathArray.length; p++) {
  26930. for (i = 0; i < minlg + closePathCorr; i++) {
  26931. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26932. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26933. if (invertUV) {
  26934. uvs.push(v, u);
  26935. }
  26936. else {
  26937. uvs.push(u, v);
  26938. }
  26939. }
  26940. }
  26941. }
  26942. // indices
  26943. p = 0; // path index
  26944. var pi = 0; // positions array index
  26945. var l1 = lg[p] - 1; // path1 length
  26946. var l2 = lg[p + 1] - 1; // path2 length
  26947. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26948. var shft = idx[1] - idx[0]; // shift
  26949. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26950. while (pi <= min && p < path1nb) {
  26951. // 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
  26952. indices.push(pi, pi + shft, pi + 1);
  26953. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26954. pi += 1;
  26955. if (pi === min) {
  26956. p++;
  26957. if (p === lg.length - 1) {
  26958. shft = idx[0] - idx[p];
  26959. l1 = lg[p] - 1;
  26960. l2 = lg[0] - 1;
  26961. }
  26962. else {
  26963. shft = idx[p + 1] - idx[p];
  26964. l1 = lg[p] - 1;
  26965. l2 = lg[p + 1] - 1;
  26966. }
  26967. pi = idx[p];
  26968. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26969. }
  26970. }
  26971. // normals
  26972. VertexData.ComputeNormals(positions, indices, normals);
  26973. if (closePath) {
  26974. var indexFirst = 0;
  26975. var indexLast = 0;
  26976. for (p = 0; p < pathArray.length; p++) {
  26977. indexFirst = idx[p] * 3;
  26978. if (p + 1 < pathArray.length) {
  26979. indexLast = (idx[p + 1] - 1) * 3;
  26980. }
  26981. else {
  26982. indexLast = normals.length - 3;
  26983. }
  26984. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26985. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26986. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26987. normals[indexLast] = normals[indexFirst];
  26988. normals[indexLast + 1] = normals[indexFirst + 1];
  26989. normals[indexLast + 2] = normals[indexFirst + 2];
  26990. }
  26991. }
  26992. // sides
  26993. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26994. // Colors
  26995. if (customColors) {
  26996. var colors = new Float32Array(customColors.length * 4);
  26997. for (var c = 0; c < customColors.length; c++) {
  26998. colors[c * 4] = customColors[c].r;
  26999. colors[c * 4 + 1] = customColors[c].g;
  27000. colors[c * 4 + 2] = customColors[c].b;
  27001. colors[c * 4 + 3] = customColors[c].a;
  27002. }
  27003. }
  27004. // Result
  27005. var vertexData = new VertexData();
  27006. var positions32 = new Float32Array(positions);
  27007. var normals32 = new Float32Array(normals);
  27008. var uvs32 = new Float32Array(uvs);
  27009. vertexData.indices = indices;
  27010. vertexData.positions = positions32;
  27011. vertexData.normals = normals32;
  27012. vertexData.uvs = uvs32;
  27013. if (customColors) {
  27014. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27015. }
  27016. if (closePath) {
  27017. vertexData._idx = idx;
  27018. }
  27019. return vertexData;
  27020. };
  27021. /**
  27022. * Creates the VertexData of the Box.
  27023. */
  27024. VertexData.CreateBox = function (options) {
  27025. var normalsSource = [
  27026. new BABYLON.Vector3(0, 0, 1),
  27027. new BABYLON.Vector3(0, 0, -1),
  27028. new BABYLON.Vector3(1, 0, 0),
  27029. new BABYLON.Vector3(-1, 0, 0),
  27030. new BABYLON.Vector3(0, 1, 0),
  27031. new BABYLON.Vector3(0, -1, 0)
  27032. ];
  27033. var indices = [];
  27034. var positions = [];
  27035. var normals = [];
  27036. var uvs = [];
  27037. var width = options.width || options.size || 1;
  27038. var height = options.height || options.size || 1;
  27039. var depth = options.depth || options.size || 1;
  27040. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27041. var faceUV = options.faceUV || new Array(6);
  27042. var faceColors = options.faceColors;
  27043. var colors = [];
  27044. // default face colors and UV if undefined
  27045. for (var f = 0; f < 6; f++) {
  27046. if (faceUV[f] === undefined) {
  27047. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27048. }
  27049. if (faceColors && faceColors[f] === undefined) {
  27050. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27051. }
  27052. }
  27053. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27054. // Create each face in turn.
  27055. for (var index = 0; index < normalsSource.length; index++) {
  27056. var normal = normalsSource[index];
  27057. // Get two vectors perpendicular to the face normal and to each other.
  27058. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27059. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27060. // Six indices (two triangles) per face.
  27061. var verticesLength = positions.length / 3;
  27062. indices.push(verticesLength);
  27063. indices.push(verticesLength + 1);
  27064. indices.push(verticesLength + 2);
  27065. indices.push(verticesLength);
  27066. indices.push(verticesLength + 2);
  27067. indices.push(verticesLength + 3);
  27068. // Four vertices per face.
  27069. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27070. positions.push(vertex.x, vertex.y, vertex.z);
  27071. normals.push(normal.x, normal.y, normal.z);
  27072. uvs.push(faceUV[index].z, faceUV[index].w);
  27073. if (faceColors) {
  27074. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27075. }
  27076. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27077. positions.push(vertex.x, vertex.y, vertex.z);
  27078. normals.push(normal.x, normal.y, normal.z);
  27079. uvs.push(faceUV[index].x, faceUV[index].w);
  27080. if (faceColors) {
  27081. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27082. }
  27083. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27084. positions.push(vertex.x, vertex.y, vertex.z);
  27085. normals.push(normal.x, normal.y, normal.z);
  27086. uvs.push(faceUV[index].x, faceUV[index].y);
  27087. if (faceColors) {
  27088. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27089. }
  27090. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27091. positions.push(vertex.x, vertex.y, vertex.z);
  27092. normals.push(normal.x, normal.y, normal.z);
  27093. uvs.push(faceUV[index].z, faceUV[index].y);
  27094. if (faceColors) {
  27095. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27096. }
  27097. }
  27098. // sides
  27099. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27100. // Result
  27101. var vertexData = new VertexData();
  27102. vertexData.indices = indices;
  27103. vertexData.positions = positions;
  27104. vertexData.normals = normals;
  27105. vertexData.uvs = uvs;
  27106. if (faceColors) {
  27107. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27108. vertexData.colors = totalColors;
  27109. }
  27110. return vertexData;
  27111. };
  27112. /**
  27113. * Creates the VertexData of the Sphere.
  27114. */
  27115. VertexData.CreateSphere = function (options) {
  27116. var segments = options.segments || 32;
  27117. var diameterX = options.diameterX || options.diameter || 1;
  27118. var diameterY = options.diameterY || options.diameter || 1;
  27119. var diameterZ = options.diameterZ || options.diameter || 1;
  27120. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27121. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27122. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27123. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27124. var totalZRotationSteps = 2 + segments;
  27125. var totalYRotationSteps = 2 * totalZRotationSteps;
  27126. var indices = [];
  27127. var positions = [];
  27128. var normals = [];
  27129. var uvs = [];
  27130. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27131. var normalizedZ = zRotationStep / totalZRotationSteps;
  27132. var angleZ = normalizedZ * Math.PI * slice;
  27133. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27134. var normalizedY = yRotationStep / totalYRotationSteps;
  27135. var angleY = normalizedY * Math.PI * 2 * arc;
  27136. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27137. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27138. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27139. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27140. var vertex = complete.multiply(radius);
  27141. var normal = complete.divide(radius).normalize();
  27142. positions.push(vertex.x, vertex.y, vertex.z);
  27143. normals.push(normal.x, normal.y, normal.z);
  27144. uvs.push(normalizedY, normalizedZ);
  27145. }
  27146. if (zRotationStep > 0) {
  27147. var verticesCount = positions.length / 3;
  27148. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27149. indices.push((firstIndex));
  27150. indices.push((firstIndex + 1));
  27151. indices.push(firstIndex + totalYRotationSteps + 1);
  27152. indices.push((firstIndex + totalYRotationSteps + 1));
  27153. indices.push((firstIndex + 1));
  27154. indices.push((firstIndex + totalYRotationSteps + 2));
  27155. }
  27156. }
  27157. }
  27158. // Sides
  27159. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27160. // Result
  27161. var vertexData = new VertexData();
  27162. vertexData.indices = indices;
  27163. vertexData.positions = positions;
  27164. vertexData.normals = normals;
  27165. vertexData.uvs = uvs;
  27166. return vertexData;
  27167. };
  27168. /**
  27169. * Creates the VertexData of the Cylinder or Cone.
  27170. */
  27171. VertexData.CreateCylinder = function (options) {
  27172. var height = options.height || 2;
  27173. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27174. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27175. var tessellation = options.tessellation || 24;
  27176. var subdivisions = options.subdivisions || 1;
  27177. var hasRings = options.hasRings;
  27178. var enclose = options.enclose;
  27179. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27180. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27181. var faceUV = options.faceUV || new Array(3);
  27182. var faceColors = options.faceColors;
  27183. // default face colors and UV if undefined
  27184. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27185. var ringNb = (hasRings) ? subdivisions : 1;
  27186. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27187. var f;
  27188. for (f = 0; f < surfaceNb; f++) {
  27189. if (faceColors && faceColors[f] === undefined) {
  27190. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27191. }
  27192. }
  27193. for (f = 0; f < surfaceNb; f++) {
  27194. if (faceUV && faceUV[f] === undefined) {
  27195. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27196. }
  27197. }
  27198. var indices = [];
  27199. var positions = [];
  27200. var normals = [];
  27201. var uvs = [];
  27202. var colors = [];
  27203. var angle_step = Math.PI * 2 * arc / tessellation;
  27204. var angle;
  27205. var h;
  27206. var radius;
  27207. var tan = (diameterBottom - diameterTop) / 2 / height;
  27208. var ringVertex = BABYLON.Vector3.Zero();
  27209. var ringNormal = BABYLON.Vector3.Zero();
  27210. var ringFirstVertex = BABYLON.Vector3.Zero();
  27211. var ringFirstNormal = BABYLON.Vector3.Zero();
  27212. var quadNormal = BABYLON.Vector3.Zero();
  27213. var Y = BABYLON.Axis.Y;
  27214. // positions, normals, uvs
  27215. var i;
  27216. var j;
  27217. var r;
  27218. var ringIdx = 1;
  27219. var s = 1; // surface index
  27220. var cs = 0;
  27221. var v = 0;
  27222. for (i = 0; i <= subdivisions; i++) {
  27223. h = i / subdivisions;
  27224. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27225. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27226. for (r = 0; r < ringIdx; r++) {
  27227. if (hasRings) {
  27228. s += r;
  27229. }
  27230. if (enclose) {
  27231. s += 2 * r;
  27232. }
  27233. for (j = 0; j <= tessellation; j++) {
  27234. angle = j * angle_step;
  27235. // position
  27236. ringVertex.x = Math.cos(-angle) * radius;
  27237. ringVertex.y = -height / 2 + h * height;
  27238. ringVertex.z = Math.sin(-angle) * radius;
  27239. // normal
  27240. if (diameterTop === 0 && i === subdivisions) {
  27241. // if no top cap, reuse former normals
  27242. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27243. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27244. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27245. }
  27246. else {
  27247. ringNormal.x = ringVertex.x;
  27248. ringNormal.z = ringVertex.z;
  27249. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27250. ringNormal.normalize();
  27251. }
  27252. // keep first ring vertex values for enclose
  27253. if (j === 0) {
  27254. ringFirstVertex.copyFrom(ringVertex);
  27255. ringFirstNormal.copyFrom(ringNormal);
  27256. }
  27257. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27258. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27259. if (hasRings) {
  27260. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27261. }
  27262. else {
  27263. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27264. }
  27265. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27266. if (faceColors) {
  27267. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27268. }
  27269. }
  27270. // if enclose, add four vertices and their dedicated normals
  27271. if (arc !== 1 && enclose) {
  27272. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27273. positions.push(0, ringVertex.y, 0);
  27274. positions.push(0, ringVertex.y, 0);
  27275. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27276. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27277. quadNormal.normalize();
  27278. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27279. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27280. quadNormal.normalize();
  27281. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27282. if (hasRings) {
  27283. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27284. }
  27285. else {
  27286. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27287. }
  27288. uvs.push(faceUV[s + 1].x, v);
  27289. uvs.push(faceUV[s + 1].z, v);
  27290. if (hasRings) {
  27291. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27292. }
  27293. else {
  27294. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27295. }
  27296. uvs.push(faceUV[s + 2].x, v);
  27297. uvs.push(faceUV[s + 2].z, v);
  27298. if (faceColors) {
  27299. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27300. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27301. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27302. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27303. }
  27304. }
  27305. if (cs !== s) {
  27306. cs = s;
  27307. }
  27308. }
  27309. }
  27310. // indices
  27311. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27312. var s;
  27313. i = 0;
  27314. for (s = 0; s < subdivisions; s++) {
  27315. for (j = 0; j < tessellation; j++) {
  27316. var i0 = i * (e + 1) + j;
  27317. var i1 = (i + 1) * (e + 1) + j;
  27318. var i2 = i * (e + 1) + (j + 1);
  27319. var i3 = (i + 1) * (e + 1) + (j + 1);
  27320. indices.push(i0, i1, i2);
  27321. indices.push(i3, i2, i1);
  27322. }
  27323. if (arc !== 1 && enclose) {
  27324. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27325. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27326. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27327. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27328. }
  27329. i = (hasRings) ? (i + 2) : (i + 1);
  27330. }
  27331. // Caps
  27332. var createCylinderCap = function (isTop) {
  27333. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27334. if (radius === 0) {
  27335. return;
  27336. }
  27337. // Cap positions, normals & uvs
  27338. var angle;
  27339. var circleVector;
  27340. var i;
  27341. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27342. var c;
  27343. if (faceColors) {
  27344. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27345. }
  27346. // cap center
  27347. var vbase = positions.length / 3;
  27348. var offset = isTop ? height / 2 : -height / 2;
  27349. var center = new BABYLON.Vector3(0, offset, 0);
  27350. positions.push(center.x, center.y, center.z);
  27351. normals.push(0, isTop ? 1 : -1, 0);
  27352. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27353. if (faceColors) {
  27354. colors.push(c.r, c.g, c.b, c.a);
  27355. }
  27356. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27357. for (i = 0; i <= tessellation; i++) {
  27358. angle = Math.PI * 2 * i * arc / tessellation;
  27359. var cos = Math.cos(-angle);
  27360. var sin = Math.sin(-angle);
  27361. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27362. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27363. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27364. normals.push(0, isTop ? 1 : -1, 0);
  27365. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27366. if (faceColors) {
  27367. colors.push(c.r, c.g, c.b, c.a);
  27368. }
  27369. }
  27370. // Cap indices
  27371. for (i = 0; i < tessellation; i++) {
  27372. if (!isTop) {
  27373. indices.push(vbase);
  27374. indices.push(vbase + (i + 1));
  27375. indices.push(vbase + (i + 2));
  27376. }
  27377. else {
  27378. indices.push(vbase);
  27379. indices.push(vbase + (i + 2));
  27380. indices.push(vbase + (i + 1));
  27381. }
  27382. }
  27383. };
  27384. // add caps to geometry
  27385. createCylinderCap(false);
  27386. createCylinderCap(true);
  27387. // Sides
  27388. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27389. var vertexData = new VertexData();
  27390. vertexData.indices = indices;
  27391. vertexData.positions = positions;
  27392. vertexData.normals = normals;
  27393. vertexData.uvs = uvs;
  27394. if (faceColors) {
  27395. vertexData.colors = colors;
  27396. }
  27397. return vertexData;
  27398. };
  27399. /**
  27400. * Creates the VertexData of the Torus.
  27401. */
  27402. VertexData.CreateTorus = function (options) {
  27403. var indices = [];
  27404. var positions = [];
  27405. var normals = [];
  27406. var uvs = [];
  27407. var diameter = options.diameter || 1;
  27408. var thickness = options.thickness || 0.5;
  27409. var tessellation = options.tessellation || 16;
  27410. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27411. var stride = tessellation + 1;
  27412. for (var i = 0; i <= tessellation; i++) {
  27413. var u = i / tessellation;
  27414. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27415. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27416. for (var j = 0; j <= tessellation; j++) {
  27417. var v = 1 - j / tessellation;
  27418. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27419. var dx = Math.cos(innerAngle);
  27420. var dy = Math.sin(innerAngle);
  27421. // Create a vertex.
  27422. var normal = new BABYLON.Vector3(dx, dy, 0);
  27423. var position = normal.scale(thickness / 2);
  27424. var textureCoordinate = new BABYLON.Vector2(u, v);
  27425. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27426. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27427. positions.push(position.x, position.y, position.z);
  27428. normals.push(normal.x, normal.y, normal.z);
  27429. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27430. // And create indices for two triangles.
  27431. var nextI = (i + 1) % stride;
  27432. var nextJ = (j + 1) % stride;
  27433. indices.push(i * stride + j);
  27434. indices.push(i * stride + nextJ);
  27435. indices.push(nextI * stride + j);
  27436. indices.push(i * stride + nextJ);
  27437. indices.push(nextI * stride + nextJ);
  27438. indices.push(nextI * stride + j);
  27439. }
  27440. }
  27441. // Sides
  27442. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27443. // Result
  27444. var vertexData = new VertexData();
  27445. vertexData.indices = indices;
  27446. vertexData.positions = positions;
  27447. vertexData.normals = normals;
  27448. vertexData.uvs = uvs;
  27449. return vertexData;
  27450. };
  27451. /**
  27452. * Creates the VertexData of the LineSystem.
  27453. */
  27454. VertexData.CreateLineSystem = function (options) {
  27455. var indices = [];
  27456. var positions = [];
  27457. var lines = options.lines;
  27458. var idx = 0;
  27459. for (var l = 0; l < lines.length; l++) {
  27460. var points = lines[l];
  27461. for (var index = 0; index < points.length; index++) {
  27462. positions.push(points[index].x, points[index].y, points[index].z);
  27463. if (index > 0) {
  27464. indices.push(idx - 1);
  27465. indices.push(idx);
  27466. }
  27467. idx++;
  27468. }
  27469. }
  27470. var vertexData = new VertexData();
  27471. vertexData.indices = indices;
  27472. vertexData.positions = positions;
  27473. return vertexData;
  27474. };
  27475. /**
  27476. * Create the VertexData of the DashedLines.
  27477. */
  27478. VertexData.CreateDashedLines = function (options) {
  27479. var dashSize = options.dashSize || 3;
  27480. var gapSize = options.gapSize || 1;
  27481. var dashNb = options.dashNb || 200;
  27482. var points = options.points;
  27483. var positions = new Array();
  27484. var indices = new Array();
  27485. var curvect = BABYLON.Vector3.Zero();
  27486. var lg = 0;
  27487. var nb = 0;
  27488. var shft = 0;
  27489. var dashshft = 0;
  27490. var curshft = 0;
  27491. var idx = 0;
  27492. var i = 0;
  27493. for (i = 0; i < points.length - 1; i++) {
  27494. points[i + 1].subtractToRef(points[i], curvect);
  27495. lg += curvect.length();
  27496. }
  27497. shft = lg / dashNb;
  27498. dashshft = dashSize * shft / (dashSize + gapSize);
  27499. for (i = 0; i < points.length - 1; i++) {
  27500. points[i + 1].subtractToRef(points[i], curvect);
  27501. nb = Math.floor(curvect.length() / shft);
  27502. curvect.normalize();
  27503. for (var j = 0; j < nb; j++) {
  27504. curshft = shft * j;
  27505. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27506. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27507. indices.push(idx, idx + 1);
  27508. idx += 2;
  27509. }
  27510. }
  27511. // Result
  27512. var vertexData = new VertexData();
  27513. vertexData.positions = positions;
  27514. vertexData.indices = indices;
  27515. return vertexData;
  27516. };
  27517. /**
  27518. * Creates the VertexData of the Ground.
  27519. */
  27520. VertexData.CreateGround = function (options) {
  27521. var indices = [];
  27522. var positions = [];
  27523. var normals = [];
  27524. var uvs = [];
  27525. var row, col;
  27526. var width = options.width || 1;
  27527. var height = options.height || 1;
  27528. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27529. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27530. for (row = 0; row <= subdivisionsY; row++) {
  27531. for (col = 0; col <= subdivisionsX; col++) {
  27532. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27533. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27534. positions.push(position.x, position.y, position.z);
  27535. normals.push(normal.x, normal.y, normal.z);
  27536. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27537. }
  27538. }
  27539. for (row = 0; row < subdivisionsY; row++) {
  27540. for (col = 0; col < subdivisionsX; col++) {
  27541. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27542. indices.push(col + 1 + row * (subdivisionsX + 1));
  27543. indices.push(col + row * (subdivisionsX + 1));
  27544. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27545. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27546. indices.push(col + row * (subdivisionsX + 1));
  27547. }
  27548. }
  27549. // Result
  27550. var vertexData = new VertexData();
  27551. vertexData.indices = indices;
  27552. vertexData.positions = positions;
  27553. vertexData.normals = normals;
  27554. vertexData.uvs = uvs;
  27555. return vertexData;
  27556. };
  27557. /**
  27558. * Creates the VertexData of the TiledGround.
  27559. */
  27560. VertexData.CreateTiledGround = function (options) {
  27561. var xmin = options.xmin || -1.0;
  27562. var zmin = options.zmin || -1.0;
  27563. var xmax = options.xmax || 1.0;
  27564. var zmax = options.zmax || 1.0;
  27565. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27566. var precision = options.precision || { w: 1, h: 1 };
  27567. var indices = [];
  27568. var positions = [];
  27569. var normals = [];
  27570. var uvs = [];
  27571. var row, col, tileRow, tileCol;
  27572. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27573. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27574. precision.w = (precision.w < 1) ? 1 : precision.w;
  27575. precision.h = (precision.h < 1) ? 1 : precision.h;
  27576. var tileSize = {
  27577. 'w': (xmax - xmin) / subdivisions.w,
  27578. 'h': (zmax - zmin) / subdivisions.h
  27579. };
  27580. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27581. // Indices
  27582. var base = positions.length / 3;
  27583. var rowLength = precision.w + 1;
  27584. for (row = 0; row < precision.h; row++) {
  27585. for (col = 0; col < precision.w; col++) {
  27586. var square = [
  27587. base + col + row * rowLength,
  27588. base + (col + 1) + row * rowLength,
  27589. base + (col + 1) + (row + 1) * rowLength,
  27590. base + col + (row + 1) * rowLength
  27591. ];
  27592. indices.push(square[1]);
  27593. indices.push(square[2]);
  27594. indices.push(square[3]);
  27595. indices.push(square[0]);
  27596. indices.push(square[1]);
  27597. indices.push(square[3]);
  27598. }
  27599. }
  27600. // Position, normals and uvs
  27601. var position = BABYLON.Vector3.Zero();
  27602. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27603. for (row = 0; row <= precision.h; row++) {
  27604. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27605. for (col = 0; col <= precision.w; col++) {
  27606. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27607. position.y = 0;
  27608. positions.push(position.x, position.y, position.z);
  27609. normals.push(normal.x, normal.y, normal.z);
  27610. uvs.push(col / precision.w, row / precision.h);
  27611. }
  27612. }
  27613. }
  27614. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27615. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27616. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27617. }
  27618. }
  27619. // Result
  27620. var vertexData = new VertexData();
  27621. vertexData.indices = indices;
  27622. vertexData.positions = positions;
  27623. vertexData.normals = normals;
  27624. vertexData.uvs = uvs;
  27625. return vertexData;
  27626. };
  27627. /**
  27628. * Creates the VertexData of the Ground designed from a heightmap.
  27629. */
  27630. VertexData.CreateGroundFromHeightMap = function (options) {
  27631. var indices = [];
  27632. var positions = [];
  27633. var normals = [];
  27634. var uvs = [];
  27635. var row, col;
  27636. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27637. // Vertices
  27638. for (row = 0; row <= options.subdivisions; row++) {
  27639. for (col = 0; col <= options.subdivisions; col++) {
  27640. 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));
  27641. // Compute height
  27642. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27643. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27644. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27645. var r = options.buffer[pos] / 255.0;
  27646. var g = options.buffer[pos + 1] / 255.0;
  27647. var b = options.buffer[pos + 2] / 255.0;
  27648. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27649. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27650. // Add vertex
  27651. positions.push(position.x, position.y, position.z);
  27652. normals.push(0, 0, 0);
  27653. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27654. }
  27655. }
  27656. // Indices
  27657. for (row = 0; row < options.subdivisions; row++) {
  27658. for (col = 0; col < options.subdivisions; col++) {
  27659. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27660. indices.push(col + 1 + row * (options.subdivisions + 1));
  27661. indices.push(col + row * (options.subdivisions + 1));
  27662. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27663. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27664. indices.push(col + row * (options.subdivisions + 1));
  27665. }
  27666. }
  27667. // Normals
  27668. VertexData.ComputeNormals(positions, indices, normals);
  27669. // Result
  27670. var vertexData = new VertexData();
  27671. vertexData.indices = indices;
  27672. vertexData.positions = positions;
  27673. vertexData.normals = normals;
  27674. vertexData.uvs = uvs;
  27675. return vertexData;
  27676. };
  27677. /**
  27678. * Creates the VertexData of the Plane.
  27679. */
  27680. VertexData.CreatePlane = function (options) {
  27681. var indices = [];
  27682. var positions = [];
  27683. var normals = [];
  27684. var uvs = [];
  27685. var width = options.width || options.size || 1;
  27686. var height = options.height || options.size || 1;
  27687. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27688. // Vertices
  27689. var halfWidth = width / 2.0;
  27690. var halfHeight = height / 2.0;
  27691. positions.push(-halfWidth, -halfHeight, 0);
  27692. normals.push(0, 0, -1.0);
  27693. uvs.push(0.0, 0.0);
  27694. positions.push(halfWidth, -halfHeight, 0);
  27695. normals.push(0, 0, -1.0);
  27696. uvs.push(1.0, 0.0);
  27697. positions.push(halfWidth, halfHeight, 0);
  27698. normals.push(0, 0, -1.0);
  27699. uvs.push(1.0, 1.0);
  27700. positions.push(-halfWidth, halfHeight, 0);
  27701. normals.push(0, 0, -1.0);
  27702. uvs.push(0.0, 1.0);
  27703. // Indices
  27704. indices.push(0);
  27705. indices.push(1);
  27706. indices.push(2);
  27707. indices.push(0);
  27708. indices.push(2);
  27709. indices.push(3);
  27710. // Sides
  27711. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27712. // Result
  27713. var vertexData = new VertexData();
  27714. vertexData.indices = indices;
  27715. vertexData.positions = positions;
  27716. vertexData.normals = normals;
  27717. vertexData.uvs = uvs;
  27718. return vertexData;
  27719. };
  27720. /**
  27721. * Creates the VertexData of the Disc or regular Polygon.
  27722. */
  27723. VertexData.CreateDisc = function (options) {
  27724. var positions = [];
  27725. var indices = [];
  27726. var normals = [];
  27727. var uvs = [];
  27728. var radius = options.radius || 0.5;
  27729. var tessellation = options.tessellation || 64;
  27730. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27731. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27732. // positions and uvs
  27733. positions.push(0, 0, 0); // disc center first
  27734. uvs.push(0.5, 0.5);
  27735. var theta = Math.PI * 2 * arc;
  27736. var step = theta / tessellation;
  27737. for (var a = 0; a < theta; a += step) {
  27738. var x = Math.cos(a);
  27739. var y = Math.sin(a);
  27740. var u = (x + 1) / 2;
  27741. var v = (1 - y) / 2;
  27742. positions.push(radius * x, radius * y, 0);
  27743. uvs.push(u, v);
  27744. }
  27745. if (arc === 1) {
  27746. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27747. uvs.push(uvs[2], uvs[3]);
  27748. }
  27749. //indices
  27750. var vertexNb = positions.length / 3;
  27751. for (var i = 1; i < vertexNb - 1; i++) {
  27752. indices.push(i + 1, 0, i);
  27753. }
  27754. // result
  27755. VertexData.ComputeNormals(positions, indices, normals);
  27756. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27757. var vertexData = new VertexData();
  27758. vertexData.indices = indices;
  27759. vertexData.positions = positions;
  27760. vertexData.normals = normals;
  27761. vertexData.uvs = uvs;
  27762. return vertexData;
  27763. };
  27764. /**
  27765. * Re-creates the VertexData of the Polygon for sideOrientation.
  27766. */
  27767. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27768. var faceUV = fUV || new Array(3);
  27769. var faceColors = fColors;
  27770. var colors = [];
  27771. // default face colors and UV if undefined
  27772. for (var f = 0; f < 3; f++) {
  27773. if (faceUV[f] === undefined) {
  27774. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27775. }
  27776. if (faceColors && faceColors[f] === undefined) {
  27777. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27778. }
  27779. }
  27780. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27781. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27782. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27783. var indices = polygon.getIndices();
  27784. // set face colours and textures
  27785. var idx = 0;
  27786. var face = 0;
  27787. for (var index = 0; index < normals.length; index += 3) {
  27788. //Edge Face no. 1
  27789. if (Math.abs(normals[index + 1]) < 0.001) {
  27790. face = 1;
  27791. }
  27792. //Top Face no. 0
  27793. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27794. face = 0;
  27795. }
  27796. //Bottom Face no. 2
  27797. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27798. face = 2;
  27799. }
  27800. idx = index / 3;
  27801. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27802. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27803. if (faceColors) {
  27804. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27805. }
  27806. }
  27807. // sides
  27808. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27809. // Result
  27810. var vertexData = new VertexData();
  27811. vertexData.indices = indices;
  27812. vertexData.positions = positions;
  27813. vertexData.normals = normals;
  27814. vertexData.uvs = uvs;
  27815. if (faceColors) {
  27816. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27817. vertexData.colors = totalColors;
  27818. }
  27819. return vertexData;
  27820. };
  27821. /**
  27822. * Creates the VertexData of the IcoSphere.
  27823. */
  27824. VertexData.CreateIcoSphere = function (options) {
  27825. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27826. var radius = options.radius || 1;
  27827. var flat = (options.flat === undefined) ? true : options.flat;
  27828. var subdivisions = options.subdivisions || 4;
  27829. var radiusX = options.radiusX || radius;
  27830. var radiusY = options.radiusY || radius;
  27831. var radiusZ = options.radiusZ || radius;
  27832. var t = (1 + Math.sqrt(5)) / 2;
  27833. // 12 vertex x,y,z
  27834. var ico_vertices = [
  27835. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27836. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27837. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27838. ];
  27839. // index of 3 vertex makes a face of icopshere
  27840. var ico_indices = [
  27841. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27842. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27843. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27844. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27845. ];
  27846. // vertex for uv have aliased position, not for UV
  27847. var vertices_unalias_id = [
  27848. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27849. // vertex alias
  27850. 0,
  27851. 2,
  27852. 3,
  27853. 3,
  27854. 3,
  27855. 4,
  27856. 7,
  27857. 8,
  27858. 9,
  27859. 9,
  27860. 10,
  27861. 11 // 23: B + 12
  27862. ];
  27863. // uv as integer step (not pixels !)
  27864. var ico_vertexuv = [
  27865. 5, 1, 3, 1, 6, 4, 0, 0,
  27866. 5, 3, 4, 2, 2, 2, 4, 0,
  27867. 2, 0, 1, 1, 6, 0, 6, 2,
  27868. // vertex alias (for same vertex on different faces)
  27869. 0, 4,
  27870. 3, 3,
  27871. 4, 4,
  27872. 3, 1,
  27873. 4, 2,
  27874. 4, 4,
  27875. 0, 2,
  27876. 1, 1,
  27877. 2, 2,
  27878. 3, 3,
  27879. 1, 3,
  27880. 2, 4 // 23: B + 12
  27881. ];
  27882. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27883. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27884. // First island of uv mapping
  27885. // v = 4h 3+ 2
  27886. // v = 3h 9+ 4
  27887. // v = 2h 9+ 5 B
  27888. // v = 1h 9 1 0
  27889. // v = 0h 3 8 7 A
  27890. // u = 0 1 2 3 4 5 6 *a
  27891. // Second island of uv mapping
  27892. // v = 4h 0+ B+ 4+
  27893. // v = 3h A+ 2+
  27894. // v = 2h 7+ 6 3+
  27895. // v = 1h 8+ 3+
  27896. // v = 0h
  27897. // u = 0 1 2 3 4 5 6 *a
  27898. // Face layout on texture UV mapping
  27899. // ============
  27900. // \ 4 /\ 16 / ======
  27901. // \ / \ / /\ 11 /
  27902. // \/ 7 \/ / \ /
  27903. // ======= / 10 \/
  27904. // /\ 17 /\ =======
  27905. // / \ / \ \ 15 /\
  27906. // / 8 \/ 12 \ \ / \
  27907. // ============ \/ 6 \
  27908. // \ 18 /\ ============
  27909. // \ / \ \ 5 /\ 0 /
  27910. // \/ 13 \ \ / \ /
  27911. // ======= \/ 1 \/
  27912. // =============
  27913. // /\ 19 /\ 2 /\
  27914. // / \ / \ / \
  27915. // / 14 \/ 9 \/ 3 \
  27916. // ===================
  27917. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27918. var ustep = 138 / 1024;
  27919. var vstep = 239 / 1024;
  27920. var uoffset = 60 / 1024;
  27921. var voffset = 26 / 1024;
  27922. // Second island should have margin, not to touch the first island
  27923. // avoid any borderline artefact in pixel rounding
  27924. var island_u_offset = -40 / 1024;
  27925. var island_v_offset = +20 / 1024;
  27926. // face is either island 0 or 1 :
  27927. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27928. var island = [
  27929. 0, 0, 0, 0, 1,
  27930. 0, 0, 1, 1, 0,
  27931. 0, 0, 1, 1, 0,
  27932. 0, 1, 1, 1, 0 // 15 - 19
  27933. ];
  27934. var indices = [];
  27935. var positions = [];
  27936. var normals = [];
  27937. var uvs = [];
  27938. var current_indice = 0;
  27939. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27940. var face_vertex_pos = new Array(3);
  27941. var face_vertex_uv = new Array(3);
  27942. var v012;
  27943. for (v012 = 0; v012 < 3; v012++) {
  27944. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27945. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27946. }
  27947. // create all with normals
  27948. for (var face = 0; face < 20; face++) {
  27949. // 3 vertex per face
  27950. for (v012 = 0; v012 < 3; v012++) {
  27951. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27952. var v_id = ico_indices[3 * face + v012];
  27953. // vertex have 3D position (x,y,z)
  27954. 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]);
  27955. // Normalize to get normal, then scale to radius
  27956. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27957. // uv Coordinates from vertex ID
  27958. 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);
  27959. }
  27960. // Subdivide the face (interpolate pos, norm, uv)
  27961. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27962. // - norm is linear interpolation of vertex corner normal
  27963. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27964. // - uv is linear interpolation
  27965. //
  27966. // Topology is as below for sub-divide by 2
  27967. // vertex shown as v0,v1,v2
  27968. // interp index is i1 to progress in range [v0,v1[
  27969. // interp index is i2 to progress in range [v0,v2[
  27970. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27971. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27972. //
  27973. //
  27974. // i2 v2
  27975. // ^ ^
  27976. // / / \
  27977. // / / \
  27978. // / / \
  27979. // / / (0,1) \
  27980. // / #---------\
  27981. // / / \ (0,0)'/ \
  27982. // / / \ / \
  27983. // / / \ / \
  27984. // / / (0,0) \ / (1,0) \
  27985. // / #---------#---------\
  27986. // v0 v1
  27987. //
  27988. // --------------------> i1
  27989. //
  27990. // interp of (i1,i2):
  27991. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27992. // along i1 : lerp(x0,x1, i1/(S-i2))
  27993. //
  27994. // centroid of triangle is needed to get help normal computation
  27995. // (c1,c2) are used for centroid location
  27996. var interp_vertex = function (i1, i2, c1, c2) {
  27997. // vertex is interpolated from
  27998. // - face_vertex_pos[0..2]
  27999. // - face_vertex_uv[0..2]
  28000. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28001. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28002. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28003. pos_interp.normalize();
  28004. var vertex_normal;
  28005. if (flat) {
  28006. // in flat mode, recalculate normal as face centroid normal
  28007. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28008. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28009. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28010. }
  28011. else {
  28012. // in smooth mode, recalculate normal from each single vertex position
  28013. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28014. }
  28015. // Vertex normal need correction due to X,Y,Z radius scaling
  28016. vertex_normal.x /= radiusX;
  28017. vertex_normal.y /= radiusY;
  28018. vertex_normal.z /= radiusZ;
  28019. vertex_normal.normalize();
  28020. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28021. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28022. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28023. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28024. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28025. uvs.push(uv_interp.x, uv_interp.y);
  28026. // push each vertex has member of a face
  28027. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28028. indices.push(current_indice);
  28029. current_indice++;
  28030. };
  28031. for (var i2 = 0; i2 < subdivisions; i2++) {
  28032. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28033. // face : (i1,i2) for /\ :
  28034. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28035. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28036. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28037. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28038. if (i1 + i2 + 1 < subdivisions) {
  28039. // face : (i1,i2)' for \/ :
  28040. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28041. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28042. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28043. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28044. }
  28045. }
  28046. }
  28047. }
  28048. // Sides
  28049. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28050. // Result
  28051. var vertexData = new VertexData();
  28052. vertexData.indices = indices;
  28053. vertexData.positions = positions;
  28054. vertexData.normals = normals;
  28055. vertexData.uvs = uvs;
  28056. return vertexData;
  28057. };
  28058. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28059. /**
  28060. * Creates the VertexData of the Polyhedron.
  28061. */
  28062. VertexData.CreatePolyhedron = function (options) {
  28063. // provided polyhedron types :
  28064. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28065. // 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)
  28066. var polyhedra = [];
  28067. 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]] };
  28068. 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]] };
  28069. polyhedra[2] = {
  28070. 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]],
  28071. 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]]
  28072. };
  28073. polyhedra[3] = {
  28074. 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]],
  28075. 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]]
  28076. };
  28077. polyhedra[4] = {
  28078. 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]],
  28079. 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]]
  28080. };
  28081. 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]] };
  28082. 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]] };
  28083. 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]] };
  28084. 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]] };
  28085. 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]] };
  28086. 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]] };
  28087. 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]] };
  28088. 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]] };
  28089. 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]] };
  28090. polyhedra[14] = {
  28091. 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]],
  28092. 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]]
  28093. };
  28094. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28095. var size = options.size;
  28096. var sizeX = options.sizeX || size || 1;
  28097. var sizeY = options.sizeY || size || 1;
  28098. var sizeZ = options.sizeZ || size || 1;
  28099. var data = options.custom || polyhedra[type];
  28100. var nbfaces = data.face.length;
  28101. var faceUV = options.faceUV || new Array(nbfaces);
  28102. var faceColors = options.faceColors;
  28103. var flat = (options.flat === undefined) ? true : options.flat;
  28104. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28105. var positions = [];
  28106. var indices = [];
  28107. var normals = [];
  28108. var uvs = [];
  28109. var colors = [];
  28110. var index = 0;
  28111. var faceIdx = 0; // face cursor in the array "indexes"
  28112. var indexes = [];
  28113. var i = 0;
  28114. var f = 0;
  28115. var u, v, ang, x, y, tmp;
  28116. // default face colors and UV if undefined
  28117. if (flat) {
  28118. for (f = 0; f < nbfaces; f++) {
  28119. if (faceColors && faceColors[f] === undefined) {
  28120. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28121. }
  28122. if (faceUV && faceUV[f] === undefined) {
  28123. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28124. }
  28125. }
  28126. }
  28127. if (!flat) {
  28128. for (i = 0; i < data.vertex.length; i++) {
  28129. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28130. uvs.push(0, 0);
  28131. }
  28132. for (f = 0; f < nbfaces; f++) {
  28133. for (i = 0; i < data.face[f].length - 2; i++) {
  28134. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28135. }
  28136. }
  28137. }
  28138. else {
  28139. for (f = 0; f < nbfaces; f++) {
  28140. var fl = data.face[f].length; // number of vertices of the current face
  28141. ang = 2 * Math.PI / fl;
  28142. x = 0.5 * Math.tan(ang / 2);
  28143. y = 0.5;
  28144. // positions, uvs, colors
  28145. for (i = 0; i < fl; i++) {
  28146. // positions
  28147. 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);
  28148. indexes.push(index);
  28149. index++;
  28150. // uvs
  28151. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28152. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28153. uvs.push(u, v);
  28154. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28155. y = x * Math.sin(ang) + y * Math.cos(ang);
  28156. x = tmp;
  28157. // colors
  28158. if (faceColors) {
  28159. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28160. }
  28161. }
  28162. // indices from indexes
  28163. for (i = 0; i < fl - 2; i++) {
  28164. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28165. }
  28166. faceIdx += fl;
  28167. }
  28168. }
  28169. VertexData.ComputeNormals(positions, indices, normals);
  28170. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28171. var vertexData = new VertexData();
  28172. vertexData.positions = positions;
  28173. vertexData.indices = indices;
  28174. vertexData.normals = normals;
  28175. vertexData.uvs = uvs;
  28176. if (faceColors && flat) {
  28177. vertexData.colors = colors;
  28178. }
  28179. return vertexData;
  28180. };
  28181. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28182. /**
  28183. * Creates the VertexData of the Torus Knot.
  28184. */
  28185. VertexData.CreateTorusKnot = function (options) {
  28186. var indices = [];
  28187. var positions = [];
  28188. var normals = [];
  28189. var uvs = [];
  28190. var radius = options.radius || 2;
  28191. var tube = options.tube || 0.5;
  28192. var radialSegments = options.radialSegments || 32;
  28193. var tubularSegments = options.tubularSegments || 32;
  28194. var p = options.p || 2;
  28195. var q = options.q || 3;
  28196. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28197. // Helper
  28198. var getPos = function (angle) {
  28199. var cu = Math.cos(angle);
  28200. var su = Math.sin(angle);
  28201. var quOverP = q / p * angle;
  28202. var cs = Math.cos(quOverP);
  28203. var tx = radius * (2 + cs) * 0.5 * cu;
  28204. var ty = radius * (2 + cs) * su * 0.5;
  28205. var tz = radius * Math.sin(quOverP) * 0.5;
  28206. return new BABYLON.Vector3(tx, ty, tz);
  28207. };
  28208. // Vertices
  28209. var i;
  28210. var j;
  28211. for (i = 0; i <= radialSegments; i++) {
  28212. var modI = i % radialSegments;
  28213. var u = modI / radialSegments * 2 * p * Math.PI;
  28214. var p1 = getPos(u);
  28215. var p2 = getPos(u + 0.01);
  28216. var tang = p2.subtract(p1);
  28217. var n = p2.add(p1);
  28218. var bitan = BABYLON.Vector3.Cross(tang, n);
  28219. n = BABYLON.Vector3.Cross(bitan, tang);
  28220. bitan.normalize();
  28221. n.normalize();
  28222. for (j = 0; j < tubularSegments; j++) {
  28223. var modJ = j % tubularSegments;
  28224. var v = modJ / tubularSegments * 2 * Math.PI;
  28225. var cx = -tube * Math.cos(v);
  28226. var cy = tube * Math.sin(v);
  28227. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28228. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28229. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28230. uvs.push(i / radialSegments);
  28231. uvs.push(j / tubularSegments);
  28232. }
  28233. }
  28234. for (i = 0; i < radialSegments; i++) {
  28235. for (j = 0; j < tubularSegments; j++) {
  28236. var jNext = (j + 1) % tubularSegments;
  28237. var a = i * tubularSegments + j;
  28238. var b = (i + 1) * tubularSegments + j;
  28239. var c = (i + 1) * tubularSegments + jNext;
  28240. var d = i * tubularSegments + jNext;
  28241. indices.push(d);
  28242. indices.push(b);
  28243. indices.push(a);
  28244. indices.push(d);
  28245. indices.push(c);
  28246. indices.push(b);
  28247. }
  28248. }
  28249. // Normals
  28250. VertexData.ComputeNormals(positions, indices, normals);
  28251. // Sides
  28252. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28253. // Result
  28254. var vertexData = new VertexData();
  28255. vertexData.indices = indices;
  28256. vertexData.positions = positions;
  28257. vertexData.normals = normals;
  28258. vertexData.uvs = uvs;
  28259. return vertexData;
  28260. };
  28261. // Tools
  28262. /**
  28263. * @param {any} - positions (number[] or Float32Array)
  28264. * @param {any} - indices (number[] or Uint16Array)
  28265. * @param {any} - normals (number[] or Float32Array)
  28266. * options (optional) :
  28267. * facetPositions : optional array of facet positions (vector3)
  28268. * facetNormals : optional array of facet normals (vector3)
  28269. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28270. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28271. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28272. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28273. * bInfo : optional bounding info, required for facetPartitioning computation
  28274. */
  28275. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28276. // temporary scalar variables
  28277. var index = 0; // facet index
  28278. var p1p2x = 0.0; // p1p2 vector x coordinate
  28279. var p1p2y = 0.0; // p1p2 vector y coordinate
  28280. var p1p2z = 0.0; // p1p2 vector z coordinate
  28281. var p3p2x = 0.0; // p3p2 vector x coordinate
  28282. var p3p2y = 0.0; // p3p2 vector y coordinate
  28283. var p3p2z = 0.0; // p3p2 vector z coordinate
  28284. var faceNormalx = 0.0; // facet normal x coordinate
  28285. var faceNormaly = 0.0; // facet normal y coordinate
  28286. var faceNormalz = 0.0; // facet normal z coordinate
  28287. var length = 0.0; // facet normal length before normalization
  28288. var v1x = 0; // vector1 x index in the positions array
  28289. var v1y = 0; // vector1 y index in the positions array
  28290. var v1z = 0; // vector1 z index in the positions array
  28291. var v2x = 0; // vector2 x index in the positions array
  28292. var v2y = 0; // vector2 y index in the positions array
  28293. var v2z = 0; // vector2 z index in the positions array
  28294. var v3x = 0; // vector3 x index in the positions array
  28295. var v3y = 0; // vector3 y index in the positions array
  28296. var v3z = 0; // vector3 z index in the positions array
  28297. var computeFacetNormals = false;
  28298. var computeFacetPositions = false;
  28299. var computeFacetPartitioning = false;
  28300. var faceNormalSign = 1;
  28301. if (options) {
  28302. computeFacetNormals = (options.facetNormals) ? true : false;
  28303. computeFacetPositions = (options.facetPositions) ? true : false;
  28304. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28305. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28306. }
  28307. // facetPartitioning reinit if needed
  28308. if (computeFacetPartitioning) {
  28309. var ox = 0; // X partitioning index for facet position
  28310. var oy = 0; // Y partinioning index for facet position
  28311. var oz = 0; // Z partinioning index for facet position
  28312. var b1x = 0; // X partitioning index for facet v1 vertex
  28313. var b1y = 0; // Y partitioning index for facet v1 vertex
  28314. var b1z = 0; // z partitioning index for facet v1 vertex
  28315. var b2x = 0; // X partitioning index for facet v2 vertex
  28316. var b2y = 0; // Y partitioning index for facet v2 vertex
  28317. var b2z = 0; // Z partitioning index for facet v2 vertex
  28318. var b3x = 0; // X partitioning index for facet v3 vertex
  28319. var b3y = 0; // Y partitioning index for facet v3 vertex
  28320. var b3z = 0; // Z partitioning index for facet v3 vertex
  28321. var block_idx_o = 0; // facet barycenter block index
  28322. var block_idx_v1 = 0; // v1 vertex block index
  28323. var block_idx_v2 = 0; // v2 vertex block index
  28324. var block_idx_v3 = 0; // v3 vertex block index
  28325. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28326. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28327. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28328. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28329. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28330. var subSq = options.subDiv.max * options.subDiv.max;
  28331. options.facetPartitioning.length = 0;
  28332. }
  28333. // reset the normals
  28334. for (index = 0; index < positions.length; index++) {
  28335. normals[index] = 0.0;
  28336. }
  28337. // Loop : 1 indice triplet = 1 facet
  28338. var nbFaces = indices.length / 3;
  28339. for (index = 0; index < nbFaces; index++) {
  28340. // get the indexes of the coordinates of each vertex of the facet
  28341. v1x = indices[index * 3] * 3;
  28342. v1y = v1x + 1;
  28343. v1z = v1x + 2;
  28344. v2x = indices[index * 3 + 1] * 3;
  28345. v2y = v2x + 1;
  28346. v2z = v2x + 2;
  28347. v3x = indices[index * 3 + 2] * 3;
  28348. v3y = v3x + 1;
  28349. v3z = v3x + 2;
  28350. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28351. p1p2y = positions[v1y] - positions[v2y];
  28352. p1p2z = positions[v1z] - positions[v2z];
  28353. p3p2x = positions[v3x] - positions[v2x];
  28354. p3p2y = positions[v3y] - positions[v2y];
  28355. p3p2z = positions[v3z] - positions[v2z];
  28356. // compute the face normal with the cross product
  28357. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28358. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28359. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28360. // normalize this normal and store it in the array facetData
  28361. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28362. length = (length === 0) ? 1.0 : length;
  28363. faceNormalx /= length;
  28364. faceNormaly /= length;
  28365. faceNormalz /= length;
  28366. if (computeFacetNormals) {
  28367. options.facetNormals[index].x = faceNormalx;
  28368. options.facetNormals[index].y = faceNormaly;
  28369. options.facetNormals[index].z = faceNormalz;
  28370. }
  28371. if (computeFacetPositions) {
  28372. // compute and the facet barycenter coordinates in the array facetPositions
  28373. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28374. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28375. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28376. }
  28377. if (computeFacetPartitioning) {
  28378. // store the facet indexes in arrays in the main facetPartitioning array :
  28379. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28380. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28381. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28382. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28383. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28384. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28385. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28386. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28387. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28388. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28389. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28390. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28391. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28392. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28393. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28394. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28395. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28396. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28397. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28398. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28399. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28400. // push each facet index in each block containing the vertex
  28401. options.facetPartitioning[block_idx_v1].push(index);
  28402. if (block_idx_v2 != block_idx_v1) {
  28403. options.facetPartitioning[block_idx_v2].push(index);
  28404. }
  28405. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28406. options.facetPartitioning[block_idx_v3].push(index);
  28407. }
  28408. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28409. options.facetPartitioning[block_idx_o].push(index);
  28410. }
  28411. }
  28412. // compute the normals anyway
  28413. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28414. normals[v1y] += faceNormaly;
  28415. normals[v1z] += faceNormalz;
  28416. normals[v2x] += faceNormalx;
  28417. normals[v2y] += faceNormaly;
  28418. normals[v2z] += faceNormalz;
  28419. normals[v3x] += faceNormalx;
  28420. normals[v3y] += faceNormaly;
  28421. normals[v3z] += faceNormalz;
  28422. }
  28423. // last normalization of each normal
  28424. for (index = 0; index < normals.length / 3; index++) {
  28425. faceNormalx = normals[index * 3];
  28426. faceNormaly = normals[index * 3 + 1];
  28427. faceNormalz = normals[index * 3 + 2];
  28428. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28429. length = (length === 0) ? 1.0 : length;
  28430. faceNormalx /= length;
  28431. faceNormaly /= length;
  28432. faceNormalz /= length;
  28433. normals[index * 3] = faceNormalx;
  28434. normals[index * 3 + 1] = faceNormaly;
  28435. normals[index * 3 + 2] = faceNormalz;
  28436. }
  28437. };
  28438. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28439. var li = indices.length;
  28440. var ln = normals.length;
  28441. var i;
  28442. var n;
  28443. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28444. switch (sideOrientation) {
  28445. case BABYLON.Mesh.FRONTSIDE:
  28446. // nothing changed
  28447. break;
  28448. case BABYLON.Mesh.BACKSIDE:
  28449. var tmp;
  28450. // indices
  28451. for (i = 0; i < li; i += 3) {
  28452. tmp = indices[i];
  28453. indices[i] = indices[i + 2];
  28454. indices[i + 2] = tmp;
  28455. }
  28456. // normals
  28457. for (n = 0; n < ln; n++) {
  28458. normals[n] = -normals[n];
  28459. }
  28460. break;
  28461. case BABYLON.Mesh.DOUBLESIDE:
  28462. // positions
  28463. var lp = positions.length;
  28464. var l = lp / 3;
  28465. for (var p = 0; p < lp; p++) {
  28466. positions[lp + p] = positions[p];
  28467. }
  28468. // indices
  28469. for (i = 0; i < li; i += 3) {
  28470. indices[i + li] = indices[i + 2] + l;
  28471. indices[i + 1 + li] = indices[i + 1] + l;
  28472. indices[i + 2 + li] = indices[i] + l;
  28473. }
  28474. // normals
  28475. for (n = 0; n < ln; n++) {
  28476. normals[ln + n] = -normals[n];
  28477. }
  28478. // uvs
  28479. var lu = uvs.length;
  28480. var u = 0;
  28481. for (u = 0; u < lu; u++) {
  28482. uvs[u + lu] = uvs[u];
  28483. }
  28484. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28485. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28486. u = 0;
  28487. for (i = 0; i < lu / 2; i++) {
  28488. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28489. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28490. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28491. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28492. u += 2;
  28493. }
  28494. break;
  28495. }
  28496. };
  28497. /**
  28498. * Creates a new VertexData from the imported parameters.
  28499. */
  28500. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28501. var vertexData = new VertexData();
  28502. // positions
  28503. var positions = parsedVertexData.positions;
  28504. if (positions) {
  28505. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28506. }
  28507. // normals
  28508. var normals = parsedVertexData.normals;
  28509. if (normals) {
  28510. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28511. }
  28512. // tangents
  28513. var tangents = parsedVertexData.tangents;
  28514. if (tangents) {
  28515. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28516. }
  28517. // uvs
  28518. var uvs = parsedVertexData.uvs;
  28519. if (uvs) {
  28520. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28521. }
  28522. // uv2s
  28523. var uv2s = parsedVertexData.uv2s;
  28524. if (uv2s) {
  28525. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28526. }
  28527. // uv3s
  28528. var uv3s = parsedVertexData.uv3s;
  28529. if (uv3s) {
  28530. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28531. }
  28532. // uv4s
  28533. var uv4s = parsedVertexData.uv4s;
  28534. if (uv4s) {
  28535. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28536. }
  28537. // uv5s
  28538. var uv5s = parsedVertexData.uv5s;
  28539. if (uv5s) {
  28540. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28541. }
  28542. // uv6s
  28543. var uv6s = parsedVertexData.uv6s;
  28544. if (uv6s) {
  28545. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28546. }
  28547. // colors
  28548. var colors = parsedVertexData.colors;
  28549. if (colors) {
  28550. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28551. }
  28552. // matricesIndices
  28553. var matricesIndices = parsedVertexData.matricesIndices;
  28554. if (matricesIndices) {
  28555. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28556. }
  28557. // matricesWeights
  28558. var matricesWeights = parsedVertexData.matricesWeights;
  28559. if (matricesWeights) {
  28560. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28561. }
  28562. // indices
  28563. var indices = parsedVertexData.indices;
  28564. if (indices) {
  28565. vertexData.indices = indices;
  28566. }
  28567. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28568. };
  28569. return VertexData;
  28570. }());
  28571. BABYLON.VertexData = VertexData;
  28572. })(BABYLON || (BABYLON = {}));
  28573. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28574. var BABYLON;
  28575. (function (BABYLON) {
  28576. var Geometry = (function () {
  28577. function Geometry(id, scene, vertexData, updatable, mesh) {
  28578. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28579. this._totalVertices = 0;
  28580. this._isDisposed = false;
  28581. this.id = id;
  28582. this._engine = scene.getEngine();
  28583. this._meshes = [];
  28584. this._scene = scene;
  28585. //Init vertex buffer cache
  28586. this._vertexBuffers = {};
  28587. this._indices = [];
  28588. this._updatable = updatable;
  28589. // vertexData
  28590. if (vertexData) {
  28591. this.setAllVerticesData(vertexData, updatable);
  28592. }
  28593. else {
  28594. this._totalVertices = 0;
  28595. this._indices = [];
  28596. }
  28597. if (this._engine.getCaps().vertexArrayObject) {
  28598. this._vertexArrayObjects = {};
  28599. }
  28600. // applyToMesh
  28601. if (mesh) {
  28602. if (mesh.getClassName() === "LinesMesh") {
  28603. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28604. this.updateExtend();
  28605. }
  28606. this.applyToMesh(mesh);
  28607. mesh.computeWorldMatrix(true);
  28608. }
  28609. }
  28610. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28611. /**
  28612. * 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
  28613. * @returns The Bias Vector
  28614. */
  28615. get: function () {
  28616. return this._boundingBias;
  28617. },
  28618. set: function (value) {
  28619. if (this._boundingBias && this._boundingBias.equals(value)) {
  28620. return;
  28621. }
  28622. this._boundingBias = value.clone();
  28623. this.updateBoundingInfo(true, null);
  28624. },
  28625. enumerable: true,
  28626. configurable: true
  28627. });
  28628. Object.defineProperty(Geometry.prototype, "extend", {
  28629. get: function () {
  28630. return this._extend;
  28631. },
  28632. enumerable: true,
  28633. configurable: true
  28634. });
  28635. Geometry.prototype.getScene = function () {
  28636. return this._scene;
  28637. };
  28638. Geometry.prototype.getEngine = function () {
  28639. return this._engine;
  28640. };
  28641. Geometry.prototype.isReady = function () {
  28642. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28643. };
  28644. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28645. get: function () {
  28646. for (var index = 0; index < this._meshes.length; index++) {
  28647. if (!this._meshes[index].doNotSerialize) {
  28648. return false;
  28649. }
  28650. }
  28651. return true;
  28652. },
  28653. enumerable: true,
  28654. configurable: true
  28655. });
  28656. Geometry.prototype._rebuild = function () {
  28657. if (this._vertexArrayObjects) {
  28658. this._vertexArrayObjects = {};
  28659. }
  28660. // Index buffer
  28661. if (this._meshes.length !== 0 && this._indices) {
  28662. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28663. }
  28664. // Vertex buffers
  28665. for (var key in this._vertexBuffers) {
  28666. var vertexBuffer = this._vertexBuffers[key];
  28667. vertexBuffer._rebuild();
  28668. }
  28669. };
  28670. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28671. vertexData.applyToGeometry(this, updatable);
  28672. this.notifyUpdate();
  28673. };
  28674. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28675. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28676. this.setVerticesBuffer(buffer);
  28677. };
  28678. Geometry.prototype.removeVerticesData = function (kind) {
  28679. if (this._vertexBuffers[kind]) {
  28680. this._vertexBuffers[kind].dispose();
  28681. delete this._vertexBuffers[kind];
  28682. }
  28683. };
  28684. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28685. var kind = buffer.getKind();
  28686. if (this._vertexBuffers[kind]) {
  28687. this._vertexBuffers[kind].dispose();
  28688. }
  28689. this._vertexBuffers[kind] = buffer;
  28690. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28691. var data = buffer.getData();
  28692. var stride = buffer.getStrideSize();
  28693. this._totalVertices = data.length / stride;
  28694. this.updateExtend(data, stride);
  28695. this._resetPointsArrayCache();
  28696. var meshes = this._meshes;
  28697. var numOfMeshes = meshes.length;
  28698. for (var index = 0; index < numOfMeshes; index++) {
  28699. var mesh = meshes[index];
  28700. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28701. mesh._createGlobalSubMesh(false);
  28702. mesh.computeWorldMatrix(true);
  28703. }
  28704. }
  28705. this.notifyUpdate(kind);
  28706. if (this._vertexArrayObjects) {
  28707. this._disposeVertexArrayObjects();
  28708. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28709. }
  28710. };
  28711. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28712. var vertexBuffer = this.getVertexBuffer(kind);
  28713. if (!vertexBuffer) {
  28714. return;
  28715. }
  28716. vertexBuffer.updateDirectly(data, offset);
  28717. this.notifyUpdate(kind);
  28718. };
  28719. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28720. var vertexBuffer = this.getVertexBuffer(kind);
  28721. if (!vertexBuffer) {
  28722. return;
  28723. }
  28724. vertexBuffer.update(data);
  28725. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28726. var stride = vertexBuffer.getStrideSize();
  28727. this._totalVertices = data.length / stride;
  28728. this.updateBoundingInfo(updateExtends, data);
  28729. }
  28730. this.notifyUpdate(kind);
  28731. };
  28732. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28733. if (updateExtends) {
  28734. this.updateExtend(data);
  28735. }
  28736. var meshes = this._meshes;
  28737. var numOfMeshes = meshes.length;
  28738. this._resetPointsArrayCache();
  28739. for (var index = 0; index < numOfMeshes; index++) {
  28740. var mesh = meshes[index];
  28741. if (updateExtends) {
  28742. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28743. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28744. var subMesh = mesh.subMeshes[subIndex];
  28745. subMesh.refreshBoundingInfo();
  28746. }
  28747. }
  28748. }
  28749. };
  28750. Geometry.prototype._bind = function (effect, indexToBind) {
  28751. if (indexToBind === void 0) { indexToBind = undefined; }
  28752. if (indexToBind === undefined) {
  28753. indexToBind = this._indexBuffer;
  28754. }
  28755. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28756. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28757. return;
  28758. }
  28759. // Using VAO
  28760. if (!this._vertexArrayObjects[effect.key]) {
  28761. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28762. }
  28763. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28764. };
  28765. Geometry.prototype.getTotalVertices = function () {
  28766. if (!this.isReady()) {
  28767. return 0;
  28768. }
  28769. return this._totalVertices;
  28770. };
  28771. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28772. var vertexBuffer = this.getVertexBuffer(kind);
  28773. if (!vertexBuffer) {
  28774. return null;
  28775. }
  28776. var orig = vertexBuffer.getData();
  28777. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28778. return orig;
  28779. }
  28780. else {
  28781. var len = orig.length;
  28782. var copy = [];
  28783. for (var i = 0; i < len; i++) {
  28784. copy.push(orig[i]);
  28785. }
  28786. return copy;
  28787. }
  28788. };
  28789. Geometry.prototype.getVertexBuffer = function (kind) {
  28790. if (!this.isReady()) {
  28791. return null;
  28792. }
  28793. return this._vertexBuffers[kind];
  28794. };
  28795. Geometry.prototype.getVertexBuffers = function () {
  28796. if (!this.isReady()) {
  28797. return null;
  28798. }
  28799. return this._vertexBuffers;
  28800. };
  28801. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28802. if (!this._vertexBuffers) {
  28803. if (this._delayInfo) {
  28804. return this._delayInfo.indexOf(kind) !== -1;
  28805. }
  28806. return false;
  28807. }
  28808. return this._vertexBuffers[kind] !== undefined;
  28809. };
  28810. Geometry.prototype.getVerticesDataKinds = function () {
  28811. var result = [];
  28812. var kind;
  28813. if (!this._vertexBuffers && this._delayInfo) {
  28814. for (kind in this._delayInfo) {
  28815. result.push(kind);
  28816. }
  28817. }
  28818. else {
  28819. for (kind in this._vertexBuffers) {
  28820. result.push(kind);
  28821. }
  28822. }
  28823. return result;
  28824. };
  28825. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28826. if (this._indexBuffer) {
  28827. this._engine._releaseBuffer(this._indexBuffer);
  28828. }
  28829. this._disposeVertexArrayObjects();
  28830. this._indices = indices;
  28831. if (this._meshes.length !== 0 && this._indices) {
  28832. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28833. }
  28834. if (totalVertices !== undefined) {
  28835. this._totalVertices = totalVertices;
  28836. }
  28837. var meshes = this._meshes;
  28838. var numOfMeshes = meshes.length;
  28839. for (var index = 0; index < numOfMeshes; index++) {
  28840. meshes[index]._createGlobalSubMesh(true);
  28841. }
  28842. this.notifyUpdate();
  28843. };
  28844. Geometry.prototype.getTotalIndices = function () {
  28845. if (!this.isReady()) {
  28846. return 0;
  28847. }
  28848. return this._indices.length;
  28849. };
  28850. Geometry.prototype.getIndices = function (copyWhenShared) {
  28851. if (!this.isReady()) {
  28852. return null;
  28853. }
  28854. var orig = this._indices;
  28855. if (!copyWhenShared || this._meshes.length === 1) {
  28856. return orig;
  28857. }
  28858. else {
  28859. var len = orig.length;
  28860. var copy = [];
  28861. for (var i = 0; i < len; i++) {
  28862. copy.push(orig[i]);
  28863. }
  28864. return copy;
  28865. }
  28866. };
  28867. Geometry.prototype.getIndexBuffer = function () {
  28868. if (!this.isReady()) {
  28869. return null;
  28870. }
  28871. return this._indexBuffer;
  28872. };
  28873. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28874. if (!effect || !this._vertexArrayObjects) {
  28875. return;
  28876. }
  28877. if (this._vertexArrayObjects[effect.key]) {
  28878. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28879. delete this._vertexArrayObjects[effect.key];
  28880. }
  28881. };
  28882. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28883. var meshes = this._meshes;
  28884. var index = meshes.indexOf(mesh);
  28885. if (index === -1) {
  28886. return;
  28887. }
  28888. meshes.splice(index, 1);
  28889. mesh._geometry = null;
  28890. if (meshes.length === 0 && shouldDispose) {
  28891. this.dispose();
  28892. }
  28893. };
  28894. Geometry.prototype.applyToMesh = function (mesh) {
  28895. if (mesh._geometry === this) {
  28896. return;
  28897. }
  28898. var previousGeometry = mesh._geometry;
  28899. if (previousGeometry) {
  28900. previousGeometry.releaseForMesh(mesh);
  28901. }
  28902. var meshes = this._meshes;
  28903. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28904. mesh._geometry = this;
  28905. this._scene.pushGeometry(this);
  28906. meshes.push(mesh);
  28907. if (this.isReady()) {
  28908. this._applyToMesh(mesh);
  28909. }
  28910. else {
  28911. mesh._boundingInfo = this._boundingInfo;
  28912. }
  28913. };
  28914. Geometry.prototype.updateExtend = function (data, stride) {
  28915. if (data === void 0) { data = null; }
  28916. if (!data) {
  28917. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28918. }
  28919. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28920. };
  28921. Geometry.prototype._applyToMesh = function (mesh) {
  28922. var numOfMeshes = this._meshes.length;
  28923. // vertexBuffers
  28924. for (var kind in this._vertexBuffers) {
  28925. if (numOfMeshes === 1) {
  28926. this._vertexBuffers[kind].create();
  28927. }
  28928. var buffer = this._vertexBuffers[kind].getBuffer();
  28929. if (buffer)
  28930. buffer.references = numOfMeshes;
  28931. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28932. if (!this._extend) {
  28933. this.updateExtend(this._vertexBuffers[kind].getData());
  28934. }
  28935. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28936. mesh._createGlobalSubMesh(false);
  28937. //bounding info was just created again, world matrix should be applied again.
  28938. mesh._updateBoundingInfo();
  28939. }
  28940. }
  28941. // indexBuffer
  28942. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28943. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28944. }
  28945. if (this._indexBuffer) {
  28946. this._indexBuffer.references = numOfMeshes;
  28947. }
  28948. };
  28949. Geometry.prototype.notifyUpdate = function (kind) {
  28950. if (this.onGeometryUpdated) {
  28951. this.onGeometryUpdated(this, kind);
  28952. }
  28953. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28954. var mesh = _a[_i];
  28955. mesh._markSubMeshesAsAttributesDirty();
  28956. }
  28957. };
  28958. Geometry.prototype.load = function (scene, onLoaded) {
  28959. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28960. return;
  28961. }
  28962. if (this.isReady()) {
  28963. if (onLoaded) {
  28964. onLoaded();
  28965. }
  28966. return;
  28967. }
  28968. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28969. this._queueLoad(scene, onLoaded);
  28970. };
  28971. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28972. var _this = this;
  28973. scene._addPendingData(this);
  28974. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28975. _this._delayLoadingFunction(JSON.parse(data), _this);
  28976. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28977. _this._delayInfo = [];
  28978. scene._removePendingData(_this);
  28979. var meshes = _this._meshes;
  28980. var numOfMeshes = meshes.length;
  28981. for (var index = 0; index < numOfMeshes; index++) {
  28982. _this._applyToMesh(meshes[index]);
  28983. }
  28984. if (onLoaded) {
  28985. onLoaded();
  28986. }
  28987. }, function () { }, scene.database);
  28988. };
  28989. /**
  28990. * Invert the geometry to move from a right handed system to a left handed one.
  28991. */
  28992. Geometry.prototype.toLeftHanded = function () {
  28993. // Flip faces
  28994. var tIndices = this.getIndices(false);
  28995. if (tIndices != null && tIndices.length > 0) {
  28996. for (var i = 0; i < tIndices.length; i += 3) {
  28997. var tTemp = tIndices[i + 0];
  28998. tIndices[i + 0] = tIndices[i + 2];
  28999. tIndices[i + 2] = tTemp;
  29000. }
  29001. this.setIndices(tIndices);
  29002. }
  29003. // Negate position.z
  29004. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29005. if (tPositions != null && tPositions.length > 0) {
  29006. for (var i = 0; i < tPositions.length; i += 3) {
  29007. tPositions[i + 2] = -tPositions[i + 2];
  29008. }
  29009. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29010. }
  29011. // Negate normal.z
  29012. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29013. if (tNormals != null && tNormals.length > 0) {
  29014. for (var i = 0; i < tNormals.length; i += 3) {
  29015. tNormals[i + 2] = -tNormals[i + 2];
  29016. }
  29017. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29018. }
  29019. };
  29020. // Cache
  29021. Geometry.prototype._resetPointsArrayCache = function () {
  29022. this._positions = null;
  29023. };
  29024. Geometry.prototype._generatePointsArray = function () {
  29025. if (this._positions)
  29026. return true;
  29027. this._positions = [];
  29028. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29029. if (!data) {
  29030. return false;
  29031. }
  29032. for (var index = 0; index < data.length; index += 3) {
  29033. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29034. }
  29035. return true;
  29036. };
  29037. Geometry.prototype.isDisposed = function () {
  29038. return this._isDisposed;
  29039. };
  29040. Geometry.prototype._disposeVertexArrayObjects = function () {
  29041. if (this._vertexArrayObjects) {
  29042. for (var kind in this._vertexArrayObjects) {
  29043. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29044. }
  29045. this._vertexArrayObjects = {};
  29046. }
  29047. };
  29048. Geometry.prototype.dispose = function () {
  29049. var meshes = this._meshes;
  29050. var numOfMeshes = meshes.length;
  29051. var index;
  29052. for (index = 0; index < numOfMeshes; index++) {
  29053. this.releaseForMesh(meshes[index]);
  29054. }
  29055. this._meshes = [];
  29056. this._disposeVertexArrayObjects();
  29057. for (var kind in this._vertexBuffers) {
  29058. this._vertexBuffers[kind].dispose();
  29059. }
  29060. this._vertexBuffers = {};
  29061. this._totalVertices = 0;
  29062. if (this._indexBuffer) {
  29063. this._engine._releaseBuffer(this._indexBuffer);
  29064. }
  29065. this._indexBuffer = null;
  29066. this._indices = [];
  29067. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29068. this.delayLoadingFile = null;
  29069. this._delayLoadingFunction = null;
  29070. this._delayInfo = [];
  29071. this._boundingInfo = null;
  29072. this._scene.removeGeometry(this);
  29073. this._isDisposed = true;
  29074. };
  29075. Geometry.prototype.copy = function (id) {
  29076. var vertexData = new BABYLON.VertexData();
  29077. vertexData.indices = [];
  29078. var indices = this.getIndices();
  29079. for (var index = 0; index < indices.length; index++) {
  29080. vertexData.indices.push(indices[index]);
  29081. }
  29082. var updatable = false;
  29083. var stopChecking = false;
  29084. var kind;
  29085. for (kind in this._vertexBuffers) {
  29086. // using slice() to make a copy of the array and not just reference it
  29087. var data = this.getVerticesData(kind);
  29088. if (data instanceof Float32Array) {
  29089. vertexData.set(new Float32Array(data), kind);
  29090. }
  29091. else {
  29092. vertexData.set(data.slice(0), kind);
  29093. }
  29094. if (!stopChecking) {
  29095. updatable = this.getVertexBuffer(kind).isUpdatable();
  29096. stopChecking = !updatable;
  29097. }
  29098. }
  29099. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29100. geometry.delayLoadState = this.delayLoadState;
  29101. geometry.delayLoadingFile = this.delayLoadingFile;
  29102. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29103. for (kind in this._delayInfo) {
  29104. geometry._delayInfo = geometry._delayInfo || [];
  29105. geometry._delayInfo.push(kind);
  29106. }
  29107. // Bounding info
  29108. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29109. return geometry;
  29110. };
  29111. Geometry.prototype.serialize = function () {
  29112. var serializationObject = {};
  29113. serializationObject.id = this.id;
  29114. serializationObject.updatable = this._updatable;
  29115. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29116. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29117. }
  29118. return serializationObject;
  29119. };
  29120. Geometry.prototype.toNumberArray = function (origin) {
  29121. if (Array.isArray(origin)) {
  29122. return origin;
  29123. }
  29124. else {
  29125. return Array.prototype.slice.call(origin);
  29126. }
  29127. };
  29128. Geometry.prototype.serializeVerticeData = function () {
  29129. var serializationObject = this.serialize();
  29130. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29131. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29132. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29133. serializationObject.positions._updatable = true;
  29134. }
  29135. }
  29136. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29137. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29138. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29139. serializationObject.normals._updatable = true;
  29140. }
  29141. }
  29142. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29143. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29144. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29145. serializationObject.uvs._updatable = true;
  29146. }
  29147. }
  29148. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29149. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29150. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29151. serializationObject.uv2s._updatable = true;
  29152. }
  29153. }
  29154. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29155. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29156. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29157. serializationObject.uv3s._updatable = true;
  29158. }
  29159. }
  29160. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29161. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29162. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29163. serializationObject.uv4s._updatable = true;
  29164. }
  29165. }
  29166. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29167. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29168. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29169. serializationObject.uv5s._updatable = true;
  29170. }
  29171. }
  29172. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29173. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29174. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29175. serializationObject.uv6s._updatable = true;
  29176. }
  29177. }
  29178. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29179. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29180. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29181. serializationObject.colors._updatable = true;
  29182. }
  29183. }
  29184. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29185. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29186. serializationObject.matricesIndices._isExpanded = true;
  29187. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29188. serializationObject.matricesIndices._updatable = true;
  29189. }
  29190. }
  29191. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29192. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29193. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29194. serializationObject.matricesWeights._updatable = true;
  29195. }
  29196. }
  29197. serializationObject.indices = this.toNumberArray(this.getIndices());
  29198. return serializationObject;
  29199. };
  29200. // Statics
  29201. Geometry.ExtractFromMesh = function (mesh, id) {
  29202. var geometry = mesh._geometry;
  29203. if (!geometry) {
  29204. return null;
  29205. }
  29206. return geometry.copy(id);
  29207. };
  29208. /**
  29209. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29210. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29211. * Be aware Math.random() could cause collisions, but:
  29212. * "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"
  29213. */
  29214. Geometry.RandomId = function () {
  29215. return BABYLON.Tools.RandomId();
  29216. };
  29217. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29218. var scene = mesh.getScene();
  29219. // Geometry
  29220. var geometryId = parsedGeometry.geometryId;
  29221. if (geometryId) {
  29222. var geometry = scene.getGeometryByID(geometryId);
  29223. if (geometry) {
  29224. geometry.applyToMesh(mesh);
  29225. }
  29226. }
  29227. else if (parsedGeometry instanceof ArrayBuffer) {
  29228. var binaryInfo = mesh._binaryInfo;
  29229. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29230. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29231. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29232. }
  29233. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29234. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29235. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29236. }
  29237. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29238. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29239. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29240. }
  29241. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29242. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29243. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29244. }
  29245. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29246. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29247. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29248. }
  29249. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29250. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29251. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29252. }
  29253. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29254. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29255. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29256. }
  29257. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29258. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29259. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29260. }
  29261. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29262. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29263. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29264. }
  29265. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29266. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29267. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29268. }
  29269. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29270. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29271. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29272. }
  29273. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29274. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29275. mesh.setIndices(indicesData);
  29276. }
  29277. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29278. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29279. mesh.subMeshes = [];
  29280. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29281. var materialIndex = subMeshesData[(i * 5) + 0];
  29282. var verticesStart = subMeshesData[(i * 5) + 1];
  29283. var verticesCount = subMeshesData[(i * 5) + 2];
  29284. var indexStart = subMeshesData[(i * 5) + 3];
  29285. var indexCount = subMeshesData[(i * 5) + 4];
  29286. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29287. }
  29288. }
  29289. }
  29290. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29291. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29292. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29293. if (parsedGeometry.uvs) {
  29294. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29295. }
  29296. if (parsedGeometry.uvs2) {
  29297. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29298. }
  29299. if (parsedGeometry.uvs3) {
  29300. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29301. }
  29302. if (parsedGeometry.uvs4) {
  29303. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29304. }
  29305. if (parsedGeometry.uvs5) {
  29306. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29307. }
  29308. if (parsedGeometry.uvs6) {
  29309. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29310. }
  29311. if (parsedGeometry.colors) {
  29312. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29313. }
  29314. if (parsedGeometry.matricesIndices) {
  29315. if (!parsedGeometry.matricesIndices._isExpanded) {
  29316. var floatIndices = [];
  29317. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29318. var matricesIndex = parsedGeometry.matricesIndices[i];
  29319. floatIndices.push(matricesIndex & 0x000000FF);
  29320. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29321. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29322. floatIndices.push(matricesIndex >> 24);
  29323. }
  29324. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29325. }
  29326. else {
  29327. delete parsedGeometry.matricesIndices._isExpanded;
  29328. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29329. }
  29330. }
  29331. if (parsedGeometry.matricesIndicesExtra) {
  29332. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29333. var floatIndices = [];
  29334. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29335. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29336. floatIndices.push(matricesIndex & 0x000000FF);
  29337. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29338. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29339. floatIndices.push(matricesIndex >> 24);
  29340. }
  29341. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29342. }
  29343. else {
  29344. delete parsedGeometry.matricesIndices._isExpanded;
  29345. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29346. }
  29347. }
  29348. if (parsedGeometry.matricesWeights) {
  29349. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29350. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29351. }
  29352. if (parsedGeometry.matricesWeightsExtra) {
  29353. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29354. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29355. }
  29356. mesh.setIndices(parsedGeometry.indices);
  29357. }
  29358. // SubMeshes
  29359. if (parsedGeometry.subMeshes) {
  29360. mesh.subMeshes = [];
  29361. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29362. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29363. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29364. }
  29365. }
  29366. // Flat shading
  29367. if (mesh._shouldGenerateFlatShading) {
  29368. mesh.convertToFlatShadedMesh();
  29369. delete mesh._shouldGenerateFlatShading;
  29370. }
  29371. // Update
  29372. mesh.computeWorldMatrix(true);
  29373. // Octree
  29374. if (scene['_selectionOctree']) {
  29375. scene['_selectionOctree'].addMesh(mesh);
  29376. }
  29377. };
  29378. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29379. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29380. return;
  29381. }
  29382. var size = matricesWeights.length;
  29383. for (var i = 0; i < size; i += influencers) {
  29384. var weight = 0;
  29385. var biggerIndex = i;
  29386. var biggerWeight = 0;
  29387. for (var j = 0; j < influencers - 1; j++) {
  29388. weight += matricesWeights[i + j];
  29389. if (matricesWeights[i + j] > biggerWeight) {
  29390. biggerWeight = matricesWeights[i + j];
  29391. biggerIndex = i + j;
  29392. }
  29393. }
  29394. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29395. }
  29396. };
  29397. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29398. if (scene.getGeometryByID(parsedVertexData.id)) {
  29399. return null; // null since geometry could be something else than a box...
  29400. }
  29401. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29402. if (BABYLON.Tags) {
  29403. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29404. }
  29405. if (parsedVertexData.delayLoadingFile) {
  29406. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29407. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29408. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29409. geometry._delayInfo = [];
  29410. if (parsedVertexData.hasUVs) {
  29411. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29412. }
  29413. if (parsedVertexData.hasUVs2) {
  29414. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29415. }
  29416. if (parsedVertexData.hasUVs3) {
  29417. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29418. }
  29419. if (parsedVertexData.hasUVs4) {
  29420. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29421. }
  29422. if (parsedVertexData.hasUVs5) {
  29423. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29424. }
  29425. if (parsedVertexData.hasUVs6) {
  29426. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29427. }
  29428. if (parsedVertexData.hasColors) {
  29429. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29430. }
  29431. if (parsedVertexData.hasMatricesIndices) {
  29432. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29433. }
  29434. if (parsedVertexData.hasMatricesWeights) {
  29435. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29436. }
  29437. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29438. }
  29439. else {
  29440. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29441. }
  29442. scene.pushGeometry(geometry, true);
  29443. return geometry;
  29444. };
  29445. return Geometry;
  29446. }());
  29447. BABYLON.Geometry = Geometry;
  29448. /////// Primitives //////////////////////////////////////////////
  29449. (function (Geometry) {
  29450. var Primitives;
  29451. (function (Primitives) {
  29452. /// Abstract class
  29453. var _Primitive = (function (_super) {
  29454. __extends(_Primitive, _super);
  29455. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29456. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29457. _this._canBeRegenerated = _canBeRegenerated;
  29458. _this._beingRegenerated = true;
  29459. _this.regenerate();
  29460. _this._beingRegenerated = false;
  29461. return _this;
  29462. }
  29463. _Primitive.prototype.canBeRegenerated = function () {
  29464. return this._canBeRegenerated;
  29465. };
  29466. _Primitive.prototype.regenerate = function () {
  29467. if (!this._canBeRegenerated) {
  29468. return;
  29469. }
  29470. this._beingRegenerated = true;
  29471. this.setAllVerticesData(this._regenerateVertexData(), false);
  29472. this._beingRegenerated = false;
  29473. };
  29474. _Primitive.prototype.asNewGeometry = function (id) {
  29475. return _super.prototype.copy.call(this, id);
  29476. };
  29477. // overrides
  29478. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29479. if (!this._beingRegenerated) {
  29480. return;
  29481. }
  29482. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29483. };
  29484. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29485. if (!this._beingRegenerated) {
  29486. return;
  29487. }
  29488. _super.prototype.setVerticesData.call(this, kind, data, false);
  29489. };
  29490. // to override
  29491. // protected
  29492. _Primitive.prototype._regenerateVertexData = function () {
  29493. throw new Error("Abstract method");
  29494. };
  29495. _Primitive.prototype.copy = function (id) {
  29496. throw new Error("Must be overriden in sub-classes.");
  29497. };
  29498. _Primitive.prototype.serialize = function () {
  29499. var serializationObject = _super.prototype.serialize.call(this);
  29500. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29501. return serializationObject;
  29502. };
  29503. return _Primitive;
  29504. }(Geometry));
  29505. Primitives._Primitive = _Primitive;
  29506. var Ribbon = (function (_super) {
  29507. __extends(Ribbon, _super);
  29508. // Members
  29509. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29510. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29511. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29512. _this.pathArray = pathArray;
  29513. _this.closeArray = closeArray;
  29514. _this.closePath = closePath;
  29515. _this.offset = offset;
  29516. _this.side = side;
  29517. return _this;
  29518. }
  29519. Ribbon.prototype._regenerateVertexData = function () {
  29520. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29521. };
  29522. Ribbon.prototype.copy = function (id) {
  29523. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29524. };
  29525. return Ribbon;
  29526. }(_Primitive));
  29527. Primitives.Ribbon = Ribbon;
  29528. var Box = (function (_super) {
  29529. __extends(Box, _super);
  29530. // Members
  29531. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29532. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29533. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29534. _this.size = size;
  29535. _this.side = side;
  29536. return _this;
  29537. }
  29538. Box.prototype._regenerateVertexData = function () {
  29539. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29540. };
  29541. Box.prototype.copy = function (id) {
  29542. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29543. };
  29544. Box.prototype.serialize = function () {
  29545. var serializationObject = _super.prototype.serialize.call(this);
  29546. serializationObject.size = this.size;
  29547. return serializationObject;
  29548. };
  29549. Box.Parse = function (parsedBox, scene) {
  29550. if (scene.getGeometryByID(parsedBox.id)) {
  29551. return null; // null since geometry could be something else than a box...
  29552. }
  29553. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29554. if (BABYLON.Tags) {
  29555. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29556. }
  29557. scene.pushGeometry(box, true);
  29558. return box;
  29559. };
  29560. return Box;
  29561. }(_Primitive));
  29562. Primitives.Box = Box;
  29563. var Sphere = (function (_super) {
  29564. __extends(Sphere, _super);
  29565. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29566. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29567. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29568. _this.segments = segments;
  29569. _this.diameter = diameter;
  29570. _this.side = side;
  29571. return _this;
  29572. }
  29573. Sphere.prototype._regenerateVertexData = function () {
  29574. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29575. };
  29576. Sphere.prototype.copy = function (id) {
  29577. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29578. };
  29579. Sphere.prototype.serialize = function () {
  29580. var serializationObject = _super.prototype.serialize.call(this);
  29581. serializationObject.segments = this.segments;
  29582. serializationObject.diameter = this.diameter;
  29583. return serializationObject;
  29584. };
  29585. Sphere.Parse = function (parsedSphere, scene) {
  29586. if (scene.getGeometryByID(parsedSphere.id)) {
  29587. return null; // null since geometry could be something else than a sphere...
  29588. }
  29589. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29590. if (BABYLON.Tags) {
  29591. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29592. }
  29593. scene.pushGeometry(sphere, true);
  29594. return sphere;
  29595. };
  29596. return Sphere;
  29597. }(_Primitive));
  29598. Primitives.Sphere = Sphere;
  29599. var Disc = (function (_super) {
  29600. __extends(Disc, _super);
  29601. // Members
  29602. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29603. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29604. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29605. _this.radius = radius;
  29606. _this.tessellation = tessellation;
  29607. _this.side = side;
  29608. return _this;
  29609. }
  29610. Disc.prototype._regenerateVertexData = function () {
  29611. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29612. };
  29613. Disc.prototype.copy = function (id) {
  29614. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29615. };
  29616. return Disc;
  29617. }(_Primitive));
  29618. Primitives.Disc = Disc;
  29619. var Cylinder = (function (_super) {
  29620. __extends(Cylinder, _super);
  29621. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29622. if (subdivisions === void 0) { subdivisions = 1; }
  29623. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29624. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29625. _this.height = height;
  29626. _this.diameterTop = diameterTop;
  29627. _this.diameterBottom = diameterBottom;
  29628. _this.tessellation = tessellation;
  29629. _this.subdivisions = subdivisions;
  29630. _this.side = side;
  29631. return _this;
  29632. }
  29633. Cylinder.prototype._regenerateVertexData = function () {
  29634. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29635. };
  29636. Cylinder.prototype.copy = function (id) {
  29637. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29638. };
  29639. Cylinder.prototype.serialize = function () {
  29640. var serializationObject = _super.prototype.serialize.call(this);
  29641. serializationObject.height = this.height;
  29642. serializationObject.diameterTop = this.diameterTop;
  29643. serializationObject.diameterBottom = this.diameterBottom;
  29644. serializationObject.tessellation = this.tessellation;
  29645. return serializationObject;
  29646. };
  29647. Cylinder.Parse = function (parsedCylinder, scene) {
  29648. if (scene.getGeometryByID(parsedCylinder.id)) {
  29649. return null; // null since geometry could be something else than a cylinder...
  29650. }
  29651. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29652. if (BABYLON.Tags) {
  29653. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29654. }
  29655. scene.pushGeometry(cylinder, true);
  29656. return cylinder;
  29657. };
  29658. return Cylinder;
  29659. }(_Primitive));
  29660. Primitives.Cylinder = Cylinder;
  29661. var Torus = (function (_super) {
  29662. __extends(Torus, _super);
  29663. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29664. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29665. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29666. _this.diameter = diameter;
  29667. _this.thickness = thickness;
  29668. _this.tessellation = tessellation;
  29669. _this.side = side;
  29670. return _this;
  29671. }
  29672. Torus.prototype._regenerateVertexData = function () {
  29673. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29674. };
  29675. Torus.prototype.copy = function (id) {
  29676. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29677. };
  29678. Torus.prototype.serialize = function () {
  29679. var serializationObject = _super.prototype.serialize.call(this);
  29680. serializationObject.diameter = this.diameter;
  29681. serializationObject.thickness = this.thickness;
  29682. serializationObject.tessellation = this.tessellation;
  29683. return serializationObject;
  29684. };
  29685. Torus.Parse = function (parsedTorus, scene) {
  29686. if (scene.getGeometryByID(parsedTorus.id)) {
  29687. return null; // null since geometry could be something else than a torus...
  29688. }
  29689. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29690. if (BABYLON.Tags) {
  29691. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29692. }
  29693. scene.pushGeometry(torus, true);
  29694. return torus;
  29695. };
  29696. return Torus;
  29697. }(_Primitive));
  29698. Primitives.Torus = Torus;
  29699. var Ground = (function (_super) {
  29700. __extends(Ground, _super);
  29701. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29702. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29703. _this.width = width;
  29704. _this.height = height;
  29705. _this.subdivisions = subdivisions;
  29706. return _this;
  29707. }
  29708. Ground.prototype._regenerateVertexData = function () {
  29709. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29710. };
  29711. Ground.prototype.copy = function (id) {
  29712. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29713. };
  29714. Ground.prototype.serialize = function () {
  29715. var serializationObject = _super.prototype.serialize.call(this);
  29716. serializationObject.width = this.width;
  29717. serializationObject.height = this.height;
  29718. serializationObject.subdivisions = this.subdivisions;
  29719. return serializationObject;
  29720. };
  29721. Ground.Parse = function (parsedGround, scene) {
  29722. if (scene.getGeometryByID(parsedGround.id)) {
  29723. return null; // null since geometry could be something else than a ground...
  29724. }
  29725. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29726. if (BABYLON.Tags) {
  29727. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29728. }
  29729. scene.pushGeometry(ground, true);
  29730. return ground;
  29731. };
  29732. return Ground;
  29733. }(_Primitive));
  29734. Primitives.Ground = Ground;
  29735. var TiledGround = (function (_super) {
  29736. __extends(TiledGround, _super);
  29737. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29738. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29739. _this.xmin = xmin;
  29740. _this.zmin = zmin;
  29741. _this.xmax = xmax;
  29742. _this.zmax = zmax;
  29743. _this.subdivisions = subdivisions;
  29744. _this.precision = precision;
  29745. return _this;
  29746. }
  29747. TiledGround.prototype._regenerateVertexData = function () {
  29748. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29749. };
  29750. TiledGround.prototype.copy = function (id) {
  29751. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29752. };
  29753. return TiledGround;
  29754. }(_Primitive));
  29755. Primitives.TiledGround = TiledGround;
  29756. var Plane = (function (_super) {
  29757. __extends(Plane, _super);
  29758. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29759. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29760. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29761. _this.size = size;
  29762. _this.side = side;
  29763. return _this;
  29764. }
  29765. Plane.prototype._regenerateVertexData = function () {
  29766. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29767. };
  29768. Plane.prototype.copy = function (id) {
  29769. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29770. };
  29771. Plane.prototype.serialize = function () {
  29772. var serializationObject = _super.prototype.serialize.call(this);
  29773. serializationObject.size = this.size;
  29774. return serializationObject;
  29775. };
  29776. Plane.Parse = function (parsedPlane, scene) {
  29777. if (scene.getGeometryByID(parsedPlane.id)) {
  29778. return null; // null since geometry could be something else than a ground...
  29779. }
  29780. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29781. if (BABYLON.Tags) {
  29782. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29783. }
  29784. scene.pushGeometry(plane, true);
  29785. return plane;
  29786. };
  29787. return Plane;
  29788. }(_Primitive));
  29789. Primitives.Plane = Plane;
  29790. var TorusKnot = (function (_super) {
  29791. __extends(TorusKnot, _super);
  29792. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29793. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29794. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29795. _this.radius = radius;
  29796. _this.tube = tube;
  29797. _this.radialSegments = radialSegments;
  29798. _this.tubularSegments = tubularSegments;
  29799. _this.p = p;
  29800. _this.q = q;
  29801. _this.side = side;
  29802. return _this;
  29803. }
  29804. TorusKnot.prototype._regenerateVertexData = function () {
  29805. 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 });
  29806. };
  29807. TorusKnot.prototype.copy = function (id) {
  29808. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29809. };
  29810. TorusKnot.prototype.serialize = function () {
  29811. var serializationObject = _super.prototype.serialize.call(this);
  29812. serializationObject.radius = this.radius;
  29813. serializationObject.tube = this.tube;
  29814. serializationObject.radialSegments = this.radialSegments;
  29815. serializationObject.tubularSegments = this.tubularSegments;
  29816. serializationObject.p = this.p;
  29817. serializationObject.q = this.q;
  29818. return serializationObject;
  29819. };
  29820. ;
  29821. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29822. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29823. return null; // null since geometry could be something else than a ground...
  29824. }
  29825. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29826. if (BABYLON.Tags) {
  29827. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29828. }
  29829. scene.pushGeometry(torusKnot, true);
  29830. return torusKnot;
  29831. };
  29832. return TorusKnot;
  29833. }(_Primitive));
  29834. Primitives.TorusKnot = TorusKnot;
  29835. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29836. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29837. })(BABYLON || (BABYLON = {}));
  29838. //# sourceMappingURL=babylon.geometry.js.map
  29839. var BABYLON;
  29840. (function (BABYLON) {
  29841. var PostProcessManager = (function () {
  29842. function PostProcessManager(scene) {
  29843. this._vertexBuffers = {};
  29844. this._scene = scene;
  29845. }
  29846. PostProcessManager.prototype._prepareBuffers = function () {
  29847. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29848. return;
  29849. }
  29850. // VBO
  29851. var vertices = [];
  29852. vertices.push(1, 1);
  29853. vertices.push(-1, 1);
  29854. vertices.push(-1, -1);
  29855. vertices.push(1, -1);
  29856. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29857. this._buildIndexBuffer();
  29858. };
  29859. PostProcessManager.prototype._buildIndexBuffer = function () {
  29860. // Indices
  29861. var indices = [];
  29862. indices.push(0);
  29863. indices.push(1);
  29864. indices.push(2);
  29865. indices.push(0);
  29866. indices.push(2);
  29867. indices.push(3);
  29868. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29869. };
  29870. PostProcessManager.prototype._rebuild = function () {
  29871. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29872. return;
  29873. }
  29874. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  29875. this._buildIndexBuffer();
  29876. };
  29877. // Methods
  29878. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29879. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29880. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29881. return false;
  29882. }
  29883. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29884. return true;
  29885. };
  29886. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  29887. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  29888. var engine = this._scene.getEngine();
  29889. for (var index = 0; index < postProcesses.length; index++) {
  29890. if (index < postProcesses.length - 1) {
  29891. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29892. }
  29893. else {
  29894. if (targetTexture) {
  29895. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  29896. }
  29897. else {
  29898. engine.restoreDefaultFramebuffer();
  29899. }
  29900. }
  29901. var pp = postProcesses[index];
  29902. var effect = pp.apply();
  29903. if (effect) {
  29904. pp.onBeforeRenderObservable.notifyObservers(effect);
  29905. // VBOs
  29906. this._prepareBuffers();
  29907. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29908. // Draw order
  29909. engine.draw(true, 0, 6);
  29910. pp.onAfterRenderObservable.notifyObservers(effect);
  29911. }
  29912. }
  29913. // Restore depth buffer
  29914. engine.setDepthBuffer(true);
  29915. engine.setDepthWrite(true);
  29916. };
  29917. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29918. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29919. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29920. return;
  29921. }
  29922. var engine = this._scene.getEngine();
  29923. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29924. if (index < len - 1) {
  29925. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29926. }
  29927. else {
  29928. if (targetTexture) {
  29929. engine.bindFramebuffer(targetTexture, faceIndex);
  29930. }
  29931. else {
  29932. engine.restoreDefaultFramebuffer();
  29933. }
  29934. }
  29935. if (doNotPresent) {
  29936. break;
  29937. }
  29938. var pp = postProcesses[index];
  29939. var effect = pp.apply();
  29940. if (effect) {
  29941. pp.onBeforeRenderObservable.notifyObservers(effect);
  29942. // VBOs
  29943. this._prepareBuffers();
  29944. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29945. // Draw order
  29946. engine.draw(true, 0, 6);
  29947. pp.onAfterRenderObservable.notifyObservers(effect);
  29948. }
  29949. }
  29950. // Restore states
  29951. engine.setDepthBuffer(true);
  29952. engine.setDepthWrite(true);
  29953. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29954. };
  29955. PostProcessManager.prototype.dispose = function () {
  29956. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29957. if (buffer) {
  29958. buffer.dispose();
  29959. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29960. }
  29961. if (this._indexBuffer) {
  29962. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29963. this._indexBuffer = null;
  29964. }
  29965. };
  29966. return PostProcessManager;
  29967. }());
  29968. BABYLON.PostProcessManager = PostProcessManager;
  29969. })(BABYLON || (BABYLON = {}));
  29970. //# sourceMappingURL=babylon.postProcessManager.js.map
  29971. var BABYLON;
  29972. (function (BABYLON) {
  29973. /**
  29974. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29975. */
  29976. var PerformanceMonitor = (function () {
  29977. /**
  29978. * constructor
  29979. * @param frameSampleSize The number of samples required to saturate the sliding window
  29980. */
  29981. function PerformanceMonitor(frameSampleSize) {
  29982. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29983. this._enabled = true;
  29984. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29985. }
  29986. /**
  29987. * Samples current frame
  29988. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29989. */
  29990. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29991. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29992. if (!this._enabled)
  29993. return;
  29994. if (this._lastFrameTimeMs != null) {
  29995. var dt = timeMs - this._lastFrameTimeMs;
  29996. this._rollingFrameTime.add(dt);
  29997. }
  29998. this._lastFrameTimeMs = timeMs;
  29999. };
  30000. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30001. /**
  30002. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30003. * @return Average frame time in milliseconds
  30004. */
  30005. get: function () {
  30006. return this._rollingFrameTime.average;
  30007. },
  30008. enumerable: true,
  30009. configurable: true
  30010. });
  30011. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30012. /**
  30013. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30014. * @return Frame time variance in milliseconds squared
  30015. */
  30016. get: function () {
  30017. return this._rollingFrameTime.variance;
  30018. },
  30019. enumerable: true,
  30020. configurable: true
  30021. });
  30022. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30023. /**
  30024. * Returns the frame time of the most recent frame
  30025. * @return Frame time in milliseconds
  30026. */
  30027. get: function () {
  30028. return this._rollingFrameTime.history(0);
  30029. },
  30030. enumerable: true,
  30031. configurable: true
  30032. });
  30033. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30034. /**
  30035. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30036. * @return Framerate in frames per second
  30037. */
  30038. get: function () {
  30039. return 1000.0 / this._rollingFrameTime.average;
  30040. },
  30041. enumerable: true,
  30042. configurable: true
  30043. });
  30044. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30045. /**
  30046. * Returns the average framerate in frames per second using the most recent frame time
  30047. * @return Framerate in frames per second
  30048. */
  30049. get: function () {
  30050. return 1000.0 / this._rollingFrameTime.history(0);
  30051. },
  30052. enumerable: true,
  30053. configurable: true
  30054. });
  30055. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30056. /**
  30057. * Returns true if enough samples have been taken to completely fill the sliding window
  30058. * @return true if saturated
  30059. */
  30060. get: function () {
  30061. return this._rollingFrameTime.isSaturated();
  30062. },
  30063. enumerable: true,
  30064. configurable: true
  30065. });
  30066. /**
  30067. * Enables contributions to the sliding window sample set
  30068. */
  30069. PerformanceMonitor.prototype.enable = function () {
  30070. this._enabled = true;
  30071. };
  30072. /**
  30073. * Disables contributions to the sliding window sample set
  30074. * Samples will not be interpolated over the disabled period
  30075. */
  30076. PerformanceMonitor.prototype.disable = function () {
  30077. this._enabled = false;
  30078. //clear last sample to avoid interpolating over the disabled period when next enabled
  30079. this._lastFrameTimeMs = null;
  30080. this._lastChangeTimeMs = null;
  30081. };
  30082. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30083. /**
  30084. * Returns true if sampling is enabled
  30085. * @return true if enabled
  30086. */
  30087. get: function () {
  30088. return this._enabled;
  30089. },
  30090. enumerable: true,
  30091. configurable: true
  30092. });
  30093. /**
  30094. * Resets performance monitor
  30095. */
  30096. PerformanceMonitor.prototype.reset = function () {
  30097. //clear last sample to avoid interpolating over the disabled period when next enabled
  30098. this._lastFrameTimeMs = null;
  30099. this._lastChangeTimeMs = null;
  30100. //wipe record
  30101. this._rollingFrameTime.reset();
  30102. };
  30103. return PerformanceMonitor;
  30104. }());
  30105. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30106. /**
  30107. * RollingAverage
  30108. *
  30109. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30110. */
  30111. var RollingAverage = (function () {
  30112. /**
  30113. * constructor
  30114. * @param length The number of samples required to saturate the sliding window
  30115. */
  30116. function RollingAverage(length) {
  30117. this._samples = new Array(length);
  30118. this.reset();
  30119. }
  30120. /**
  30121. * Adds a sample to the sample set
  30122. * @param v The sample value
  30123. */
  30124. RollingAverage.prototype.add = function (v) {
  30125. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30126. var delta;
  30127. //we need to check if we've already wrapped round
  30128. if (this.isSaturated()) {
  30129. //remove bottom of stack from mean
  30130. var bottomValue = this._samples[this._pos];
  30131. delta = bottomValue - this.average;
  30132. this.average -= delta / (this._sampleCount - 1);
  30133. this._m2 -= delta * (bottomValue - this.average);
  30134. }
  30135. else {
  30136. this._sampleCount++;
  30137. }
  30138. //add new value to mean
  30139. delta = v - this.average;
  30140. this.average += delta / (this._sampleCount);
  30141. this._m2 += delta * (v - this.average);
  30142. //set the new variance
  30143. this.variance = this._m2 / (this._sampleCount - 1);
  30144. this._samples[this._pos] = v;
  30145. this._pos++;
  30146. this._pos %= this._samples.length; //positive wrap around
  30147. };
  30148. /**
  30149. * Returns previously added values or null if outside of history or outside the sliding window domain
  30150. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30151. * @return Value previously recorded with add() or null if outside of range
  30152. */
  30153. RollingAverage.prototype.history = function (i) {
  30154. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30155. return null;
  30156. }
  30157. var i0 = this._wrapPosition(this._pos - 1.0);
  30158. return this._samples[this._wrapPosition(i0 - i)];
  30159. };
  30160. /**
  30161. * Returns true if enough samples have been taken to completely fill the sliding window
  30162. * @return true if sample-set saturated
  30163. */
  30164. RollingAverage.prototype.isSaturated = function () {
  30165. return this._sampleCount >= this._samples.length;
  30166. };
  30167. /**
  30168. * Resets the rolling average (equivalent to 0 samples taken so far)
  30169. */
  30170. RollingAverage.prototype.reset = function () {
  30171. this.average = 0;
  30172. this.variance = 0;
  30173. this._sampleCount = 0;
  30174. this._pos = 0;
  30175. this._m2 = 0;
  30176. };
  30177. /**
  30178. * Wraps a value around the sample range boundaries
  30179. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30180. * @return Wrapped position in sample range
  30181. */
  30182. RollingAverage.prototype._wrapPosition = function (i) {
  30183. var max = this._samples.length;
  30184. return ((i % max) + max) % max;
  30185. };
  30186. return RollingAverage;
  30187. }());
  30188. BABYLON.RollingAverage = RollingAverage;
  30189. })(BABYLON || (BABYLON = {}));
  30190. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30191. var BABYLON;
  30192. (function (BABYLON) {
  30193. var AnimationRange = (function () {
  30194. function AnimationRange(name, from, to) {
  30195. this.name = name;
  30196. this.from = from;
  30197. this.to = to;
  30198. }
  30199. AnimationRange.prototype.clone = function () {
  30200. return new AnimationRange(this.name, this.from, this.to);
  30201. };
  30202. return AnimationRange;
  30203. }());
  30204. BABYLON.AnimationRange = AnimationRange;
  30205. /**
  30206. * Composed of a frame, and an action function
  30207. */
  30208. var AnimationEvent = (function () {
  30209. function AnimationEvent(frame, action, onlyOnce) {
  30210. this.frame = frame;
  30211. this.action = action;
  30212. this.onlyOnce = onlyOnce;
  30213. this.isDone = false;
  30214. }
  30215. return AnimationEvent;
  30216. }());
  30217. BABYLON.AnimationEvent = AnimationEvent;
  30218. var PathCursor = (function () {
  30219. function PathCursor(path) {
  30220. this.path = path;
  30221. this._onchange = new Array();
  30222. this.value = 0;
  30223. this.animations = new Array();
  30224. }
  30225. PathCursor.prototype.getPoint = function () {
  30226. var point = this.path.getPointAtLengthPosition(this.value);
  30227. return new BABYLON.Vector3(point.x, 0, point.y);
  30228. };
  30229. PathCursor.prototype.moveAhead = function (step) {
  30230. if (step === void 0) { step = 0.002; }
  30231. this.move(step);
  30232. return this;
  30233. };
  30234. PathCursor.prototype.moveBack = function (step) {
  30235. if (step === void 0) { step = 0.002; }
  30236. this.move(-step);
  30237. return this;
  30238. };
  30239. PathCursor.prototype.move = function (step) {
  30240. if (Math.abs(step) > 1) {
  30241. throw "step size should be less than 1.";
  30242. }
  30243. this.value += step;
  30244. this.ensureLimits();
  30245. this.raiseOnChange();
  30246. return this;
  30247. };
  30248. PathCursor.prototype.ensureLimits = function () {
  30249. while (this.value > 1) {
  30250. this.value -= 1;
  30251. }
  30252. while (this.value < 0) {
  30253. this.value += 1;
  30254. }
  30255. return this;
  30256. };
  30257. // used by animation engine
  30258. PathCursor.prototype.markAsDirty = function (propertyName) {
  30259. this.ensureLimits();
  30260. this.raiseOnChange();
  30261. return this;
  30262. };
  30263. PathCursor.prototype.raiseOnChange = function () {
  30264. var _this = this;
  30265. this._onchange.forEach(function (f) { return f(_this); });
  30266. return this;
  30267. };
  30268. PathCursor.prototype.onchange = function (f) {
  30269. this._onchange.push(f);
  30270. return this;
  30271. };
  30272. return PathCursor;
  30273. }());
  30274. BABYLON.PathCursor = PathCursor;
  30275. var Animation = (function () {
  30276. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  30277. this.name = name;
  30278. this.targetProperty = targetProperty;
  30279. this.framePerSecond = framePerSecond;
  30280. this.dataType = dataType;
  30281. this.loopMode = loopMode;
  30282. this.enableBlending = enableBlending;
  30283. this._offsetsCache = {};
  30284. this._highLimitsCache = {};
  30285. this._stopped = false;
  30286. this._blendingFactor = 0;
  30287. // The set of event that will be linked to this animation
  30288. this._events = new Array();
  30289. this.allowMatricesInterpolation = false;
  30290. this.blendingSpeed = 0.01;
  30291. this._ranges = {};
  30292. this.targetPropertyPath = targetProperty.split(".");
  30293. this.dataType = dataType;
  30294. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  30295. }
  30296. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  30297. var dataType = undefined;
  30298. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  30299. dataType = Animation.ANIMATIONTYPE_FLOAT;
  30300. }
  30301. else if (from instanceof BABYLON.Quaternion) {
  30302. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  30303. }
  30304. else if (from instanceof BABYLON.Vector3) {
  30305. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  30306. }
  30307. else if (from instanceof BABYLON.Vector2) {
  30308. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  30309. }
  30310. else if (from instanceof BABYLON.Color3) {
  30311. dataType = Animation.ANIMATIONTYPE_COLOR3;
  30312. }
  30313. else if (from instanceof BABYLON.Size) {
  30314. dataType = Animation.ANIMATIONTYPE_SIZE;
  30315. }
  30316. if (dataType == undefined) {
  30317. return null;
  30318. }
  30319. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  30320. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  30321. animation.setKeys(keys);
  30322. if (easingFunction !== undefined) {
  30323. animation.setEasingFunction(easingFunction);
  30324. }
  30325. return animation;
  30326. };
  30327. /**
  30328. * Sets up an animation.
  30329. * @param property the property to animate
  30330. * @param animationType the animation type to apply
  30331. * @param easingFunction the easing function used in the animation
  30332. * @returns The created animation
  30333. */
  30334. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  30335. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30336. animation.setEasingFunction(easingFunction);
  30337. return animation;
  30338. };
  30339. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30340. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30341. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30342. };
  30343. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30344. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30345. node.animations.push(animation);
  30346. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30347. };
  30348. /**
  30349. * Transition property of the Camera to the target Value.
  30350. * @param property The property to transition
  30351. * @param targetValue The target Value of the property
  30352. * @param host The object where the property to animate belongs
  30353. * @param scene Scene used to run the animation
  30354. * @param frameRate Framerate (in frame/s) to use
  30355. * @param transition The transition type we want to use
  30356. * @param duration The duration of the animation, in milliseconds
  30357. * @param onAnimationEnd Call back trigger at the end of the animation.
  30358. */
  30359. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  30360. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  30361. if (duration <= 0) {
  30362. host[property] = targetValue;
  30363. if (onAnimationEnd) {
  30364. onAnimationEnd();
  30365. }
  30366. return;
  30367. }
  30368. var endFrame = frameRate * (duration / 1000);
  30369. transition.setKeys([{
  30370. frame: 0,
  30371. value: host[property].clone ? host[property].clone() : host[property]
  30372. },
  30373. {
  30374. frame: endFrame,
  30375. value: targetValue
  30376. }]);
  30377. if (!host.animations) {
  30378. host.animations = [];
  30379. }
  30380. host.animations.push(transition);
  30381. var animation = scene.beginAnimation(host, 0, endFrame, false);
  30382. animation.onAnimationEnd = onAnimationEnd;
  30383. return animation;
  30384. };
  30385. // Methods
  30386. /**
  30387. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30388. */
  30389. Animation.prototype.toString = function (fullDetails) {
  30390. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  30391. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  30392. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  30393. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30394. if (fullDetails) {
  30395. ret += ", Ranges: {";
  30396. var first = true;
  30397. for (var name in this._ranges) {
  30398. if (first) {
  30399. ret += ", ";
  30400. first = false;
  30401. }
  30402. ret += name;
  30403. }
  30404. ret += "}";
  30405. }
  30406. return ret;
  30407. };
  30408. /**
  30409. * Add an event to this animation.
  30410. */
  30411. Animation.prototype.addEvent = function (event) {
  30412. this._events.push(event);
  30413. };
  30414. /**
  30415. * Remove all events found at the given frame
  30416. * @param frame
  30417. */
  30418. Animation.prototype.removeEvents = function (frame) {
  30419. for (var index = 0; index < this._events.length; index++) {
  30420. if (this._events[index].frame === frame) {
  30421. this._events.splice(index, 1);
  30422. index--;
  30423. }
  30424. }
  30425. };
  30426. Animation.prototype.createRange = function (name, from, to) {
  30427. // check name not already in use; could happen for bones after serialized
  30428. if (!this._ranges[name]) {
  30429. this._ranges[name] = new AnimationRange(name, from, to);
  30430. }
  30431. };
  30432. Animation.prototype.deleteRange = function (name, deleteFrames) {
  30433. if (deleteFrames === void 0) { deleteFrames = true; }
  30434. if (this._ranges[name]) {
  30435. if (deleteFrames) {
  30436. var from = this._ranges[name].from;
  30437. var to = this._ranges[name].to;
  30438. // this loop MUST go high to low for multiple splices to work
  30439. for (var key = this._keys.length - 1; key >= 0; key--) {
  30440. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  30441. this._keys.splice(key, 1);
  30442. }
  30443. }
  30444. }
  30445. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30446. }
  30447. };
  30448. Animation.prototype.getRange = function (name) {
  30449. return this._ranges[name];
  30450. };
  30451. Animation.prototype.reset = function () {
  30452. this._offsetsCache = {};
  30453. this._highLimitsCache = {};
  30454. this.currentFrame = 0;
  30455. this._blendingFactor = 0;
  30456. this._originalBlendValue = null;
  30457. };
  30458. Animation.prototype.isStopped = function () {
  30459. return this._stopped;
  30460. };
  30461. Animation.prototype.getKeys = function () {
  30462. return this._keys;
  30463. };
  30464. Animation.prototype.getHighestFrame = function () {
  30465. var ret = 0;
  30466. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  30467. if (ret < this._keys[key].frame) {
  30468. ret = this._keys[key].frame;
  30469. }
  30470. }
  30471. return ret;
  30472. };
  30473. Animation.prototype.getEasingFunction = function () {
  30474. return this._easingFunction;
  30475. };
  30476. Animation.prototype.setEasingFunction = function (easingFunction) {
  30477. this._easingFunction = easingFunction;
  30478. };
  30479. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  30480. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  30481. };
  30482. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30483. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30484. };
  30485. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  30486. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  30487. };
  30488. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30489. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  30490. };
  30491. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  30492. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  30493. };
  30494. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30495. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30496. };
  30497. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  30498. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  30499. };
  30500. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30501. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30502. };
  30503. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  30504. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  30505. };
  30506. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  30507. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  30508. };
  30509. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30510. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30511. };
  30512. Animation.prototype.clone = function () {
  30513. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30514. clone.enableBlending = this.enableBlending;
  30515. clone.blendingSpeed = this.blendingSpeed;
  30516. if (this._keys) {
  30517. clone.setKeys(this._keys);
  30518. }
  30519. if (this._ranges) {
  30520. clone._ranges = {};
  30521. for (var name in this._ranges) {
  30522. clone._ranges[name] = this._ranges[name].clone();
  30523. }
  30524. }
  30525. return clone;
  30526. };
  30527. Animation.prototype.setKeys = function (values) {
  30528. this._keys = values.slice(0);
  30529. this._offsetsCache = {};
  30530. this._highLimitsCache = {};
  30531. };
  30532. Animation.prototype._getKeyValue = function (value) {
  30533. if (typeof value === "function") {
  30534. return value();
  30535. }
  30536. return value;
  30537. };
  30538. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30539. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30540. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30541. }
  30542. this.currentFrame = currentFrame;
  30543. // Try to get a hash to find the right key
  30544. 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));
  30545. if (this._keys[startKeyIndex].frame >= currentFrame) {
  30546. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  30547. startKeyIndex--;
  30548. }
  30549. }
  30550. for (var key = startKeyIndex; key < this._keys.length; key++) {
  30551. var endKey = this._keys[key + 1];
  30552. if (endKey.frame >= currentFrame) {
  30553. var startKey = this._keys[key];
  30554. var startValue = this._getKeyValue(startKey.value);
  30555. var endValue = this._getKeyValue(endKey.value);
  30556. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  30557. var frameDelta = endKey.frame - startKey.frame;
  30558. // gradient : percent of currentFrame between the frame inf and the frame sup
  30559. var gradient = (currentFrame - startKey.frame) / frameDelta;
  30560. // check for easingFunction and correction of gradient
  30561. if (this._easingFunction != null) {
  30562. gradient = this._easingFunction.ease(gradient);
  30563. }
  30564. switch (this.dataType) {
  30565. // Float
  30566. case Animation.ANIMATIONTYPE_FLOAT:
  30567. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  30568. switch (loopMode) {
  30569. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30570. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30571. return floatValue;
  30572. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30573. return offsetValue * repeatCount + floatValue;
  30574. }
  30575. break;
  30576. // Quaternion
  30577. case Animation.ANIMATIONTYPE_QUATERNION:
  30578. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30579. switch (loopMode) {
  30580. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30581. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30582. return quatValue;
  30583. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30584. return quatValue.add(offsetValue.scale(repeatCount));
  30585. }
  30586. return quatValue;
  30587. // Vector3
  30588. case Animation.ANIMATIONTYPE_VECTOR3:
  30589. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  30590. switch (loopMode) {
  30591. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30592. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30593. return vec3Value;
  30594. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30595. return vec3Value.add(offsetValue.scale(repeatCount));
  30596. }
  30597. // Vector2
  30598. case Animation.ANIMATIONTYPE_VECTOR2:
  30599. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  30600. switch (loopMode) {
  30601. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30602. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30603. return vec2Value;
  30604. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30605. return vec2Value.add(offsetValue.scale(repeatCount));
  30606. }
  30607. // Size
  30608. case Animation.ANIMATIONTYPE_SIZE:
  30609. switch (loopMode) {
  30610. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30611. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30612. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30613. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30614. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30615. }
  30616. // Color3
  30617. case Animation.ANIMATIONTYPE_COLOR3:
  30618. switch (loopMode) {
  30619. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30620. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30621. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30622. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30623. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30624. }
  30625. // Matrix
  30626. case Animation.ANIMATIONTYPE_MATRIX:
  30627. switch (loopMode) {
  30628. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30629. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30630. if (this.allowMatricesInterpolation) {
  30631. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30632. }
  30633. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30634. return startValue;
  30635. }
  30636. default:
  30637. break;
  30638. }
  30639. break;
  30640. }
  30641. }
  30642. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30643. };
  30644. Animation.prototype.setValue = function (currentValue, blend) {
  30645. if (blend === void 0) { blend = false; }
  30646. // Set value
  30647. var path;
  30648. var destination;
  30649. if (this.targetPropertyPath.length > 1) {
  30650. var property = this._target[this.targetPropertyPath[0]];
  30651. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30652. property = property[this.targetPropertyPath[index]];
  30653. }
  30654. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30655. destination = property;
  30656. }
  30657. else {
  30658. path = this.targetPropertyPath[0];
  30659. destination = this._target;
  30660. }
  30661. // Blending
  30662. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30663. if (!this._originalBlendValue) {
  30664. if (destination[path].clone) {
  30665. this._originalBlendValue = destination[path].clone();
  30666. }
  30667. else {
  30668. this._originalBlendValue = destination[path];
  30669. }
  30670. }
  30671. if (this._originalBlendValue.prototype) {
  30672. if (this._originalBlendValue.prototype.Lerp) {
  30673. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30674. }
  30675. else {
  30676. destination[path] = currentValue;
  30677. }
  30678. }
  30679. else if (this._originalBlendValue.m) {
  30680. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30681. }
  30682. else {
  30683. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30684. }
  30685. this._blendingFactor += this.blendingSpeed;
  30686. }
  30687. else {
  30688. destination[path] = currentValue;
  30689. }
  30690. if (this._target.markAsDirty) {
  30691. this._target.markAsDirty(this.targetProperty);
  30692. }
  30693. };
  30694. Animation.prototype.goToFrame = function (frame) {
  30695. if (frame < this._keys[0].frame) {
  30696. frame = this._keys[0].frame;
  30697. }
  30698. else if (frame > this._keys[this._keys.length - 1].frame) {
  30699. frame = this._keys[this._keys.length - 1].frame;
  30700. }
  30701. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30702. this.setValue(currentValue);
  30703. };
  30704. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30705. if (blend === void 0) { blend = false; }
  30706. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30707. this._stopped = true;
  30708. return false;
  30709. }
  30710. var returnValue = true;
  30711. // Adding a start key at frame 0 if missing
  30712. if (this._keys[0].frame !== 0) {
  30713. var newKey = { frame: 0, value: this._keys[0].value };
  30714. this._keys.splice(0, 0, newKey);
  30715. }
  30716. // Check limits
  30717. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30718. from = this._keys[0].frame;
  30719. }
  30720. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30721. to = this._keys[this._keys.length - 1].frame;
  30722. }
  30723. //to and from cannot be the same key
  30724. if (from === to) {
  30725. from++;
  30726. }
  30727. // Compute ratio
  30728. var range = to - from;
  30729. var offsetValue;
  30730. // ratio represents the frame delta between from and to
  30731. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30732. var highLimitValue = 0;
  30733. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  30734. returnValue = false;
  30735. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30736. }
  30737. else {
  30738. // Get max value if required
  30739. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30740. var keyOffset = to.toString() + from.toString();
  30741. if (!this._offsetsCache[keyOffset]) {
  30742. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30743. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30744. switch (this.dataType) {
  30745. // Float
  30746. case Animation.ANIMATIONTYPE_FLOAT:
  30747. this._offsetsCache[keyOffset] = toValue - fromValue;
  30748. break;
  30749. // Quaternion
  30750. case Animation.ANIMATIONTYPE_QUATERNION:
  30751. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30752. break;
  30753. // Vector3
  30754. case Animation.ANIMATIONTYPE_VECTOR3:
  30755. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30756. // Vector2
  30757. case Animation.ANIMATIONTYPE_VECTOR2:
  30758. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30759. // Size
  30760. case Animation.ANIMATIONTYPE_SIZE:
  30761. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30762. // Color3
  30763. case Animation.ANIMATIONTYPE_COLOR3:
  30764. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30765. default:
  30766. break;
  30767. }
  30768. this._highLimitsCache[keyOffset] = toValue;
  30769. }
  30770. highLimitValue = this._highLimitsCache[keyOffset];
  30771. offsetValue = this._offsetsCache[keyOffset];
  30772. }
  30773. }
  30774. if (offsetValue === undefined) {
  30775. switch (this.dataType) {
  30776. // Float
  30777. case Animation.ANIMATIONTYPE_FLOAT:
  30778. offsetValue = 0;
  30779. break;
  30780. // Quaternion
  30781. case Animation.ANIMATIONTYPE_QUATERNION:
  30782. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30783. break;
  30784. // Vector3
  30785. case Animation.ANIMATIONTYPE_VECTOR3:
  30786. offsetValue = BABYLON.Vector3.Zero();
  30787. break;
  30788. // Vector2
  30789. case Animation.ANIMATIONTYPE_VECTOR2:
  30790. offsetValue = BABYLON.Vector2.Zero();
  30791. break;
  30792. // Size
  30793. case Animation.ANIMATIONTYPE_SIZE:
  30794. offsetValue = BABYLON.Size.Zero();
  30795. break;
  30796. // Color3
  30797. case Animation.ANIMATIONTYPE_COLOR3:
  30798. offsetValue = BABYLON.Color3.Black();
  30799. }
  30800. }
  30801. // Compute value
  30802. var repeatCount = (ratio / range) >> 0;
  30803. var currentFrame = returnValue ? from + ratio % range : to;
  30804. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30805. // Set value
  30806. this.setValue(currentValue);
  30807. // Check events
  30808. for (var index = 0; index < this._events.length; index++) {
  30809. // Make sure current frame has passed event frame and that event frame is within the current range
  30810. // Also, handle both forward and reverse animations
  30811. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  30812. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  30813. var event = this._events[index];
  30814. if (!event.isDone) {
  30815. // If event should be done only once, remove it.
  30816. if (event.onlyOnce) {
  30817. this._events.splice(index, 1);
  30818. index--;
  30819. }
  30820. event.isDone = true;
  30821. event.action();
  30822. } // Don't do anything if the event has already be done.
  30823. }
  30824. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30825. // reset event, the animation is looping
  30826. this._events[index].isDone = false;
  30827. }
  30828. }
  30829. if (!returnValue) {
  30830. this._stopped = true;
  30831. }
  30832. return returnValue;
  30833. };
  30834. Animation.prototype.serialize = function () {
  30835. var serializationObject = {};
  30836. serializationObject.name = this.name;
  30837. serializationObject.property = this.targetProperty;
  30838. serializationObject.framePerSecond = this.framePerSecond;
  30839. serializationObject.dataType = this.dataType;
  30840. serializationObject.loopBehavior = this.loopMode;
  30841. serializationObject.enableBlending = this.enableBlending;
  30842. serializationObject.blendingSpeed = this.blendingSpeed;
  30843. var dataType = this.dataType;
  30844. serializationObject.keys = [];
  30845. var keys = this.getKeys();
  30846. for (var index = 0; index < keys.length; index++) {
  30847. var animationKey = keys[index];
  30848. var key = {};
  30849. key.frame = animationKey.frame;
  30850. switch (dataType) {
  30851. case Animation.ANIMATIONTYPE_FLOAT:
  30852. key.values = [animationKey.value];
  30853. break;
  30854. case Animation.ANIMATIONTYPE_QUATERNION:
  30855. case Animation.ANIMATIONTYPE_MATRIX:
  30856. case Animation.ANIMATIONTYPE_VECTOR3:
  30857. case Animation.ANIMATIONTYPE_COLOR3:
  30858. key.values = animationKey.value.asArray();
  30859. break;
  30860. }
  30861. serializationObject.keys.push(key);
  30862. }
  30863. serializationObject.ranges = [];
  30864. for (var name in this._ranges) {
  30865. var range = {};
  30866. range.name = name;
  30867. range.from = this._ranges[name].from;
  30868. range.to = this._ranges[name].to;
  30869. serializationObject.ranges.push(range);
  30870. }
  30871. return serializationObject;
  30872. };
  30873. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30874. get: function () {
  30875. return Animation._ANIMATIONTYPE_FLOAT;
  30876. },
  30877. enumerable: true,
  30878. configurable: true
  30879. });
  30880. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30881. get: function () {
  30882. return Animation._ANIMATIONTYPE_VECTOR3;
  30883. },
  30884. enumerable: true,
  30885. configurable: true
  30886. });
  30887. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30888. get: function () {
  30889. return Animation._ANIMATIONTYPE_VECTOR2;
  30890. },
  30891. enumerable: true,
  30892. configurable: true
  30893. });
  30894. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30895. get: function () {
  30896. return Animation._ANIMATIONTYPE_SIZE;
  30897. },
  30898. enumerable: true,
  30899. configurable: true
  30900. });
  30901. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30902. get: function () {
  30903. return Animation._ANIMATIONTYPE_QUATERNION;
  30904. },
  30905. enumerable: true,
  30906. configurable: true
  30907. });
  30908. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30909. get: function () {
  30910. return Animation._ANIMATIONTYPE_MATRIX;
  30911. },
  30912. enumerable: true,
  30913. configurable: true
  30914. });
  30915. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30916. get: function () {
  30917. return Animation._ANIMATIONTYPE_COLOR3;
  30918. },
  30919. enumerable: true,
  30920. configurable: true
  30921. });
  30922. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30923. get: function () {
  30924. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30925. },
  30926. enumerable: true,
  30927. configurable: true
  30928. });
  30929. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30930. get: function () {
  30931. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30932. },
  30933. enumerable: true,
  30934. configurable: true
  30935. });
  30936. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30937. get: function () {
  30938. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30939. },
  30940. enumerable: true,
  30941. configurable: true
  30942. });
  30943. Animation.Parse = function (parsedAnimation) {
  30944. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30945. var dataType = parsedAnimation.dataType;
  30946. var keys = [];
  30947. var data;
  30948. var index;
  30949. if (parsedAnimation.enableBlending) {
  30950. animation.enableBlending = parsedAnimation.enableBlending;
  30951. }
  30952. if (parsedAnimation.blendingSpeed) {
  30953. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30954. }
  30955. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30956. var key = parsedAnimation.keys[index];
  30957. switch (dataType) {
  30958. case Animation.ANIMATIONTYPE_FLOAT:
  30959. data = key.values[0];
  30960. break;
  30961. case Animation.ANIMATIONTYPE_QUATERNION:
  30962. data = BABYLON.Quaternion.FromArray(key.values);
  30963. break;
  30964. case Animation.ANIMATIONTYPE_MATRIX:
  30965. data = BABYLON.Matrix.FromArray(key.values);
  30966. break;
  30967. case Animation.ANIMATIONTYPE_COLOR3:
  30968. data = BABYLON.Color3.FromArray(key.values);
  30969. break;
  30970. case Animation.ANIMATIONTYPE_VECTOR3:
  30971. default:
  30972. data = BABYLON.Vector3.FromArray(key.values);
  30973. break;
  30974. }
  30975. keys.push({
  30976. frame: key.frame,
  30977. value: data
  30978. });
  30979. }
  30980. animation.setKeys(keys);
  30981. if (parsedAnimation.ranges) {
  30982. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30983. data = parsedAnimation.ranges[index];
  30984. animation.createRange(data.name, data.from, data.to);
  30985. }
  30986. }
  30987. return animation;
  30988. };
  30989. Animation.AppendSerializedAnimations = function (source, destination) {
  30990. if (source.animations) {
  30991. destination.animations = [];
  30992. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30993. var animation = source.animations[animationIndex];
  30994. destination.animations.push(animation.serialize());
  30995. }
  30996. }
  30997. };
  30998. // Statics
  30999. Animation._ANIMATIONTYPE_FLOAT = 0;
  31000. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  31001. Animation._ANIMATIONTYPE_QUATERNION = 2;
  31002. Animation._ANIMATIONTYPE_MATRIX = 3;
  31003. Animation._ANIMATIONTYPE_COLOR3 = 4;
  31004. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  31005. Animation._ANIMATIONTYPE_SIZE = 6;
  31006. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  31007. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  31008. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  31009. return Animation;
  31010. }());
  31011. BABYLON.Animation = Animation;
  31012. })(BABYLON || (BABYLON = {}));
  31013. //# sourceMappingURL=babylon.animation.js.map
  31014. var BABYLON;
  31015. (function (BABYLON) {
  31016. var Animatable = (function () {
  31017. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  31018. if (fromFrame === void 0) { fromFrame = 0; }
  31019. if (toFrame === void 0) { toFrame = 100; }
  31020. if (loopAnimation === void 0) { loopAnimation = false; }
  31021. if (speedRatio === void 0) { speedRatio = 1.0; }
  31022. this.target = target;
  31023. this.fromFrame = fromFrame;
  31024. this.toFrame = toFrame;
  31025. this.loopAnimation = loopAnimation;
  31026. this.speedRatio = speedRatio;
  31027. this.onAnimationEnd = onAnimationEnd;
  31028. this._localDelayOffset = null;
  31029. this._pausedDelay = null;
  31030. this._animations = new Array();
  31031. this._paused = false;
  31032. this.animationStarted = false;
  31033. if (animations) {
  31034. this.appendAnimations(target, animations);
  31035. }
  31036. this._scene = scene;
  31037. scene._activeAnimatables.push(this);
  31038. }
  31039. // Methods
  31040. Animatable.prototype.getAnimations = function () {
  31041. return this._animations;
  31042. };
  31043. Animatable.prototype.appendAnimations = function (target, animations) {
  31044. for (var index = 0; index < animations.length; index++) {
  31045. var animation = animations[index];
  31046. animation._target = target;
  31047. this._animations.push(animation);
  31048. }
  31049. };
  31050. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  31051. var animations = this._animations;
  31052. for (var index = 0; index < animations.length; index++) {
  31053. if (animations[index].targetProperty === property) {
  31054. return animations[index];
  31055. }
  31056. }
  31057. return null;
  31058. };
  31059. Animatable.prototype.reset = function () {
  31060. var animations = this._animations;
  31061. for (var index = 0; index < animations.length; index++) {
  31062. animations[index].reset();
  31063. }
  31064. this._localDelayOffset = null;
  31065. this._pausedDelay = null;
  31066. };
  31067. Animatable.prototype.enableBlending = function (blendingSpeed) {
  31068. var animations = this._animations;
  31069. for (var index = 0; index < animations.length; index++) {
  31070. animations[index].enableBlending = true;
  31071. animations[index].blendingSpeed = blendingSpeed;
  31072. }
  31073. };
  31074. Animatable.prototype.disableBlending = function () {
  31075. var animations = this._animations;
  31076. for (var index = 0; index < animations.length; index++) {
  31077. animations[index].enableBlending = false;
  31078. }
  31079. };
  31080. Animatable.prototype.goToFrame = function (frame) {
  31081. var animations = this._animations;
  31082. if (animations[0]) {
  31083. var fps = animations[0].framePerSecond;
  31084. var currentFrame = animations[0].currentFrame;
  31085. var adjustTime = frame - currentFrame;
  31086. var delay = adjustTime * 1000 / fps;
  31087. this._localDelayOffset -= delay;
  31088. }
  31089. for (var index = 0; index < animations.length; index++) {
  31090. animations[index].goToFrame(frame);
  31091. }
  31092. };
  31093. Animatable.prototype.pause = function () {
  31094. if (this._paused) {
  31095. return;
  31096. }
  31097. this._paused = true;
  31098. };
  31099. Animatable.prototype.restart = function () {
  31100. this._paused = false;
  31101. };
  31102. Animatable.prototype.stop = function (animationName) {
  31103. if (animationName) {
  31104. var idx = this._scene._activeAnimatables.indexOf(this);
  31105. if (idx > -1) {
  31106. var animations = this._animations;
  31107. for (var index = animations.length - 1; index >= 0; index--) {
  31108. if (typeof animationName === "string" && animations[index].name != animationName) {
  31109. continue;
  31110. }
  31111. animations[index].reset();
  31112. animations.splice(index, 1);
  31113. }
  31114. if (animations.length == 0) {
  31115. this._scene._activeAnimatables.splice(idx, 1);
  31116. if (this.onAnimationEnd) {
  31117. this.onAnimationEnd();
  31118. }
  31119. }
  31120. }
  31121. }
  31122. else {
  31123. var index = this._scene._activeAnimatables.indexOf(this);
  31124. if (index > -1) {
  31125. this._scene._activeAnimatables.splice(index, 1);
  31126. var animations = this._animations;
  31127. for (var index = 0; index < animations.length; index++) {
  31128. animations[index].reset();
  31129. }
  31130. if (this.onAnimationEnd) {
  31131. this.onAnimationEnd();
  31132. }
  31133. }
  31134. }
  31135. };
  31136. Animatable.prototype._animate = function (delay) {
  31137. if (this._paused) {
  31138. this.animationStarted = false;
  31139. if (this._pausedDelay === null) {
  31140. this._pausedDelay = delay;
  31141. }
  31142. return true;
  31143. }
  31144. if (this._localDelayOffset === null) {
  31145. this._localDelayOffset = delay;
  31146. }
  31147. else if (this._pausedDelay !== null) {
  31148. this._localDelayOffset += delay - this._pausedDelay;
  31149. this._pausedDelay = null;
  31150. }
  31151. // Animating
  31152. var running = false;
  31153. var animations = this._animations;
  31154. var index;
  31155. for (index = 0; index < animations.length; index++) {
  31156. var animation = animations[index];
  31157. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  31158. running = running || isRunning;
  31159. }
  31160. this.animationStarted = running;
  31161. if (!running) {
  31162. // Remove from active animatables
  31163. index = this._scene._activeAnimatables.indexOf(this);
  31164. this._scene._activeAnimatables.splice(index, 1);
  31165. }
  31166. if (!running && this.onAnimationEnd) {
  31167. this.onAnimationEnd();
  31168. this.onAnimationEnd = null;
  31169. }
  31170. return running;
  31171. };
  31172. return Animatable;
  31173. }());
  31174. BABYLON.Animatable = Animatable;
  31175. })(BABYLON || (BABYLON = {}));
  31176. //# sourceMappingURL=babylon.animatable.js.map
  31177. var BABYLON;
  31178. (function (BABYLON) {
  31179. var EasingFunction = (function () {
  31180. function EasingFunction() {
  31181. // Properties
  31182. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  31183. }
  31184. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  31185. get: function () {
  31186. return EasingFunction._EASINGMODE_EASEIN;
  31187. },
  31188. enumerable: true,
  31189. configurable: true
  31190. });
  31191. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  31192. get: function () {
  31193. return EasingFunction._EASINGMODE_EASEOUT;
  31194. },
  31195. enumerable: true,
  31196. configurable: true
  31197. });
  31198. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  31199. get: function () {
  31200. return EasingFunction._EASINGMODE_EASEINOUT;
  31201. },
  31202. enumerable: true,
  31203. configurable: true
  31204. });
  31205. EasingFunction.prototype.setEasingMode = function (easingMode) {
  31206. var n = Math.min(Math.max(easingMode, 0), 2);
  31207. this._easingMode = n;
  31208. };
  31209. EasingFunction.prototype.getEasingMode = function () {
  31210. return this._easingMode;
  31211. };
  31212. EasingFunction.prototype.easeInCore = function (gradient) {
  31213. throw new Error('You must implement this method');
  31214. };
  31215. EasingFunction.prototype.ease = function (gradient) {
  31216. switch (this._easingMode) {
  31217. case EasingFunction.EASINGMODE_EASEIN:
  31218. return this.easeInCore(gradient);
  31219. case EasingFunction.EASINGMODE_EASEOUT:
  31220. return (1 - this.easeInCore(1 - gradient));
  31221. }
  31222. if (gradient >= 0.5) {
  31223. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  31224. }
  31225. return (this.easeInCore(gradient * 2) * 0.5);
  31226. };
  31227. //Statics
  31228. EasingFunction._EASINGMODE_EASEIN = 0;
  31229. EasingFunction._EASINGMODE_EASEOUT = 1;
  31230. EasingFunction._EASINGMODE_EASEINOUT = 2;
  31231. return EasingFunction;
  31232. }());
  31233. BABYLON.EasingFunction = EasingFunction;
  31234. var CircleEase = (function (_super) {
  31235. __extends(CircleEase, _super);
  31236. function CircleEase() {
  31237. return _super !== null && _super.apply(this, arguments) || this;
  31238. }
  31239. CircleEase.prototype.easeInCore = function (gradient) {
  31240. gradient = Math.max(0, Math.min(1, gradient));
  31241. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  31242. };
  31243. return CircleEase;
  31244. }(EasingFunction));
  31245. BABYLON.CircleEase = CircleEase;
  31246. var BackEase = (function (_super) {
  31247. __extends(BackEase, _super);
  31248. function BackEase(amplitude) {
  31249. if (amplitude === void 0) { amplitude = 1; }
  31250. var _this = _super.call(this) || this;
  31251. _this.amplitude = amplitude;
  31252. return _this;
  31253. }
  31254. BackEase.prototype.easeInCore = function (gradient) {
  31255. var num = Math.max(0, this.amplitude);
  31256. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  31257. };
  31258. return BackEase;
  31259. }(EasingFunction));
  31260. BABYLON.BackEase = BackEase;
  31261. var BounceEase = (function (_super) {
  31262. __extends(BounceEase, _super);
  31263. function BounceEase(bounces, bounciness) {
  31264. if (bounces === void 0) { bounces = 3; }
  31265. if (bounciness === void 0) { bounciness = 2; }
  31266. var _this = _super.call(this) || this;
  31267. _this.bounces = bounces;
  31268. _this.bounciness = bounciness;
  31269. return _this;
  31270. }
  31271. BounceEase.prototype.easeInCore = function (gradient) {
  31272. var y = Math.max(0.0, this.bounces);
  31273. var bounciness = this.bounciness;
  31274. if (bounciness <= 1.0) {
  31275. bounciness = 1.001;
  31276. }
  31277. var num9 = Math.pow(bounciness, y);
  31278. var num5 = 1.0 - bounciness;
  31279. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  31280. var num15 = gradient * num4;
  31281. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  31282. var num3 = Math.floor(num65);
  31283. var num13 = num3 + 1.0;
  31284. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  31285. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  31286. var num7 = (num8 + num12) * 0.5;
  31287. var num6 = gradient - num7;
  31288. var num2 = num7 - num8;
  31289. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  31290. };
  31291. return BounceEase;
  31292. }(EasingFunction));
  31293. BABYLON.BounceEase = BounceEase;
  31294. var CubicEase = (function (_super) {
  31295. __extends(CubicEase, _super);
  31296. function CubicEase() {
  31297. return _super !== null && _super.apply(this, arguments) || this;
  31298. }
  31299. CubicEase.prototype.easeInCore = function (gradient) {
  31300. return (gradient * gradient * gradient);
  31301. };
  31302. return CubicEase;
  31303. }(EasingFunction));
  31304. BABYLON.CubicEase = CubicEase;
  31305. var ElasticEase = (function (_super) {
  31306. __extends(ElasticEase, _super);
  31307. function ElasticEase(oscillations, springiness) {
  31308. if (oscillations === void 0) { oscillations = 3; }
  31309. if (springiness === void 0) { springiness = 3; }
  31310. var _this = _super.call(this) || this;
  31311. _this.oscillations = oscillations;
  31312. _this.springiness = springiness;
  31313. return _this;
  31314. }
  31315. ElasticEase.prototype.easeInCore = function (gradient) {
  31316. var num2;
  31317. var num3 = Math.max(0.0, this.oscillations);
  31318. var num = Math.max(0.0, this.springiness);
  31319. if (num == 0) {
  31320. num2 = gradient;
  31321. }
  31322. else {
  31323. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  31324. }
  31325. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  31326. };
  31327. return ElasticEase;
  31328. }(EasingFunction));
  31329. BABYLON.ElasticEase = ElasticEase;
  31330. var ExponentialEase = (function (_super) {
  31331. __extends(ExponentialEase, _super);
  31332. function ExponentialEase(exponent) {
  31333. if (exponent === void 0) { exponent = 2; }
  31334. var _this = _super.call(this) || this;
  31335. _this.exponent = exponent;
  31336. return _this;
  31337. }
  31338. ExponentialEase.prototype.easeInCore = function (gradient) {
  31339. if (this.exponent <= 0) {
  31340. return gradient;
  31341. }
  31342. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  31343. };
  31344. return ExponentialEase;
  31345. }(EasingFunction));
  31346. BABYLON.ExponentialEase = ExponentialEase;
  31347. var PowerEase = (function (_super) {
  31348. __extends(PowerEase, _super);
  31349. function PowerEase(power) {
  31350. if (power === void 0) { power = 2; }
  31351. var _this = _super.call(this) || this;
  31352. _this.power = power;
  31353. return _this;
  31354. }
  31355. PowerEase.prototype.easeInCore = function (gradient) {
  31356. var y = Math.max(0.0, this.power);
  31357. return Math.pow(gradient, y);
  31358. };
  31359. return PowerEase;
  31360. }(EasingFunction));
  31361. BABYLON.PowerEase = PowerEase;
  31362. var QuadraticEase = (function (_super) {
  31363. __extends(QuadraticEase, _super);
  31364. function QuadraticEase() {
  31365. return _super !== null && _super.apply(this, arguments) || this;
  31366. }
  31367. QuadraticEase.prototype.easeInCore = function (gradient) {
  31368. return (gradient * gradient);
  31369. };
  31370. return QuadraticEase;
  31371. }(EasingFunction));
  31372. BABYLON.QuadraticEase = QuadraticEase;
  31373. var QuarticEase = (function (_super) {
  31374. __extends(QuarticEase, _super);
  31375. function QuarticEase() {
  31376. return _super !== null && _super.apply(this, arguments) || this;
  31377. }
  31378. QuarticEase.prototype.easeInCore = function (gradient) {
  31379. return (gradient * gradient * gradient * gradient);
  31380. };
  31381. return QuarticEase;
  31382. }(EasingFunction));
  31383. BABYLON.QuarticEase = QuarticEase;
  31384. var QuinticEase = (function (_super) {
  31385. __extends(QuinticEase, _super);
  31386. function QuinticEase() {
  31387. return _super !== null && _super.apply(this, arguments) || this;
  31388. }
  31389. QuinticEase.prototype.easeInCore = function (gradient) {
  31390. return (gradient * gradient * gradient * gradient * gradient);
  31391. };
  31392. return QuinticEase;
  31393. }(EasingFunction));
  31394. BABYLON.QuinticEase = QuinticEase;
  31395. var SineEase = (function (_super) {
  31396. __extends(SineEase, _super);
  31397. function SineEase() {
  31398. return _super !== null && _super.apply(this, arguments) || this;
  31399. }
  31400. SineEase.prototype.easeInCore = function (gradient) {
  31401. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  31402. };
  31403. return SineEase;
  31404. }(EasingFunction));
  31405. BABYLON.SineEase = SineEase;
  31406. var BezierCurveEase = (function (_super) {
  31407. __extends(BezierCurveEase, _super);
  31408. function BezierCurveEase(x1, y1, x2, y2) {
  31409. if (x1 === void 0) { x1 = 0; }
  31410. if (y1 === void 0) { y1 = 0; }
  31411. if (x2 === void 0) { x2 = 1; }
  31412. if (y2 === void 0) { y2 = 1; }
  31413. var _this = _super.call(this) || this;
  31414. _this.x1 = x1;
  31415. _this.y1 = y1;
  31416. _this.x2 = x2;
  31417. _this.y2 = y2;
  31418. return _this;
  31419. }
  31420. BezierCurveEase.prototype.easeInCore = function (gradient) {
  31421. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  31422. };
  31423. return BezierCurveEase;
  31424. }(EasingFunction));
  31425. BABYLON.BezierCurveEase = BezierCurveEase;
  31426. })(BABYLON || (BABYLON = {}));
  31427. //# sourceMappingURL=babylon.easing.js.map
  31428. var BABYLON;
  31429. (function (BABYLON) {
  31430. BABYLON.CameraInputTypes = {};
  31431. var CameraInputsManager = (function () {
  31432. function CameraInputsManager(camera) {
  31433. this.attached = {};
  31434. this.camera = camera;
  31435. this.checkInputs = function () { };
  31436. }
  31437. CameraInputsManager.prototype.add = function (input) {
  31438. var type = input.getSimpleName();
  31439. if (this.attached[type]) {
  31440. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31441. return;
  31442. }
  31443. this.attached[type] = input;
  31444. input.camera = this.camera;
  31445. //for checkInputs, we are dynamically creating a function
  31446. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31447. if (input.checkInputs) {
  31448. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31449. }
  31450. if (this.attachedElement) {
  31451. input.attachControl(this.attachedElement);
  31452. }
  31453. };
  31454. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31455. for (var cam in this.attached) {
  31456. var input = this.attached[cam];
  31457. if (input === inputToRemove) {
  31458. input.detachControl(this.attachedElement);
  31459. input.camera = null;
  31460. delete this.attached[cam];
  31461. this.rebuildInputCheck();
  31462. }
  31463. }
  31464. };
  31465. CameraInputsManager.prototype.removeByType = function (inputType) {
  31466. for (var cam in this.attached) {
  31467. var input = this.attached[cam];
  31468. if (input.getClassName() === inputType) {
  31469. input.detachControl(this.attachedElement);
  31470. input.camera = null;
  31471. delete this.attached[cam];
  31472. this.rebuildInputCheck();
  31473. }
  31474. }
  31475. };
  31476. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31477. var current = this.checkInputs;
  31478. return function () {
  31479. current();
  31480. fn();
  31481. };
  31482. };
  31483. CameraInputsManager.prototype.attachInput = function (input) {
  31484. input.attachControl(this.attachedElement, this.noPreventDefault);
  31485. };
  31486. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31487. if (this.attachedElement) {
  31488. return;
  31489. }
  31490. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31491. this.attachedElement = element;
  31492. this.noPreventDefault = noPreventDefault;
  31493. for (var cam in this.attached) {
  31494. var input = this.attached[cam];
  31495. this.attached[cam].attachControl(element, noPreventDefault);
  31496. }
  31497. };
  31498. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  31499. if (disconnect === void 0) { disconnect = false; }
  31500. if (this.attachedElement !== element) {
  31501. return;
  31502. }
  31503. for (var cam in this.attached) {
  31504. var input = this.attached[cam];
  31505. this.attached[cam].detachControl(element);
  31506. if (disconnect) {
  31507. this.attached[cam].camera = null;
  31508. }
  31509. }
  31510. this.attachedElement = null;
  31511. };
  31512. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31513. this.checkInputs = function () { };
  31514. for (var cam in this.attached) {
  31515. var input = this.attached[cam];
  31516. if (input.checkInputs) {
  31517. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31518. }
  31519. }
  31520. };
  31521. CameraInputsManager.prototype.clear = function () {
  31522. if (this.attachedElement) {
  31523. this.detachElement(this.attachedElement, true);
  31524. }
  31525. this.attached = {};
  31526. this.attachedElement = null;
  31527. this.checkInputs = function () { };
  31528. };
  31529. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31530. var inputs = {};
  31531. for (var cam in this.attached) {
  31532. var input = this.attached[cam];
  31533. var res = BABYLON.SerializationHelper.Serialize(input);
  31534. inputs[input.getClassName()] = res;
  31535. }
  31536. serializedCamera.inputsmgr = inputs;
  31537. };
  31538. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31539. var parsedInputs = parsedCamera.inputsmgr;
  31540. if (parsedInputs) {
  31541. this.clear();
  31542. for (var n in parsedInputs) {
  31543. var construct = BABYLON.CameraInputTypes[n];
  31544. if (construct) {
  31545. var parsedinput = parsedInputs[n];
  31546. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31547. this.add(input);
  31548. }
  31549. }
  31550. }
  31551. else {
  31552. //2016-03-08 this part is for managing backward compatibility
  31553. for (var n in this.attached) {
  31554. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  31555. if (construct) {
  31556. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31557. this.remove(this.attached[n]);
  31558. this.add(input);
  31559. }
  31560. }
  31561. }
  31562. };
  31563. return CameraInputsManager;
  31564. }());
  31565. BABYLON.CameraInputsManager = CameraInputsManager;
  31566. })(BABYLON || (BABYLON = {}));
  31567. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31568. /// <reference path="babylon.camera.ts" />
  31569. var BABYLON;
  31570. (function (BABYLON) {
  31571. var TargetCamera = (function (_super) {
  31572. __extends(TargetCamera, _super);
  31573. function TargetCamera(name, position, scene) {
  31574. var _this = _super.call(this, name, position, scene) || this;
  31575. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31576. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31577. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31578. _this.speed = 2.0;
  31579. _this.noRotationConstraint = false;
  31580. _this.lockedTarget = null;
  31581. _this._currentTarget = BABYLON.Vector3.Zero();
  31582. _this._viewMatrix = BABYLON.Matrix.Zero();
  31583. _this._camMatrix = BABYLON.Matrix.Zero();
  31584. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31585. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31586. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31587. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31588. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31589. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31590. _this._tempMatrix = BABYLON.Matrix.Zero();
  31591. return _this;
  31592. }
  31593. TargetCamera.prototype.getFrontPosition = function (distance) {
  31594. var direction = this.getTarget().subtract(this.position);
  31595. direction.normalize();
  31596. direction.scaleInPlace(distance);
  31597. return this.globalPosition.add(direction);
  31598. };
  31599. TargetCamera.prototype._getLockedTargetPosition = function () {
  31600. if (!this.lockedTarget) {
  31601. return null;
  31602. }
  31603. if (this.lockedTarget.absolutePosition) {
  31604. this.lockedTarget.computeWorldMatrix();
  31605. }
  31606. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31607. };
  31608. TargetCamera.prototype.storeState = function () {
  31609. this._storedPosition = this.position.clone();
  31610. this._storedRotation = this.rotation.clone();
  31611. if (this.rotationQuaternion) {
  31612. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  31613. }
  31614. return _super.prototype.storeState.call(this);
  31615. };
  31616. /**
  31617. * Restored camera state. You must call storeState() first
  31618. */
  31619. TargetCamera.prototype.restoreState = function () {
  31620. if (!_super.prototype.restoreState.call(this)) {
  31621. return false;
  31622. }
  31623. this.position = this._storedPosition.clone();
  31624. this.rotation = this._storedRotation.clone();
  31625. if (this.rotationQuaternion) {
  31626. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  31627. }
  31628. this.cameraDirection.copyFromFloats(0, 0, 0);
  31629. this.cameraRotation.copyFromFloats(0, 0);
  31630. return true;
  31631. };
  31632. // Cache
  31633. TargetCamera.prototype._initCache = function () {
  31634. _super.prototype._initCache.call(this);
  31635. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31636. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31637. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31638. };
  31639. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31640. if (!ignoreParentClass) {
  31641. _super.prototype._updateCache.call(this);
  31642. }
  31643. var lockedTargetPosition = this._getLockedTargetPosition();
  31644. if (!lockedTargetPosition) {
  31645. this._cache.lockedTarget = null;
  31646. }
  31647. else {
  31648. if (!this._cache.lockedTarget) {
  31649. this._cache.lockedTarget = lockedTargetPosition.clone();
  31650. }
  31651. else {
  31652. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31653. }
  31654. }
  31655. this._cache.rotation.copyFrom(this.rotation);
  31656. if (this.rotationQuaternion)
  31657. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31658. };
  31659. // Synchronized
  31660. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31661. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31662. return false;
  31663. }
  31664. var lockedTargetPosition = this._getLockedTargetPosition();
  31665. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31666. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31667. };
  31668. // Methods
  31669. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31670. var engine = this.getEngine();
  31671. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31672. };
  31673. // Target
  31674. TargetCamera.prototype.setTarget = function (target) {
  31675. this.upVector.normalize();
  31676. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31677. this._camMatrix.invert();
  31678. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31679. var vDir = target.subtract(this.position);
  31680. if (vDir.x >= 0.0) {
  31681. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31682. }
  31683. else {
  31684. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31685. }
  31686. this.rotation.z = 0;
  31687. if (isNaN(this.rotation.x)) {
  31688. this.rotation.x = 0;
  31689. }
  31690. if (isNaN(this.rotation.y)) {
  31691. this.rotation.y = 0;
  31692. }
  31693. if (isNaN(this.rotation.z)) {
  31694. this.rotation.z = 0;
  31695. }
  31696. if (this.rotationQuaternion) {
  31697. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31698. }
  31699. };
  31700. /**
  31701. * Return the current target position of the camera. This value is expressed in local space.
  31702. */
  31703. TargetCamera.prototype.getTarget = function () {
  31704. return this._currentTarget;
  31705. };
  31706. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31707. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31708. };
  31709. TargetCamera.prototype._updatePosition = function () {
  31710. if (this.parent) {
  31711. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31712. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31713. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31714. return;
  31715. }
  31716. this.position.addInPlace(this.cameraDirection);
  31717. };
  31718. TargetCamera.prototype._checkInputs = function () {
  31719. var needToMove = this._decideIfNeedsToMove();
  31720. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31721. // Move
  31722. if (needToMove) {
  31723. this._updatePosition();
  31724. }
  31725. // Rotate
  31726. if (needToRotate) {
  31727. this.rotation.x += this.cameraRotation.x;
  31728. this.rotation.y += this.cameraRotation.y;
  31729. //rotate, if quaternion is set and rotation was used
  31730. if (this.rotationQuaternion) {
  31731. var len = this.rotation.lengthSquared();
  31732. if (len) {
  31733. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31734. }
  31735. }
  31736. if (!this.noRotationConstraint) {
  31737. var limit = (Math.PI / 2) * 0.95;
  31738. if (this.rotation.x > limit)
  31739. this.rotation.x = limit;
  31740. if (this.rotation.x < -limit)
  31741. this.rotation.x = -limit;
  31742. }
  31743. }
  31744. // Inertia
  31745. if (needToMove) {
  31746. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31747. this.cameraDirection.x = 0;
  31748. }
  31749. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31750. this.cameraDirection.y = 0;
  31751. }
  31752. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31753. this.cameraDirection.z = 0;
  31754. }
  31755. this.cameraDirection.scaleInPlace(this.inertia);
  31756. }
  31757. if (needToRotate) {
  31758. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31759. this.cameraRotation.x = 0;
  31760. }
  31761. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31762. this.cameraRotation.y = 0;
  31763. }
  31764. this.cameraRotation.scaleInPlace(this.inertia);
  31765. }
  31766. _super.prototype._checkInputs.call(this);
  31767. };
  31768. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31769. if (this.rotationQuaternion) {
  31770. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31771. //update the up vector!
  31772. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31773. }
  31774. else {
  31775. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31776. }
  31777. };
  31778. TargetCamera.prototype._getViewMatrix = function () {
  31779. if (!this.lockedTarget) {
  31780. // Compute
  31781. this._updateCameraRotationMatrix();
  31782. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31783. // Computing target and final matrix
  31784. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31785. }
  31786. else {
  31787. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31788. }
  31789. if (this.getScene().useRightHandedSystem) {
  31790. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31791. }
  31792. else {
  31793. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31794. }
  31795. return this._viewMatrix;
  31796. };
  31797. /**
  31798. * @override
  31799. * Override Camera.createRigCamera
  31800. */
  31801. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31802. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31803. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31804. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31805. if (!this.rotationQuaternion) {
  31806. this.rotationQuaternion = new BABYLON.Quaternion();
  31807. }
  31808. rigCamera._cameraRigParams = {};
  31809. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31810. }
  31811. return rigCamera;
  31812. }
  31813. return null;
  31814. };
  31815. /**
  31816. * @override
  31817. * Override Camera._updateRigCameras
  31818. */
  31819. TargetCamera.prototype._updateRigCameras = function () {
  31820. var camLeft = this._rigCameras[0];
  31821. var camRight = this._rigCameras[1];
  31822. switch (this.cameraRigMode) {
  31823. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31824. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31825. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31826. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31827. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31828. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31829. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31830. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31831. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31832. camLeft.setTarget(this.getTarget());
  31833. camRight.setTarget(this.getTarget());
  31834. break;
  31835. case BABYLON.Camera.RIG_MODE_VR:
  31836. if (camLeft.rotationQuaternion) {
  31837. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31838. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31839. }
  31840. else {
  31841. camLeft.rotation.copyFrom(this.rotation);
  31842. camRight.rotation.copyFrom(this.rotation);
  31843. }
  31844. camLeft.position.copyFrom(this.position);
  31845. camRight.position.copyFrom(this.position);
  31846. break;
  31847. }
  31848. _super.prototype._updateRigCameras.call(this);
  31849. };
  31850. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31851. if (!this._rigCamTransformMatrix) {
  31852. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31853. }
  31854. var target = this.getTarget();
  31855. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31856. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31857. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31858. };
  31859. TargetCamera.prototype.getClassName = function () {
  31860. return "TargetCamera";
  31861. };
  31862. __decorate([
  31863. BABYLON.serializeAsVector3()
  31864. ], TargetCamera.prototype, "rotation", void 0);
  31865. __decorate([
  31866. BABYLON.serialize()
  31867. ], TargetCamera.prototype, "speed", void 0);
  31868. __decorate([
  31869. BABYLON.serializeAsMeshReference("lockedTargetId")
  31870. ], TargetCamera.prototype, "lockedTarget", void 0);
  31871. return TargetCamera;
  31872. }(BABYLON.Camera));
  31873. BABYLON.TargetCamera = TargetCamera;
  31874. })(BABYLON || (BABYLON = {}));
  31875. //# sourceMappingURL=babylon.targetCamera.js.map
  31876. var BABYLON;
  31877. (function (BABYLON) {
  31878. var ArcRotateCameraKeyboardMoveInput = (function () {
  31879. function ArcRotateCameraKeyboardMoveInput() {
  31880. this._keys = [];
  31881. this.keysUp = [38];
  31882. this.keysDown = [40];
  31883. this.keysLeft = [37];
  31884. this.keysRight = [39];
  31885. this.keysReset = [111];
  31886. this.panningSensibility = 50.0;
  31887. }
  31888. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31889. var _this = this;
  31890. if (this._onCanvasBlurObserver) {
  31891. return;
  31892. }
  31893. this._scene = this.camera.getScene();
  31894. this._engine = this._scene.getEngine();
  31895. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  31896. _this._keys = [];
  31897. });
  31898. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  31899. var evt = info.event;
  31900. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  31901. _this._ctrlPressed = evt.ctrlKey;
  31902. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31903. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31904. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31905. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  31906. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  31907. var index = _this._keys.indexOf(evt.keyCode);
  31908. if (index === -1) {
  31909. _this._keys.push(evt.keyCode);
  31910. }
  31911. if (evt.preventDefault) {
  31912. if (!noPreventDefault) {
  31913. evt.preventDefault();
  31914. }
  31915. }
  31916. }
  31917. }
  31918. else {
  31919. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31920. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31921. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31922. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  31923. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  31924. var index = _this._keys.indexOf(evt.keyCode);
  31925. if (index >= 0) {
  31926. _this._keys.splice(index, 1);
  31927. }
  31928. if (evt.preventDefault) {
  31929. if (!noPreventDefault) {
  31930. evt.preventDefault();
  31931. }
  31932. }
  31933. }
  31934. }
  31935. });
  31936. };
  31937. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31938. if (this._scene) {
  31939. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  31940. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  31941. this._onKeyboardObserver = null;
  31942. this._onCanvasBlurObserver = null;
  31943. }
  31944. this._keys = [];
  31945. };
  31946. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31947. if (this._onKeyboardObserver) {
  31948. var camera = this.camera;
  31949. for (var index = 0; index < this._keys.length; index++) {
  31950. var keyCode = this._keys[index];
  31951. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31952. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31953. camera.inertialPanningX -= 1 / this.panningSensibility;
  31954. }
  31955. else {
  31956. camera.inertialAlphaOffset -= 0.01;
  31957. }
  31958. }
  31959. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31960. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31961. camera.inertialPanningY += 1 / this.panningSensibility;
  31962. }
  31963. else {
  31964. camera.inertialBetaOffset -= 0.01;
  31965. }
  31966. }
  31967. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31968. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31969. camera.inertialPanningX += 1 / this.panningSensibility;
  31970. }
  31971. else {
  31972. camera.inertialAlphaOffset += 0.01;
  31973. }
  31974. }
  31975. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31976. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31977. camera.inertialPanningY -= 1 / this.panningSensibility;
  31978. }
  31979. else {
  31980. camera.inertialBetaOffset += 0.01;
  31981. }
  31982. }
  31983. else if (this.keysReset.indexOf(keyCode) !== -1) {
  31984. camera.restoreState();
  31985. }
  31986. }
  31987. }
  31988. };
  31989. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  31990. return "ArcRotateCameraKeyboardMoveInput";
  31991. };
  31992. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31993. return "keyboard";
  31994. };
  31995. __decorate([
  31996. BABYLON.serialize()
  31997. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31998. __decorate([
  31999. BABYLON.serialize()
  32000. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32001. __decorate([
  32002. BABYLON.serialize()
  32003. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32004. __decorate([
  32005. BABYLON.serialize()
  32006. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32007. __decorate([
  32008. BABYLON.serialize()
  32009. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  32010. __decorate([
  32011. BABYLON.serialize()
  32012. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  32013. return ArcRotateCameraKeyboardMoveInput;
  32014. }());
  32015. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  32016. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  32017. })(BABYLON || (BABYLON = {}));
  32018. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  32019. var BABYLON;
  32020. (function (BABYLON) {
  32021. var ArcRotateCameraMouseWheelInput = (function () {
  32022. function ArcRotateCameraMouseWheelInput() {
  32023. this.wheelPrecision = 3.0;
  32024. }
  32025. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  32026. var _this = this;
  32027. this._wheel = function (p, s) {
  32028. //sanity check - this should be a PointerWheel event.
  32029. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  32030. return;
  32031. var event = p.event;
  32032. var delta = 0;
  32033. if (event.wheelDelta) {
  32034. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  32035. }
  32036. else if (event.detail) {
  32037. delta = -event.detail / _this.wheelPrecision;
  32038. }
  32039. if (delta)
  32040. _this.camera.inertialRadiusOffset += delta;
  32041. if (event.preventDefault) {
  32042. if (!noPreventDefault) {
  32043. event.preventDefault();
  32044. }
  32045. }
  32046. };
  32047. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  32048. };
  32049. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  32050. if (this._observer && element) {
  32051. this.camera.getScene().onPointerObservable.remove(this._observer);
  32052. this._observer = null;
  32053. this._wheel = null;
  32054. }
  32055. };
  32056. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  32057. return "ArcRotateCameraMouseWheelInput";
  32058. };
  32059. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  32060. return "mousewheel";
  32061. };
  32062. __decorate([
  32063. BABYLON.serialize()
  32064. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  32065. return ArcRotateCameraMouseWheelInput;
  32066. }());
  32067. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  32068. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  32069. })(BABYLON || (BABYLON = {}));
  32070. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  32071. var BABYLON;
  32072. (function (BABYLON) {
  32073. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  32074. var ArcRotateCameraPointersInput = (function () {
  32075. function ArcRotateCameraPointersInput() {
  32076. this.buttons = [0, 1, 2];
  32077. this.angularSensibilityX = 1000.0;
  32078. this.angularSensibilityY = 1000.0;
  32079. this.pinchPrecision = 6.0;
  32080. this.panningSensibility = 50.0;
  32081. this._isPanClick = false;
  32082. this.pinchInwards = true;
  32083. }
  32084. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  32085. var _this = this;
  32086. var engine = this.camera.getEngine();
  32087. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  32088. var pointA, pointB;
  32089. var previousPinchDistance = 0;
  32090. this._pointerInput = function (p, s) {
  32091. var evt = p.event;
  32092. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  32093. return;
  32094. }
  32095. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  32096. try {
  32097. evt.srcElement.setPointerCapture(evt.pointerId);
  32098. }
  32099. catch (e) {
  32100. //Nothing to do with the error. Execution will continue.
  32101. }
  32102. // Manage panning with pan button click
  32103. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  32104. // manage pointers
  32105. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  32106. if (pointA === undefined) {
  32107. pointA = cacheSoloPointer;
  32108. }
  32109. else if (pointB === undefined) {
  32110. pointB = cacheSoloPointer;
  32111. }
  32112. if (!noPreventDefault) {
  32113. evt.preventDefault();
  32114. element.focus();
  32115. }
  32116. }
  32117. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  32118. _this.camera.restoreState();
  32119. }
  32120. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32121. try {
  32122. evt.srcElement.releasePointerCapture(evt.pointerId);
  32123. }
  32124. catch (e) {
  32125. //Nothing to do with the error.
  32126. }
  32127. cacheSoloPointer = null;
  32128. previousPinchDistance = 0;
  32129. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  32130. //but emptying completly pointers collection is required to fix a bug on iPhone :
  32131. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  32132. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  32133. pointA = pointB = undefined;
  32134. if (!noPreventDefault) {
  32135. evt.preventDefault();
  32136. }
  32137. }
  32138. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32139. if (!noPreventDefault) {
  32140. evt.preventDefault();
  32141. }
  32142. // One button down
  32143. if (pointA && pointB === undefined) {
  32144. if (_this.panningSensibility !== 0 &&
  32145. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  32146. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  32147. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  32148. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  32149. }
  32150. else {
  32151. var offsetX = evt.clientX - cacheSoloPointer.x;
  32152. var offsetY = evt.clientY - cacheSoloPointer.y;
  32153. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32154. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32155. }
  32156. cacheSoloPointer.x = evt.clientX;
  32157. cacheSoloPointer.y = evt.clientY;
  32158. }
  32159. else if (pointA && pointB) {
  32160. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  32161. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  32162. ed.x = evt.clientX;
  32163. ed.y = evt.clientY;
  32164. var direction = _this.pinchInwards ? 1 : -1;
  32165. var distX = pointA.x - pointB.x;
  32166. var distY = pointA.y - pointB.y;
  32167. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  32168. if (previousPinchDistance === 0) {
  32169. previousPinchDistance = pinchSquaredDistance;
  32170. return;
  32171. }
  32172. if (pinchSquaredDistance !== previousPinchDistance) {
  32173. _this.camera
  32174. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  32175. (_this.pinchPrecision *
  32176. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  32177. direction);
  32178. previousPinchDistance = pinchSquaredDistance;
  32179. }
  32180. }
  32181. }
  32182. };
  32183. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  32184. this._onContextMenu = function (evt) {
  32185. evt.preventDefault();
  32186. };
  32187. if (!this.camera._useCtrlForPanning) {
  32188. element.addEventListener("contextmenu", this._onContextMenu, false);
  32189. }
  32190. this._onLostFocus = function () {
  32191. //this._keys = [];
  32192. pointA = pointB = undefined;
  32193. previousPinchDistance = 0;
  32194. cacheSoloPointer = null;
  32195. };
  32196. this._onMouseMove = function (evt) {
  32197. if (!engine.isPointerLock) {
  32198. return;
  32199. }
  32200. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32201. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32202. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32203. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32204. if (!noPreventDefault) {
  32205. evt.preventDefault();
  32206. }
  32207. };
  32208. this._onGestureStart = function (e) {
  32209. if (window.MSGesture === undefined) {
  32210. return;
  32211. }
  32212. if (!_this._MSGestureHandler) {
  32213. _this._MSGestureHandler = new MSGesture();
  32214. _this._MSGestureHandler.target = element;
  32215. }
  32216. _this._MSGestureHandler.addPointer(e.pointerId);
  32217. };
  32218. this._onGesture = function (e) {
  32219. _this.camera.radius *= e.scale;
  32220. if (e.preventDefault) {
  32221. if (!noPreventDefault) {
  32222. e.stopPropagation();
  32223. e.preventDefault();
  32224. }
  32225. }
  32226. };
  32227. element.addEventListener("mousemove", this._onMouseMove, false);
  32228. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  32229. element.addEventListener("MSGestureChange", this._onGesture, false);
  32230. BABYLON.Tools.RegisterTopRootEvents([
  32231. { name: "blur", handler: this._onLostFocus }
  32232. ]);
  32233. };
  32234. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  32235. BABYLON.Tools.UnregisterTopRootEvents([
  32236. { name: "blur", handler: this._onLostFocus }
  32237. ]);
  32238. if (element && this._observer) {
  32239. this.camera.getScene().onPointerObservable.remove(this._observer);
  32240. this._observer = null;
  32241. element.removeEventListener("contextmenu", this._onContextMenu);
  32242. element.removeEventListener("mousemove", this._onMouseMove);
  32243. element.removeEventListener("MSPointerDown", this._onGestureStart);
  32244. element.removeEventListener("MSGestureChange", this._onGesture);
  32245. this._isPanClick = false;
  32246. this.pinchInwards = true;
  32247. this._onMouseMove = null;
  32248. this._onGestureStart = null;
  32249. this._onGesture = null;
  32250. this._MSGestureHandler = null;
  32251. this._onLostFocus = null;
  32252. this._onContextMenu = null;
  32253. }
  32254. };
  32255. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  32256. return "ArcRotateCameraPointersInput";
  32257. };
  32258. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  32259. return "pointers";
  32260. };
  32261. __decorate([
  32262. BABYLON.serialize()
  32263. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  32264. __decorate([
  32265. BABYLON.serialize()
  32266. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  32267. __decorate([
  32268. BABYLON.serialize()
  32269. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  32270. __decorate([
  32271. BABYLON.serialize()
  32272. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  32273. __decorate([
  32274. BABYLON.serialize()
  32275. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  32276. return ArcRotateCameraPointersInput;
  32277. }());
  32278. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  32279. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  32280. })(BABYLON || (BABYLON = {}));
  32281. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  32282. /// <reference path="babylon.targetCamera.ts" />
  32283. /// <reference path="..\Tools\babylon.tools.ts" />
  32284. var BABYLON;
  32285. (function (BABYLON) {
  32286. var ArcRotateCamera = (function (_super) {
  32287. __extends(ArcRotateCamera, _super);
  32288. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  32289. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  32290. _this.inertialAlphaOffset = 0;
  32291. _this.inertialBetaOffset = 0;
  32292. _this.inertialRadiusOffset = 0;
  32293. _this.lowerAlphaLimit = null;
  32294. _this.upperAlphaLimit = null;
  32295. _this.lowerBetaLimit = 0.01;
  32296. _this.upperBetaLimit = Math.PI;
  32297. _this.lowerRadiusLimit = null;
  32298. _this.upperRadiusLimit = null;
  32299. _this.inertialPanningX = 0;
  32300. _this.inertialPanningY = 0;
  32301. _this.panningInertia = 0.9;
  32302. //-- end properties for backward compatibility for inputs
  32303. _this.zoomOnFactor = 1;
  32304. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  32305. _this.allowUpsideDown = true;
  32306. _this._viewMatrix = new BABYLON.Matrix();
  32307. // Panning
  32308. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  32309. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  32310. _this.checkCollisions = false;
  32311. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32312. _this._previousPosition = BABYLON.Vector3.Zero();
  32313. _this._collisionVelocity = BABYLON.Vector3.Zero();
  32314. _this._newPosition = BABYLON.Vector3.Zero();
  32315. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32316. if (collidedMesh === void 0) { collidedMesh = null; }
  32317. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  32318. newPosition.multiplyInPlace(_this._collider.radius);
  32319. }
  32320. if (!collidedMesh) {
  32321. _this._previousPosition.copyFrom(_this.position);
  32322. }
  32323. else {
  32324. _this.setPosition(newPosition);
  32325. if (_this.onCollide) {
  32326. _this.onCollide(collidedMesh);
  32327. }
  32328. }
  32329. // Recompute because of constraints
  32330. var cosa = Math.cos(_this.alpha);
  32331. var sina = Math.sin(_this.alpha);
  32332. var cosb = Math.cos(_this.beta);
  32333. var sinb = Math.sin(_this.beta);
  32334. if (sinb === 0) {
  32335. sinb = 0.0001;
  32336. }
  32337. var target = _this._getTargetPosition();
  32338. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  32339. _this.position.copyFrom(_this._newPosition);
  32340. var up = _this.upVector;
  32341. if (_this.allowUpsideDown && _this.beta < 0) {
  32342. up = up.clone();
  32343. up = up.negate();
  32344. }
  32345. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  32346. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  32347. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  32348. _this._collisionTriggered = false;
  32349. };
  32350. _this._target = BABYLON.Vector3.Zero();
  32351. if (target) {
  32352. _this.setTarget(target);
  32353. }
  32354. _this.alpha = alpha;
  32355. _this.beta = beta;
  32356. _this.radius = radius;
  32357. _this.getViewMatrix();
  32358. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  32359. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  32360. return _this;
  32361. }
  32362. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  32363. get: function () {
  32364. return this._target;
  32365. },
  32366. set: function (value) {
  32367. this.setTarget(value);
  32368. },
  32369. enumerable: true,
  32370. configurable: true
  32371. });
  32372. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  32373. //-- begin properties for backward compatibility for inputs
  32374. get: function () {
  32375. var pointers = this.inputs.attached["pointers"];
  32376. if (pointers)
  32377. return pointers.angularSensibilityX;
  32378. },
  32379. set: function (value) {
  32380. var pointers = this.inputs.attached["pointers"];
  32381. if (pointers) {
  32382. pointers.angularSensibilityX = value;
  32383. }
  32384. },
  32385. enumerable: true,
  32386. configurable: true
  32387. });
  32388. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  32389. get: function () {
  32390. var pointers = this.inputs.attached["pointers"];
  32391. if (pointers)
  32392. return pointers.angularSensibilityY;
  32393. },
  32394. set: function (value) {
  32395. var pointers = this.inputs.attached["pointers"];
  32396. if (pointers) {
  32397. pointers.angularSensibilityY = value;
  32398. }
  32399. },
  32400. enumerable: true,
  32401. configurable: true
  32402. });
  32403. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  32404. get: function () {
  32405. var pointers = this.inputs.attached["pointers"];
  32406. if (pointers)
  32407. return pointers.pinchPrecision;
  32408. },
  32409. set: function (value) {
  32410. var pointers = this.inputs.attached["pointers"];
  32411. if (pointers) {
  32412. pointers.pinchPrecision = value;
  32413. }
  32414. },
  32415. enumerable: true,
  32416. configurable: true
  32417. });
  32418. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  32419. get: function () {
  32420. var pointers = this.inputs.attached["pointers"];
  32421. if (pointers)
  32422. return pointers.panningSensibility;
  32423. },
  32424. set: function (value) {
  32425. var pointers = this.inputs.attached["pointers"];
  32426. if (pointers) {
  32427. pointers.panningSensibility = value;
  32428. }
  32429. },
  32430. enumerable: true,
  32431. configurable: true
  32432. });
  32433. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  32434. get: function () {
  32435. var keyboard = this.inputs.attached["keyboard"];
  32436. if (keyboard)
  32437. return keyboard.keysUp;
  32438. },
  32439. set: function (value) {
  32440. var keyboard = this.inputs.attached["keyboard"];
  32441. if (keyboard)
  32442. keyboard.keysUp = value;
  32443. },
  32444. enumerable: true,
  32445. configurable: true
  32446. });
  32447. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  32448. get: function () {
  32449. var keyboard = this.inputs.attached["keyboard"];
  32450. if (keyboard)
  32451. return keyboard.keysDown;
  32452. },
  32453. set: function (value) {
  32454. var keyboard = this.inputs.attached["keyboard"];
  32455. if (keyboard)
  32456. keyboard.keysDown = value;
  32457. },
  32458. enumerable: true,
  32459. configurable: true
  32460. });
  32461. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  32462. get: function () {
  32463. var keyboard = this.inputs.attached["keyboard"];
  32464. if (keyboard)
  32465. return keyboard.keysLeft;
  32466. },
  32467. set: function (value) {
  32468. var keyboard = this.inputs.attached["keyboard"];
  32469. if (keyboard)
  32470. keyboard.keysLeft = value;
  32471. },
  32472. enumerable: true,
  32473. configurable: true
  32474. });
  32475. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  32476. get: function () {
  32477. var keyboard = this.inputs.attached["keyboard"];
  32478. if (keyboard)
  32479. return keyboard.keysRight;
  32480. },
  32481. set: function (value) {
  32482. var keyboard = this.inputs.attached["keyboard"];
  32483. if (keyboard)
  32484. keyboard.keysRight = value;
  32485. },
  32486. enumerable: true,
  32487. configurable: true
  32488. });
  32489. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  32490. get: function () {
  32491. var mousewheel = this.inputs.attached["mousewheel"];
  32492. if (mousewheel)
  32493. return mousewheel.wheelPrecision;
  32494. },
  32495. set: function (value) {
  32496. var mousewheel = this.inputs.attached["mousewheel"];
  32497. if (mousewheel)
  32498. mousewheel.wheelPrecision = value;
  32499. },
  32500. enumerable: true,
  32501. configurable: true
  32502. });
  32503. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  32504. get: function () {
  32505. return this._bouncingBehavior;
  32506. },
  32507. enumerable: true,
  32508. configurable: true
  32509. });
  32510. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  32511. get: function () {
  32512. return this._bouncingBehavior != null;
  32513. },
  32514. set: function (value) {
  32515. if (value === this.useBouncingBehavior) {
  32516. return;
  32517. }
  32518. if (value) {
  32519. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  32520. this.addBehavior(this._bouncingBehavior);
  32521. }
  32522. else {
  32523. this.removeBehavior(this._bouncingBehavior);
  32524. this._bouncingBehavior = null;
  32525. }
  32526. },
  32527. enumerable: true,
  32528. configurable: true
  32529. });
  32530. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  32531. get: function () {
  32532. return this._framingBehavior;
  32533. },
  32534. enumerable: true,
  32535. configurable: true
  32536. });
  32537. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  32538. get: function () {
  32539. return this._framingBehavior != null;
  32540. },
  32541. set: function (value) {
  32542. if (value === this.useFramingBehavior) {
  32543. return;
  32544. }
  32545. if (value) {
  32546. this._framingBehavior = new BABYLON.FramingBehavior();
  32547. this.addBehavior(this._framingBehavior);
  32548. }
  32549. else {
  32550. this.removeBehavior(this._framingBehavior);
  32551. this._framingBehavior = null;
  32552. }
  32553. },
  32554. enumerable: true,
  32555. configurable: true
  32556. });
  32557. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  32558. get: function () {
  32559. return this._autoRotationBehavior;
  32560. },
  32561. enumerable: true,
  32562. configurable: true
  32563. });
  32564. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  32565. get: function () {
  32566. return this._autoRotationBehavior != null;
  32567. },
  32568. set: function (value) {
  32569. if (value === this.useAutoRotationBehavior) {
  32570. return;
  32571. }
  32572. if (value) {
  32573. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  32574. this.addBehavior(this._autoRotationBehavior);
  32575. }
  32576. else {
  32577. this.removeBehavior(this._autoRotationBehavior);
  32578. this._autoRotationBehavior = null;
  32579. }
  32580. },
  32581. enumerable: true,
  32582. configurable: true
  32583. });
  32584. // Cache
  32585. ArcRotateCamera.prototype._initCache = function () {
  32586. _super.prototype._initCache.call(this);
  32587. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32588. this._cache.alpha = undefined;
  32589. this._cache.beta = undefined;
  32590. this._cache.radius = undefined;
  32591. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  32592. };
  32593. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  32594. if (!ignoreParentClass) {
  32595. _super.prototype._updateCache.call(this);
  32596. }
  32597. this._cache._target.copyFrom(this._getTargetPosition());
  32598. this._cache.alpha = this.alpha;
  32599. this._cache.beta = this.beta;
  32600. this._cache.radius = this.radius;
  32601. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32602. };
  32603. ArcRotateCamera.prototype._getTargetPosition = function () {
  32604. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32605. var pos = this._targetHost.getAbsolutePosition();
  32606. if (this._targetBoundingCenter) {
  32607. pos.addToRef(this._targetBoundingCenter, this._target);
  32608. }
  32609. else {
  32610. this._target.copyFrom(pos);
  32611. }
  32612. }
  32613. var lockedTargetPosition = this._getLockedTargetPosition();
  32614. if (lockedTargetPosition) {
  32615. return lockedTargetPosition;
  32616. }
  32617. return this._target;
  32618. };
  32619. ArcRotateCamera.prototype.storeState = function () {
  32620. this._storedAlpha = this.alpha;
  32621. this._storedBeta = this.beta;
  32622. this._storedRadius = this.radius;
  32623. this._storedTarget = this._getTargetPosition().clone();
  32624. return _super.prototype.storeState.call(this);
  32625. };
  32626. /**
  32627. * Restored camera state. You must call storeState() first
  32628. */
  32629. ArcRotateCamera.prototype.restoreState = function () {
  32630. if (!_super.prototype.restoreState.call(this)) {
  32631. return false;
  32632. }
  32633. this.alpha = this._storedAlpha;
  32634. this.beta = this._storedBeta;
  32635. this.radius = this._storedRadius;
  32636. this.setTarget(this._storedTarget);
  32637. this.inertialAlphaOffset = 0;
  32638. this.inertialBetaOffset = 0;
  32639. this.inertialRadiusOffset = 0;
  32640. this.inertialPanningX = 0;
  32641. this.inertialPanningY = 0;
  32642. return true;
  32643. };
  32644. // Synchronized
  32645. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32646. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32647. return false;
  32648. return this._cache._target.equals(this._getTargetPosition())
  32649. && this._cache.alpha === this.alpha
  32650. && this._cache.beta === this.beta
  32651. && this._cache.radius === this.radius
  32652. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32653. };
  32654. // Methods
  32655. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32656. var _this = this;
  32657. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32658. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32659. this._useCtrlForPanning = useCtrlForPanning;
  32660. this._panningMouseButton = panningMouseButton;
  32661. this.inputs.attachElement(element, noPreventDefault);
  32662. this._reset = function () {
  32663. _this.inertialAlphaOffset = 0;
  32664. _this.inertialBetaOffset = 0;
  32665. _this.inertialRadiusOffset = 0;
  32666. _this.inertialPanningX = 0;
  32667. _this.inertialPanningY = 0;
  32668. };
  32669. };
  32670. ArcRotateCamera.prototype.detachControl = function (element) {
  32671. this.inputs.detachElement(element);
  32672. if (this._reset) {
  32673. this._reset();
  32674. }
  32675. };
  32676. ArcRotateCamera.prototype._checkInputs = function () {
  32677. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32678. if (this._collisionTriggered) {
  32679. return;
  32680. }
  32681. this.inputs.checkInputs();
  32682. // Inertia
  32683. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32684. if (this.getScene().useRightHandedSystem) {
  32685. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32686. }
  32687. else {
  32688. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32689. }
  32690. this.beta += this.inertialBetaOffset;
  32691. this.radius -= this.inertialRadiusOffset;
  32692. this.inertialAlphaOffset *= this.inertia;
  32693. this.inertialBetaOffset *= this.inertia;
  32694. this.inertialRadiusOffset *= this.inertia;
  32695. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  32696. this.inertialAlphaOffset = 0;
  32697. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  32698. this.inertialBetaOffset = 0;
  32699. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32700. this.inertialRadiusOffset = 0;
  32701. }
  32702. // Panning inertia
  32703. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32704. if (!this._localDirection) {
  32705. this._localDirection = BABYLON.Vector3.Zero();
  32706. this._transformedDirection = BABYLON.Vector3.Zero();
  32707. }
  32708. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32709. this._localDirection.multiplyInPlace(this.panningAxis);
  32710. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32711. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32712. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32713. if (!this.panningAxis.y) {
  32714. this._transformedDirection.y = 0;
  32715. }
  32716. if (!this._targetHost) {
  32717. this._target.addInPlace(this._transformedDirection);
  32718. }
  32719. this.inertialPanningX *= this.panningInertia;
  32720. this.inertialPanningY *= this.panningInertia;
  32721. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32722. this.inertialPanningX = 0;
  32723. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32724. this.inertialPanningY = 0;
  32725. }
  32726. // Limits
  32727. this._checkLimits();
  32728. _super.prototype._checkInputs.call(this);
  32729. };
  32730. ArcRotateCamera.prototype._checkLimits = function () {
  32731. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32732. if (this.allowUpsideDown && this.beta > Math.PI) {
  32733. this.beta = this.beta - (2 * Math.PI);
  32734. }
  32735. }
  32736. else {
  32737. if (this.beta < this.lowerBetaLimit) {
  32738. this.beta = this.lowerBetaLimit;
  32739. }
  32740. }
  32741. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32742. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32743. this.beta = this.beta + (2 * Math.PI);
  32744. }
  32745. }
  32746. else {
  32747. if (this.beta > this.upperBetaLimit) {
  32748. this.beta = this.upperBetaLimit;
  32749. }
  32750. }
  32751. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32752. this.alpha = this.lowerAlphaLimit;
  32753. }
  32754. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32755. this.alpha = this.upperAlphaLimit;
  32756. }
  32757. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32758. this.radius = this.lowerRadiusLimit;
  32759. }
  32760. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32761. this.radius = this.upperRadiusLimit;
  32762. }
  32763. };
  32764. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32765. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32766. this.radius = radiusv3.length();
  32767. if (this.radius === 0) {
  32768. this.radius = 0.0001; // Just to avoid division by zero
  32769. }
  32770. // Alpha
  32771. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32772. if (radiusv3.z < 0) {
  32773. this.alpha = 2 * Math.PI - this.alpha;
  32774. }
  32775. // Beta
  32776. this.beta = Math.acos(radiusv3.y / this.radius);
  32777. this._checkLimits();
  32778. };
  32779. ArcRotateCamera.prototype.setPosition = function (position) {
  32780. if (this.position.equals(position)) {
  32781. return;
  32782. }
  32783. this.position.copyFrom(position);
  32784. this.rebuildAnglesAndRadius();
  32785. };
  32786. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32787. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32788. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32789. if (target.getBoundingInfo) {
  32790. if (toBoundingCenter) {
  32791. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32792. }
  32793. else {
  32794. this._targetBoundingCenter = null;
  32795. }
  32796. this._targetHost = target;
  32797. this._target = this._getTargetPosition();
  32798. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  32799. }
  32800. else {
  32801. var newTarget = target;
  32802. var currentTarget = this._getTargetPosition();
  32803. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32804. return;
  32805. }
  32806. this._targetHost = null;
  32807. this._target = newTarget;
  32808. this._targetBoundingCenter = null;
  32809. this.onMeshTargetChangedObservable.notifyObservers(null);
  32810. }
  32811. this.rebuildAnglesAndRadius();
  32812. };
  32813. ArcRotateCamera.prototype._getViewMatrix = function () {
  32814. // Compute
  32815. var cosa = Math.cos(this.alpha);
  32816. var sina = Math.sin(this.alpha);
  32817. var cosb = Math.cos(this.beta);
  32818. var sinb = Math.sin(this.beta);
  32819. if (sinb === 0) {
  32820. sinb = 0.0001;
  32821. }
  32822. var target = this._getTargetPosition();
  32823. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32824. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32825. if (!this._collider) {
  32826. this._collider = new BABYLON.Collider();
  32827. }
  32828. this._collider.radius = this.collisionRadius;
  32829. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32830. this._collisionTriggered = true;
  32831. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32832. }
  32833. else {
  32834. this.position.copyFrom(this._newPosition);
  32835. var up = this.upVector;
  32836. if (this.allowUpsideDown && sinb < 0) {
  32837. up = up.clone();
  32838. up = up.negate();
  32839. }
  32840. if (this.getScene().useRightHandedSystem) {
  32841. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32842. }
  32843. else {
  32844. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32845. }
  32846. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32847. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32848. }
  32849. this._currentTarget = target;
  32850. return this._viewMatrix;
  32851. };
  32852. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32853. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32854. meshes = meshes || this.getScene().meshes;
  32855. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32856. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32857. this.radius = distance * this.zoomOnFactor;
  32858. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32859. };
  32860. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32861. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32862. var meshesOrMinMaxVector;
  32863. var distance;
  32864. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32865. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32866. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32867. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32868. }
  32869. else {
  32870. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32871. distance = meshesOrMinMaxVectorAndDistance.distance;
  32872. }
  32873. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32874. if (!doNotUpdateMaxZ) {
  32875. this.maxZ = distance * 2;
  32876. }
  32877. };
  32878. /**
  32879. * @override
  32880. * Override Camera.createRigCamera
  32881. */
  32882. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32883. var alphaShift;
  32884. switch (this.cameraRigMode) {
  32885. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32886. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32887. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32888. case BABYLON.Camera.RIG_MODE_VR:
  32889. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32890. break;
  32891. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32892. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32893. break;
  32894. }
  32895. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32896. rigCam._cameraRigParams = {};
  32897. return rigCam;
  32898. };
  32899. /**
  32900. * @override
  32901. * Override Camera._updateRigCameras
  32902. */
  32903. ArcRotateCamera.prototype._updateRigCameras = function () {
  32904. var camLeft = this._rigCameras[0];
  32905. var camRight = this._rigCameras[1];
  32906. camLeft.beta = camRight.beta = this.beta;
  32907. camLeft.radius = camRight.radius = this.radius;
  32908. switch (this.cameraRigMode) {
  32909. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32910. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32911. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32912. case BABYLON.Camera.RIG_MODE_VR:
  32913. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32914. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32915. break;
  32916. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32917. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32918. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32919. break;
  32920. }
  32921. _super.prototype._updateRigCameras.call(this);
  32922. };
  32923. ArcRotateCamera.prototype.dispose = function () {
  32924. this.inputs.clear();
  32925. _super.prototype.dispose.call(this);
  32926. };
  32927. ArcRotateCamera.prototype.getClassName = function () {
  32928. return "ArcRotateCamera";
  32929. };
  32930. __decorate([
  32931. BABYLON.serialize()
  32932. ], ArcRotateCamera.prototype, "alpha", void 0);
  32933. __decorate([
  32934. BABYLON.serialize()
  32935. ], ArcRotateCamera.prototype, "beta", void 0);
  32936. __decorate([
  32937. BABYLON.serialize()
  32938. ], ArcRotateCamera.prototype, "radius", void 0);
  32939. __decorate([
  32940. BABYLON.serializeAsVector3("target")
  32941. ], ArcRotateCamera.prototype, "_target", void 0);
  32942. __decorate([
  32943. BABYLON.serialize()
  32944. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  32945. __decorate([
  32946. BABYLON.serialize()
  32947. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  32948. __decorate([
  32949. BABYLON.serialize()
  32950. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  32951. __decorate([
  32952. BABYLON.serialize()
  32953. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  32954. __decorate([
  32955. BABYLON.serialize()
  32956. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  32957. __decorate([
  32958. BABYLON.serialize()
  32959. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  32960. __decorate([
  32961. BABYLON.serialize()
  32962. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  32963. __decorate([
  32964. BABYLON.serialize()
  32965. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  32966. __decorate([
  32967. BABYLON.serialize()
  32968. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  32969. __decorate([
  32970. BABYLON.serialize()
  32971. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  32972. __decorate([
  32973. BABYLON.serialize()
  32974. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  32975. __decorate([
  32976. BABYLON.serialize()
  32977. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  32978. __decorate([
  32979. BABYLON.serialize()
  32980. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  32981. __decorate([
  32982. BABYLON.serialize()
  32983. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  32984. return ArcRotateCamera;
  32985. }(BABYLON.TargetCamera));
  32986. BABYLON.ArcRotateCamera = ArcRotateCamera;
  32987. })(BABYLON || (BABYLON = {}));
  32988. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  32989. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  32990. var BABYLON;
  32991. (function (BABYLON) {
  32992. var ArcRotateCameraInputsManager = (function (_super) {
  32993. __extends(ArcRotateCameraInputsManager, _super);
  32994. function ArcRotateCameraInputsManager(camera) {
  32995. return _super.call(this, camera) || this;
  32996. }
  32997. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  32998. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  32999. return this;
  33000. };
  33001. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  33002. this.add(new BABYLON.ArcRotateCameraPointersInput());
  33003. return this;
  33004. };
  33005. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  33006. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  33007. return this;
  33008. };
  33009. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  33010. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  33011. return this;
  33012. };
  33013. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  33014. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  33015. return this;
  33016. };
  33017. return ArcRotateCameraInputsManager;
  33018. }(BABYLON.CameraInputsManager));
  33019. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  33020. })(BABYLON || (BABYLON = {}));
  33021. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  33022. var BABYLON;
  33023. (function (BABYLON) {
  33024. var CubeTexture = (function (_super) {
  33025. __extends(CubeTexture, _super);
  33026. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  33027. if (onLoad === void 0) { onLoad = null; }
  33028. if (onError === void 0) { onError = null; }
  33029. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33030. if (prefiltered === void 0) { prefiltered = false; }
  33031. if (forcedExtension === void 0) { forcedExtension = null; }
  33032. var _this = _super.call(this, scene) || this;
  33033. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  33034. _this.name = rootUrl;
  33035. _this.url = rootUrl;
  33036. _this._noMipmap = noMipmap;
  33037. _this.hasAlpha = false;
  33038. _this._format = format;
  33039. _this._prefiltered = prefiltered;
  33040. _this.isCube = true;
  33041. _this._textureMatrix = BABYLON.Matrix.Identity();
  33042. if (prefiltered) {
  33043. _this.gammaSpace = false;
  33044. }
  33045. if (!rootUrl && !files) {
  33046. return _this;
  33047. }
  33048. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  33049. if (!files) {
  33050. if (!extensions) {
  33051. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  33052. }
  33053. files = [];
  33054. for (var index = 0; index < extensions.length; index++) {
  33055. files.push(rootUrl + extensions[index]);
  33056. }
  33057. _this._extensions = extensions;
  33058. }
  33059. _this._files = files;
  33060. if (!_this._texture) {
  33061. if (!scene.useDelayedTextureLoading) {
  33062. if (prefiltered) {
  33063. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  33064. }
  33065. else {
  33066. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  33067. }
  33068. }
  33069. else {
  33070. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33071. }
  33072. }
  33073. else if (onLoad) {
  33074. if (_this._texture.isReady) {
  33075. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  33076. }
  33077. else {
  33078. _this._texture.onLoadedObservable.add(onLoad);
  33079. }
  33080. }
  33081. return _this;
  33082. }
  33083. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  33084. return new CubeTexture("", scene, null, noMipmap, files);
  33085. };
  33086. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  33087. if (forcedExtension === void 0) { forcedExtension = null; }
  33088. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  33089. };
  33090. // Methods
  33091. CubeTexture.prototype.delayLoad = function () {
  33092. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33093. return;
  33094. }
  33095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33096. this._texture = this._getFromCache(this.url, this._noMipmap);
  33097. if (!this._texture) {
  33098. if (this._prefiltered) {
  33099. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  33100. }
  33101. else {
  33102. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  33103. }
  33104. }
  33105. };
  33106. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  33107. return this._textureMatrix;
  33108. };
  33109. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  33110. this._textureMatrix = value;
  33111. };
  33112. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33113. var texture = BABYLON.SerializationHelper.Parse(function () {
  33114. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  33115. }, parsedTexture, scene);
  33116. // Animations
  33117. if (parsedTexture.animations) {
  33118. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  33119. var parsedAnimation = parsedTexture.animations[animationIndex];
  33120. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33121. }
  33122. }
  33123. return texture;
  33124. };
  33125. CubeTexture.prototype.clone = function () {
  33126. var _this = this;
  33127. return BABYLON.SerializationHelper.Clone(function () {
  33128. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  33129. }, this);
  33130. };
  33131. return CubeTexture;
  33132. }(BABYLON.BaseTexture));
  33133. BABYLON.CubeTexture = CubeTexture;
  33134. })(BABYLON || (BABYLON = {}));
  33135. //# sourceMappingURL=babylon.cubeTexture.js.map
  33136. var BABYLON;
  33137. (function (BABYLON) {
  33138. var RenderTargetTexture = (function (_super) {
  33139. __extends(RenderTargetTexture, _super);
  33140. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  33141. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  33142. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33143. if (isCube === void 0) { isCube = false; }
  33144. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33145. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33146. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  33147. if (isMulti === void 0) { isMulti = false; }
  33148. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  33149. _this.isCube = isCube;
  33150. /**
  33151. * Use this list to define the list of mesh you want to render.
  33152. */
  33153. _this.renderList = new Array();
  33154. _this.renderParticles = true;
  33155. _this.renderSprites = false;
  33156. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  33157. _this.ignoreCameraViewport = false;
  33158. // Events
  33159. /**
  33160. * An event triggered when the texture is unbind.
  33161. * @type {BABYLON.Observable}
  33162. */
  33163. _this.onBeforeBindObservable = new BABYLON.Observable();
  33164. /**
  33165. * An event triggered when the texture is unbind.
  33166. * @type {BABYLON.Observable}
  33167. */
  33168. _this.onAfterUnbindObservable = new BABYLON.Observable();
  33169. /**
  33170. * An event triggered before rendering the texture
  33171. * @type {BABYLON.Observable}
  33172. */
  33173. _this.onBeforeRenderObservable = new BABYLON.Observable();
  33174. /**
  33175. * An event triggered after rendering the texture
  33176. * @type {BABYLON.Observable}
  33177. */
  33178. _this.onAfterRenderObservable = new BABYLON.Observable();
  33179. /**
  33180. * An event triggered after the texture clear
  33181. * @type {BABYLON.Observable}
  33182. */
  33183. _this.onClearObservable = new BABYLON.Observable();
  33184. _this._currentRefreshId = -1;
  33185. _this._refreshRate = 1;
  33186. _this._samples = 1;
  33187. scene = _this.getScene();
  33188. _this.name = name;
  33189. _this.isRenderTarget = true;
  33190. _this._size = size;
  33191. _this._generateMipMaps = generateMipMaps;
  33192. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  33193. // Rendering groups
  33194. _this._renderingManager = new BABYLON.RenderingManager(scene);
  33195. if (isMulti) {
  33196. return _this;
  33197. }
  33198. _this._renderTargetOptions = {
  33199. generateMipMaps: generateMipMaps,
  33200. type: type,
  33201. samplingMode: samplingMode,
  33202. generateDepthBuffer: generateDepthBuffer,
  33203. generateStencilBuffer: generateStencilBuffer
  33204. };
  33205. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  33206. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33207. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33208. }
  33209. if (isCube) {
  33210. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  33211. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  33212. _this._textureMatrix = BABYLON.Matrix.Identity();
  33213. }
  33214. else {
  33215. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  33216. }
  33217. return _this;
  33218. }
  33219. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  33220. get: function () {
  33221. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  33222. },
  33223. enumerable: true,
  33224. configurable: true
  33225. });
  33226. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  33227. get: function () {
  33228. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  33229. },
  33230. enumerable: true,
  33231. configurable: true
  33232. });
  33233. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  33234. get: function () {
  33235. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  33236. },
  33237. enumerable: true,
  33238. configurable: true
  33239. });
  33240. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  33241. set: function (callback) {
  33242. if (this._onAfterUnbindObserver) {
  33243. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  33244. }
  33245. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  33246. },
  33247. enumerable: true,
  33248. configurable: true
  33249. });
  33250. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  33251. set: function (callback) {
  33252. if (this._onBeforeRenderObserver) {
  33253. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  33254. }
  33255. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  33256. },
  33257. enumerable: true,
  33258. configurable: true
  33259. });
  33260. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  33261. set: function (callback) {
  33262. if (this._onAfterRenderObserver) {
  33263. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  33264. }
  33265. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  33266. },
  33267. enumerable: true,
  33268. configurable: true
  33269. });
  33270. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  33271. set: function (callback) {
  33272. if (this._onClearObserver) {
  33273. this.onClearObservable.remove(this._onClearObserver);
  33274. }
  33275. this._onClearObserver = this.onClearObservable.add(callback);
  33276. },
  33277. enumerable: true,
  33278. configurable: true
  33279. });
  33280. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  33281. get: function () {
  33282. return this._renderTargetOptions;
  33283. },
  33284. enumerable: true,
  33285. configurable: true
  33286. });
  33287. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  33288. get: function () {
  33289. return this._samples;
  33290. },
  33291. set: function (value) {
  33292. if (this._samples === value) {
  33293. return;
  33294. }
  33295. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  33296. },
  33297. enumerable: true,
  33298. configurable: true
  33299. });
  33300. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  33301. this._currentRefreshId = -1;
  33302. };
  33303. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  33304. get: function () {
  33305. return this._refreshRate;
  33306. },
  33307. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  33308. set: function (value) {
  33309. this._refreshRate = value;
  33310. this.resetRefreshCounter();
  33311. },
  33312. enumerable: true,
  33313. configurable: true
  33314. });
  33315. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  33316. if (!this._postProcessManager) {
  33317. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  33318. this._postProcesses = new Array();
  33319. }
  33320. this._postProcesses.push(postProcess);
  33321. this._postProcesses[0].autoClear = false;
  33322. };
  33323. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  33324. if (!this._postProcesses) {
  33325. return;
  33326. }
  33327. if (dispose) {
  33328. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  33329. var postProcess = _a[_i];
  33330. postProcess.dispose();
  33331. postProcess = null;
  33332. }
  33333. }
  33334. this._postProcesses = [];
  33335. };
  33336. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  33337. if (!this._postProcesses) {
  33338. return;
  33339. }
  33340. var index = this._postProcesses.indexOf(postProcess);
  33341. if (index === -1) {
  33342. return;
  33343. }
  33344. this._postProcesses.splice(index, 1);
  33345. if (this._postProcesses.length > 0) {
  33346. this._postProcesses[0].autoClear = false;
  33347. }
  33348. };
  33349. RenderTargetTexture.prototype._shouldRender = function () {
  33350. if (this._currentRefreshId === -1) {
  33351. this._currentRefreshId = 1;
  33352. return true;
  33353. }
  33354. if (this.refreshRate === this._currentRefreshId) {
  33355. this._currentRefreshId = 1;
  33356. return true;
  33357. }
  33358. this._currentRefreshId++;
  33359. return false;
  33360. };
  33361. RenderTargetTexture.prototype.getRenderSize = function () {
  33362. return this._size;
  33363. };
  33364. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  33365. get: function () {
  33366. return true;
  33367. },
  33368. enumerable: true,
  33369. configurable: true
  33370. });
  33371. RenderTargetTexture.prototype.scale = function (ratio) {
  33372. var newSize = this._size * ratio;
  33373. this.resize(newSize);
  33374. };
  33375. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  33376. if (this.isCube) {
  33377. return this._textureMatrix;
  33378. }
  33379. return _super.prototype.getReflectionTextureMatrix.call(this);
  33380. };
  33381. RenderTargetTexture.prototype.resize = function (size) {
  33382. this.releaseInternalTexture();
  33383. if (this.isCube) {
  33384. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  33385. }
  33386. else {
  33387. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  33388. }
  33389. };
  33390. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  33391. var scene = this.getScene();
  33392. var engine = scene.getEngine();
  33393. if (this.useCameraPostProcesses !== undefined) {
  33394. useCameraPostProcess = this.useCameraPostProcesses;
  33395. }
  33396. if (this._waitingRenderList) {
  33397. this.renderList = [];
  33398. for (var index = 0; index < this._waitingRenderList.length; index++) {
  33399. var id = this._waitingRenderList[index];
  33400. this.renderList.push(scene.getMeshByID(id));
  33401. }
  33402. delete this._waitingRenderList;
  33403. }
  33404. // Is predicate defined?
  33405. if (this.renderListPredicate) {
  33406. this.renderList.splice(0); // Clear previous renderList
  33407. var sceneMeshes = this.getScene().meshes;
  33408. for (var index = 0; index < sceneMeshes.length; index++) {
  33409. var mesh = sceneMeshes[index];
  33410. if (this.renderListPredicate(mesh)) {
  33411. this.renderList.push(mesh);
  33412. }
  33413. }
  33414. }
  33415. if (this.renderList && this.renderList.length === 0) {
  33416. return;
  33417. }
  33418. this.onBeforeBindObservable.notifyObservers(this);
  33419. // Set custom projection.
  33420. // Needs to be before binding to prevent changing the aspect ratio.
  33421. var camera;
  33422. if (this.activeCamera) {
  33423. camera = this.activeCamera;
  33424. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  33425. if (this.activeCamera !== scene.activeCamera) {
  33426. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  33427. }
  33428. }
  33429. else {
  33430. camera = scene.activeCamera;
  33431. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  33432. }
  33433. // Prepare renderingManager
  33434. this._renderingManager.reset();
  33435. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  33436. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  33437. var sceneRenderId = scene.getRenderId();
  33438. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  33439. var mesh = currentRenderList[meshIndex];
  33440. if (mesh) {
  33441. if (!mesh.isReady()) {
  33442. // Reset _currentRefreshId
  33443. this.resetRefreshCounter();
  33444. continue;
  33445. }
  33446. mesh._preActivateForIntermediateRendering(sceneRenderId);
  33447. var isMasked = void 0;
  33448. if (!this.renderList) {
  33449. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  33450. }
  33451. else {
  33452. isMasked = false;
  33453. }
  33454. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  33455. mesh._activate(sceneRenderId);
  33456. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33457. var subMesh = mesh.subMeshes[subIndex];
  33458. scene._activeIndices.addCount(subMesh.indexCount, false);
  33459. this._renderingManager.dispatch(subMesh);
  33460. }
  33461. }
  33462. }
  33463. }
  33464. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  33465. var particleSystem = scene.particleSystems[particleIndex];
  33466. var emitter = particleSystem.emitter;
  33467. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  33468. continue;
  33469. }
  33470. if (currentRenderList.indexOf(emitter) >= 0) {
  33471. this._renderingManager.dispatchParticles(particleSystem);
  33472. }
  33473. }
  33474. if (this.isCube) {
  33475. for (var face = 0; face < 6; face++) {
  33476. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33477. scene.incrementRenderId();
  33478. scene.resetCachedMaterial();
  33479. }
  33480. }
  33481. else {
  33482. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33483. }
  33484. this.onAfterUnbindObservable.notifyObservers(this);
  33485. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  33486. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  33487. }
  33488. engine.setViewport(scene.activeCamera.viewport);
  33489. scene.resetCachedMaterial();
  33490. };
  33491. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  33492. var _this = this;
  33493. var scene = this.getScene();
  33494. var engine = scene.getEngine();
  33495. // Bind
  33496. if (this._postProcessManager) {
  33497. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  33498. }
  33499. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  33500. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  33501. }
  33502. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  33503. // Clear
  33504. if (this.onClearObservable.hasObservers()) {
  33505. this.onClearObservable.notifyObservers(engine);
  33506. }
  33507. else {
  33508. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  33509. }
  33510. if (!this._doNotChangeAspectRatio) {
  33511. scene.updateTransformMatrix(true);
  33512. }
  33513. // Render
  33514. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  33515. if (this._postProcessManager) {
  33516. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  33517. }
  33518. else if (useCameraPostProcess) {
  33519. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  33520. }
  33521. if (!this._doNotChangeAspectRatio) {
  33522. scene.updateTransformMatrix(true);
  33523. }
  33524. // Dump ?
  33525. if (dumpForDebug) {
  33526. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  33527. }
  33528. // Unbind
  33529. if (!this.isCube || faceIndex === 5) {
  33530. if (this.isCube) {
  33531. if (faceIndex === 5) {
  33532. engine.generateMipMapsForCubemap(this._texture);
  33533. }
  33534. }
  33535. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  33536. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  33537. });
  33538. }
  33539. else {
  33540. this.onAfterRenderObservable.notifyObservers(faceIndex);
  33541. }
  33542. };
  33543. /**
  33544. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  33545. * This allowed control for front to back rendering or reversly depending of the special needs.
  33546. *
  33547. * @param renderingGroupId The rendering group id corresponding to its index
  33548. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  33549. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  33550. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  33551. */
  33552. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  33553. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  33554. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  33555. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  33556. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  33557. };
  33558. /**
  33559. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  33560. *
  33561. * @param renderingGroupId The rendering group id corresponding to its index
  33562. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  33563. */
  33564. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  33565. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  33566. };
  33567. RenderTargetTexture.prototype.clone = function () {
  33568. var textureSize = this.getSize();
  33569. 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);
  33570. // Base texture
  33571. newTexture.hasAlpha = this.hasAlpha;
  33572. newTexture.level = this.level;
  33573. // RenderTarget Texture
  33574. newTexture.coordinatesMode = this.coordinatesMode;
  33575. newTexture.renderList = this.renderList.slice(0);
  33576. return newTexture;
  33577. };
  33578. RenderTargetTexture.prototype.serialize = function () {
  33579. if (!this.name) {
  33580. return null;
  33581. }
  33582. var serializationObject = _super.prototype.serialize.call(this);
  33583. serializationObject.renderTargetSize = this.getRenderSize();
  33584. serializationObject.renderList = [];
  33585. for (var index = 0; index < this.renderList.length; index++) {
  33586. serializationObject.renderList.push(this.renderList[index].id);
  33587. }
  33588. return serializationObject;
  33589. };
  33590. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  33591. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  33592. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  33593. };
  33594. RenderTargetTexture.prototype.dispose = function () {
  33595. if (this._postProcessManager) {
  33596. this._postProcessManager.dispose();
  33597. this._postProcessManager = null;
  33598. }
  33599. this.clearPostProcesses(true);
  33600. this.renderList = null;
  33601. // Remove from custom render targets
  33602. var scene = this.getScene();
  33603. var index = scene.customRenderTargets.indexOf(this);
  33604. if (index >= 0) {
  33605. scene.customRenderTargets.splice(index, 1);
  33606. }
  33607. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  33608. var camera = _a[_i];
  33609. index = camera.customRenderTargets.indexOf(this);
  33610. if (index >= 0) {
  33611. camera.customRenderTargets.splice(index, 1);
  33612. }
  33613. }
  33614. _super.prototype.dispose.call(this);
  33615. };
  33616. RenderTargetTexture.prototype._rebuild = function () {
  33617. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  33618. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  33619. }
  33620. if (this._postProcessManager) {
  33621. this._postProcessManager._rebuild();
  33622. }
  33623. };
  33624. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  33625. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  33626. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  33627. return RenderTargetTexture;
  33628. }(BABYLON.Texture));
  33629. BABYLON.RenderTargetTexture = RenderTargetTexture;
  33630. })(BABYLON || (BABYLON = {}));
  33631. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  33632. var BABYLON;
  33633. (function (BABYLON) {
  33634. ;
  33635. var MultiRenderTarget = (function (_super) {
  33636. __extends(MultiRenderTarget, _super);
  33637. function MultiRenderTarget(name, size, count, scene, options) {
  33638. var _this = this;
  33639. options = options || {};
  33640. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  33641. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  33642. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  33643. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  33644. if (!_this.isSupported) {
  33645. _this.dispose();
  33646. return;
  33647. }
  33648. var types = [];
  33649. var samplingModes = [];
  33650. for (var i = 0; i < count; i++) {
  33651. if (options.types && options.types[i]) {
  33652. types.push(options.types[i]);
  33653. }
  33654. else {
  33655. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  33656. }
  33657. if (options.samplingModes && options.samplingModes[i]) {
  33658. samplingModes.push(options.samplingModes[i]);
  33659. }
  33660. else {
  33661. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33662. }
  33663. }
  33664. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  33665. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  33666. _this._count = count;
  33667. _this._size = size;
  33668. _this._multiRenderTargetOptions = {
  33669. samplingModes: samplingModes,
  33670. generateMipMaps: generateMipMaps,
  33671. generateDepthBuffer: generateDepthBuffer,
  33672. generateStencilBuffer: generateStencilBuffer,
  33673. generateDepthTexture: generateDepthTexture,
  33674. types: types,
  33675. textureCount: count
  33676. };
  33677. _this._createInternalTextures();
  33678. _this._createTextures();
  33679. return _this;
  33680. }
  33681. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  33682. get: function () {
  33683. var engine = this.getScene().getEngine();
  33684. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  33685. },
  33686. enumerable: true,
  33687. configurable: true
  33688. });
  33689. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  33690. get: function () {
  33691. return this._textures;
  33692. },
  33693. enumerable: true,
  33694. configurable: true
  33695. });
  33696. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  33697. get: function () {
  33698. return this._textures[this._textures.length - 1];
  33699. },
  33700. enumerable: true,
  33701. configurable: true
  33702. });
  33703. MultiRenderTarget.prototype._rebuild = function () {
  33704. this.releaseInternalTextures();
  33705. this._createInternalTextures();
  33706. for (var i = 0; i < this._internalTextures.length; i++) {
  33707. var texture = this._textures[i];
  33708. texture._texture = this._internalTextures[i];
  33709. }
  33710. // Keeps references to frame buffer and stencil/depth buffer
  33711. this._texture = this._internalTextures[0];
  33712. };
  33713. MultiRenderTarget.prototype._createInternalTextures = function () {
  33714. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  33715. };
  33716. MultiRenderTarget.prototype._createTextures = function () {
  33717. this._textures = [];
  33718. for (var i = 0; i < this._internalTextures.length; i++) {
  33719. var texture = new BABYLON.Texture(null, this.getScene());
  33720. texture._texture = this._internalTextures[i];
  33721. this._textures.push(texture);
  33722. }
  33723. // Keeps references to frame buffer and stencil/depth buffer
  33724. this._texture = this._internalTextures[0];
  33725. };
  33726. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  33727. get: function () {
  33728. return this._samples;
  33729. },
  33730. set: function (value) {
  33731. if (this._samples === value) {
  33732. return;
  33733. }
  33734. for (var i = 0; i < this._internalTextures.length; i++) {
  33735. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  33736. }
  33737. },
  33738. enumerable: true,
  33739. configurable: true
  33740. });
  33741. MultiRenderTarget.prototype.resize = function (size) {
  33742. this.releaseInternalTextures();
  33743. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  33744. this._createInternalTextures();
  33745. };
  33746. MultiRenderTarget.prototype.dispose = function () {
  33747. this.releaseInternalTextures();
  33748. _super.prototype.dispose.call(this);
  33749. };
  33750. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  33751. if (!this._internalTextures) {
  33752. return;
  33753. }
  33754. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  33755. if (this._internalTextures[i] !== undefined) {
  33756. this._internalTextures[i].dispose();
  33757. this._internalTextures.splice(i, 1);
  33758. }
  33759. }
  33760. };
  33761. return MultiRenderTarget;
  33762. }(BABYLON.RenderTargetTexture));
  33763. BABYLON.MultiRenderTarget = MultiRenderTarget;
  33764. })(BABYLON || (BABYLON = {}));
  33765. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  33766. /// <reference path="babylon.renderTargetTexture.ts" />
  33767. var BABYLON;
  33768. (function (BABYLON) {
  33769. var MirrorTexture = (function (_super) {
  33770. __extends(MirrorTexture, _super);
  33771. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  33772. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33773. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33774. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33775. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  33776. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  33777. _this._transformMatrix = BABYLON.Matrix.Zero();
  33778. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  33779. _this._blurKernelX = 0;
  33780. _this._blurKernelY = 0;
  33781. _this._blurRatio = 1.0;
  33782. _this.onBeforeRenderObservable.add(function () {
  33783. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  33784. _this._savedViewMatrix = scene.getViewMatrix();
  33785. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  33786. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  33787. scene.clipPlane = _this.mirrorPlane;
  33788. scene.getEngine().cullBackFaces = false;
  33789. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  33790. });
  33791. _this.onAfterRenderObservable.add(function () {
  33792. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  33793. scene.getEngine().cullBackFaces = true;
  33794. scene._mirroredCameraPosition = null;
  33795. delete scene.clipPlane;
  33796. });
  33797. return _this;
  33798. }
  33799. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  33800. get: function () {
  33801. return this._blurRatio;
  33802. },
  33803. set: function (value) {
  33804. if (this._blurRatio === value) {
  33805. return;
  33806. }
  33807. this._blurRatio = value;
  33808. this._preparePostProcesses();
  33809. },
  33810. enumerable: true,
  33811. configurable: true
  33812. });
  33813. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  33814. set: function (value) {
  33815. this.blurKernelX = value;
  33816. this.blurKernelY = value;
  33817. },
  33818. enumerable: true,
  33819. configurable: true
  33820. });
  33821. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  33822. get: function () {
  33823. return this._blurKernelX;
  33824. },
  33825. set: function (value) {
  33826. if (this._blurKernelX === value) {
  33827. return;
  33828. }
  33829. this._blurKernelX = value;
  33830. this._preparePostProcesses();
  33831. },
  33832. enumerable: true,
  33833. configurable: true
  33834. });
  33835. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  33836. get: function () {
  33837. return this._blurKernelY;
  33838. },
  33839. set: function (value) {
  33840. if (this._blurKernelY === value) {
  33841. return;
  33842. }
  33843. this._blurKernelY = value;
  33844. this._preparePostProcesses();
  33845. },
  33846. enumerable: true,
  33847. configurable: true
  33848. });
  33849. MirrorTexture.prototype._preparePostProcesses = function () {
  33850. this.clearPostProcesses(true);
  33851. if (this._blurKernelX && this._blurKernelY) {
  33852. var engine = this.getScene().getEngine();
  33853. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33854. 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);
  33855. this._blurX.autoClear = false;
  33856. if (this._blurRatio === 1 && this.samples < 2) {
  33857. this._blurX.outputTexture = this._texture;
  33858. }
  33859. else {
  33860. this._blurX.alwaysForcePOT = true;
  33861. }
  33862. 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);
  33863. this._blurY.autoClear = false;
  33864. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  33865. this.addPostProcess(this._blurX);
  33866. this.addPostProcess(this._blurY);
  33867. }
  33868. };
  33869. MirrorTexture.prototype.clone = function () {
  33870. var textureSize = this.getSize();
  33871. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  33872. // Base texture
  33873. newTexture.hasAlpha = this.hasAlpha;
  33874. newTexture.level = this.level;
  33875. // Mirror Texture
  33876. newTexture.mirrorPlane = this.mirrorPlane.clone();
  33877. newTexture.renderList = this.renderList.slice(0);
  33878. return newTexture;
  33879. };
  33880. MirrorTexture.prototype.serialize = function () {
  33881. if (!this.name) {
  33882. return null;
  33883. }
  33884. var serializationObject = _super.prototype.serialize.call(this);
  33885. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  33886. return serializationObject;
  33887. };
  33888. return MirrorTexture;
  33889. }(BABYLON.RenderTargetTexture));
  33890. BABYLON.MirrorTexture = MirrorTexture;
  33891. })(BABYLON || (BABYLON = {}));
  33892. //# sourceMappingURL=babylon.mirrorTexture.js.map
  33893. /// <reference path="babylon.renderTargetTexture.ts" />
  33894. var BABYLON;
  33895. (function (BABYLON) {
  33896. /**
  33897. * Creates a refraction texture used by refraction channel of the standard material.
  33898. * @param name the texture name
  33899. * @param size size of the underlying texture
  33900. * @param scene root scene
  33901. */
  33902. var RefractionTexture = (function (_super) {
  33903. __extends(RefractionTexture, _super);
  33904. function RefractionTexture(name, size, scene, generateMipMaps) {
  33905. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  33906. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  33907. _this.depth = 2.0;
  33908. _this.onBeforeRenderObservable.add(function () {
  33909. scene.clipPlane = _this.refractionPlane;
  33910. });
  33911. _this.onAfterRenderObservable.add(function () {
  33912. delete scene.clipPlane;
  33913. });
  33914. return _this;
  33915. }
  33916. RefractionTexture.prototype.clone = function () {
  33917. var textureSize = this.getSize();
  33918. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  33919. // Base texture
  33920. newTexture.hasAlpha = this.hasAlpha;
  33921. newTexture.level = this.level;
  33922. // Refraction Texture
  33923. newTexture.refractionPlane = this.refractionPlane.clone();
  33924. newTexture.renderList = this.renderList.slice(0);
  33925. newTexture.depth = this.depth;
  33926. return newTexture;
  33927. };
  33928. RefractionTexture.prototype.serialize = function () {
  33929. if (!this.name) {
  33930. return null;
  33931. }
  33932. var serializationObject = _super.prototype.serialize.call(this);
  33933. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  33934. serializationObject.depth = this.depth;
  33935. return serializationObject;
  33936. };
  33937. return RefractionTexture;
  33938. }(BABYLON.RenderTargetTexture));
  33939. BABYLON.RefractionTexture = RefractionTexture;
  33940. })(BABYLON || (BABYLON = {}));
  33941. //# sourceMappingURL=babylon.refractionTexture.js.map
  33942. /// <reference path="babylon.texture.ts" />
  33943. var BABYLON;
  33944. (function (BABYLON) {
  33945. var DynamicTexture = (function (_super) {
  33946. __extends(DynamicTexture, _super);
  33947. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  33948. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33949. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33950. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  33951. _this.name = name;
  33952. var engine = _this.getScene().getEngine();
  33953. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33954. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33955. _this._generateMipMaps = generateMipMaps;
  33956. if (options.getContext) {
  33957. _this._canvas = options;
  33958. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33959. }
  33960. else {
  33961. _this._canvas = document.createElement("canvas");
  33962. if (options.width) {
  33963. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33964. }
  33965. else {
  33966. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  33967. }
  33968. }
  33969. var textureSize = _this.getSize();
  33970. _this._canvas.width = textureSize.width;
  33971. _this._canvas.height = textureSize.height;
  33972. _this._context = _this._canvas.getContext("2d");
  33973. return _this;
  33974. }
  33975. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  33976. get: function () {
  33977. return true;
  33978. },
  33979. enumerable: true,
  33980. configurable: true
  33981. });
  33982. DynamicTexture.prototype._recreate = function (textureSize) {
  33983. this._canvas.width = textureSize.width;
  33984. this._canvas.height = textureSize.height;
  33985. this.releaseInternalTexture();
  33986. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  33987. };
  33988. DynamicTexture.prototype.scale = function (ratio) {
  33989. var textureSize = this.getSize();
  33990. textureSize.width *= ratio;
  33991. textureSize.height *= ratio;
  33992. this._recreate(textureSize);
  33993. };
  33994. DynamicTexture.prototype.scaleTo = function (width, height) {
  33995. var textureSize = this.getSize();
  33996. textureSize.width = width;
  33997. textureSize.height = height;
  33998. this._recreate(textureSize);
  33999. };
  34000. DynamicTexture.prototype.getContext = function () {
  34001. return this._context;
  34002. };
  34003. DynamicTexture.prototype.clear = function () {
  34004. var size = this.getSize();
  34005. this._context.fillRect(0, 0, size.width, size.height);
  34006. };
  34007. DynamicTexture.prototype.update = function (invertY) {
  34008. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  34009. };
  34010. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  34011. if (update === void 0) { update = true; }
  34012. var size = this.getSize();
  34013. if (clearColor) {
  34014. this._context.fillStyle = clearColor;
  34015. this._context.fillRect(0, 0, size.width, size.height);
  34016. }
  34017. this._context.font = font;
  34018. if (x === null || x === undefined) {
  34019. var textSize = this._context.measureText(text);
  34020. x = (size.width - textSize.width) / 2;
  34021. }
  34022. if (y === null || y === undefined) {
  34023. var fontSize = parseInt((font.replace(/\D/g, '')));
  34024. ;
  34025. y = (size.height / 2) + (fontSize / 3.65);
  34026. }
  34027. this._context.fillStyle = color;
  34028. this._context.fillText(text, x, y);
  34029. if (update) {
  34030. this.update(invertY);
  34031. }
  34032. };
  34033. DynamicTexture.prototype.clone = function () {
  34034. var textureSize = this.getSize();
  34035. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  34036. // Base texture
  34037. newTexture.hasAlpha = this.hasAlpha;
  34038. newTexture.level = this.level;
  34039. // Dynamic Texture
  34040. newTexture.wrapU = this.wrapU;
  34041. newTexture.wrapV = this.wrapV;
  34042. return newTexture;
  34043. };
  34044. DynamicTexture.prototype._rebuild = function () {
  34045. this.update();
  34046. };
  34047. return DynamicTexture;
  34048. }(BABYLON.Texture));
  34049. BABYLON.DynamicTexture = DynamicTexture;
  34050. })(BABYLON || (BABYLON = {}));
  34051. //# sourceMappingURL=babylon.dynamicTexture.js.map
  34052. var BABYLON;
  34053. (function (BABYLON) {
  34054. var VideoTexture = (function (_super) {
  34055. __extends(VideoTexture, _super);
  34056. /**
  34057. * Creates a video texture.
  34058. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  34059. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  34060. * @param {BABYLON.Scene} scene is obviously the current scene.
  34061. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  34062. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  34063. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  34064. */
  34065. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  34066. if (generateMipMaps === void 0) { generateMipMaps = false; }
  34067. if (invertY === void 0) { invertY = false; }
  34068. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34069. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  34070. _this._autoLaunch = true;
  34071. var urls;
  34072. _this.name = name;
  34073. if (urlsOrVideo instanceof HTMLVideoElement) {
  34074. _this.video = urlsOrVideo;
  34075. }
  34076. else {
  34077. urls = urlsOrVideo;
  34078. _this.video = document.createElement("video");
  34079. _this.video.autoplay = false;
  34080. _this.video.loop = true;
  34081. }
  34082. _this._generateMipMaps = generateMipMaps;
  34083. _this._samplingMode = samplingMode;
  34084. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  34085. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34086. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34087. }
  34088. else {
  34089. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34090. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34091. _this._generateMipMaps = false;
  34092. }
  34093. if (urls) {
  34094. _this.video.addEventListener("canplay", function () {
  34095. _this._createTexture();
  34096. });
  34097. urls.forEach(function (url) {
  34098. var source = document.createElement("source");
  34099. source.src = url;
  34100. _this.video.appendChild(source);
  34101. });
  34102. }
  34103. else {
  34104. _this._createTexture();
  34105. }
  34106. _this._lastUpdate = BABYLON.Tools.Now;
  34107. return _this;
  34108. }
  34109. VideoTexture.prototype.__setTextureReady = function () {
  34110. this._texture.isReady = true;
  34111. };
  34112. VideoTexture.prototype._createTexture = function () {
  34113. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  34114. if (this._autoLaunch) {
  34115. this._autoLaunch = false;
  34116. this.video.play();
  34117. }
  34118. this._setTextureReady = this.__setTextureReady.bind(this);
  34119. this.video.addEventListener("playing", this._setTextureReady);
  34120. };
  34121. VideoTexture.prototype._rebuild = function () {
  34122. this.update();
  34123. };
  34124. VideoTexture.prototype.update = function () {
  34125. var now = BABYLON.Tools.Now;
  34126. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  34127. return false;
  34128. }
  34129. this._lastUpdate = now;
  34130. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  34131. return true;
  34132. };
  34133. VideoTexture.prototype.dispose = function () {
  34134. _super.prototype.dispose.call(this);
  34135. this.video.removeEventListener("playing", this._setTextureReady);
  34136. };
  34137. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  34138. var video = document.createElement("video");
  34139. var constraintsDeviceId;
  34140. if (constraints && constraints.deviceId) {
  34141. constraintsDeviceId = {
  34142. exact: constraints.deviceId
  34143. };
  34144. }
  34145. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  34146. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  34147. if (navigator.getUserMedia) {
  34148. navigator.getUserMedia({
  34149. video: {
  34150. deviceId: constraintsDeviceId,
  34151. width: {
  34152. min: (constraints && constraints.minWidth) || 256,
  34153. max: (constraints && constraints.maxWidth) || 640
  34154. },
  34155. height: {
  34156. min: (constraints && constraints.minHeight) || 256,
  34157. max: (constraints && constraints.maxHeight) || 480
  34158. }
  34159. }
  34160. }, function (stream) {
  34161. if (video.mozSrcObject !== undefined) {
  34162. video.mozSrcObject = stream;
  34163. }
  34164. else {
  34165. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  34166. }
  34167. video.play();
  34168. if (onReady) {
  34169. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  34170. }
  34171. }, function (e) {
  34172. BABYLON.Tools.Error(e.name);
  34173. });
  34174. }
  34175. };
  34176. return VideoTexture;
  34177. }(BABYLON.Texture));
  34178. BABYLON.VideoTexture = VideoTexture;
  34179. })(BABYLON || (BABYLON = {}));
  34180. //# sourceMappingURL=babylon.videoTexture.js.map
  34181. var BABYLON;
  34182. (function (BABYLON) {
  34183. var RawTexture = (function (_super) {
  34184. __extends(RawTexture, _super);
  34185. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  34186. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34187. if (invertY === void 0) { invertY = false; }
  34188. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34189. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  34190. _this.format = format;
  34191. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  34192. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34193. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34194. return _this;
  34195. }
  34196. RawTexture.prototype.update = function (data) {
  34197. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  34198. };
  34199. // Statics
  34200. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34201. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34202. if (invertY === void 0) { invertY = false; }
  34203. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34204. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  34205. };
  34206. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34207. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34208. if (invertY === void 0) { invertY = false; }
  34209. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34210. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34211. };
  34212. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34213. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34214. if (invertY === void 0) { invertY = false; }
  34215. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34216. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34217. };
  34218. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34219. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34220. if (invertY === void 0) { invertY = false; }
  34221. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34222. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  34223. };
  34224. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34225. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34226. if (invertY === void 0) { invertY = false; }
  34227. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34228. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  34229. };
  34230. return RawTexture;
  34231. }(BABYLON.Texture));
  34232. BABYLON.RawTexture = RawTexture;
  34233. })(BABYLON || (BABYLON = {}));
  34234. //# sourceMappingURL=babylon.rawTexture.js.map
  34235. var BABYLON;
  34236. (function (BABYLON) {
  34237. var Internals;
  34238. (function (Internals) {
  34239. /*
  34240. * Based on jsTGALoader - Javascript loader for TGA file
  34241. * By Vincent Thibault
  34242. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  34243. */
  34244. var TGATools = (function () {
  34245. function TGATools() {
  34246. }
  34247. TGATools.GetTGAHeader = function (data) {
  34248. var offset = 0;
  34249. var header = {
  34250. id_length: data[offset++],
  34251. colormap_type: data[offset++],
  34252. image_type: data[offset++],
  34253. colormap_index: data[offset++] | data[offset++] << 8,
  34254. colormap_length: data[offset++] | data[offset++] << 8,
  34255. colormap_size: data[offset++],
  34256. origin: [
  34257. data[offset++] | data[offset++] << 8,
  34258. data[offset++] | data[offset++] << 8
  34259. ],
  34260. width: data[offset++] | data[offset++] << 8,
  34261. height: data[offset++] | data[offset++] << 8,
  34262. pixel_size: data[offset++],
  34263. flags: data[offset++]
  34264. };
  34265. return header;
  34266. };
  34267. TGATools.UploadContent = function (gl, data) {
  34268. // Not enough data to contain header ?
  34269. if (data.length < 19) {
  34270. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  34271. return;
  34272. }
  34273. // Read Header
  34274. var offset = 18;
  34275. var header = TGATools.GetTGAHeader(data);
  34276. // Assume it's a valid Targa file.
  34277. if (header.id_length + offset > data.length) {
  34278. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  34279. return;
  34280. }
  34281. // Skip not needed data
  34282. offset += header.id_length;
  34283. var use_rle = false;
  34284. var use_pal = false;
  34285. var use_rgb = false;
  34286. var use_grey = false;
  34287. // Get some informations.
  34288. switch (header.image_type) {
  34289. case TGATools._TYPE_RLE_INDEXED:
  34290. use_rle = true;
  34291. case TGATools._TYPE_INDEXED:
  34292. use_pal = true;
  34293. break;
  34294. case TGATools._TYPE_RLE_RGB:
  34295. use_rle = true;
  34296. case TGATools._TYPE_RGB:
  34297. use_rgb = true;
  34298. break;
  34299. case TGATools._TYPE_RLE_GREY:
  34300. use_rle = true;
  34301. case TGATools._TYPE_GREY:
  34302. use_grey = true;
  34303. break;
  34304. }
  34305. var pixel_data;
  34306. var numAlphaBits = header.flags & 0xf;
  34307. var pixel_size = header.pixel_size >> 3;
  34308. var pixel_total = header.width * header.height * pixel_size;
  34309. // Read palettes
  34310. var palettes;
  34311. if (use_pal) {
  34312. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  34313. }
  34314. // Read LRE
  34315. if (use_rle) {
  34316. pixel_data = new Uint8Array(pixel_total);
  34317. var c, count, i;
  34318. var localOffset = 0;
  34319. var pixels = new Uint8Array(pixel_size);
  34320. while (offset < pixel_total && localOffset < pixel_total) {
  34321. c = data[offset++];
  34322. count = (c & 0x7f) + 1;
  34323. // RLE pixels
  34324. if (c & 0x80) {
  34325. // Bind pixel tmp array
  34326. for (i = 0; i < pixel_size; ++i) {
  34327. pixels[i] = data[offset++];
  34328. }
  34329. // Copy pixel array
  34330. for (i = 0; i < count; ++i) {
  34331. pixel_data.set(pixels, localOffset + i * pixel_size);
  34332. }
  34333. localOffset += pixel_size * count;
  34334. }
  34335. else {
  34336. count *= pixel_size;
  34337. for (i = 0; i < count; ++i) {
  34338. pixel_data[localOffset + i] = data[offset++];
  34339. }
  34340. localOffset += count;
  34341. }
  34342. }
  34343. }
  34344. else {
  34345. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  34346. }
  34347. // Load to texture
  34348. var x_start, y_start, x_step, y_step, y_end, x_end;
  34349. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  34350. default:
  34351. case TGATools._ORIGIN_UL:
  34352. x_start = 0;
  34353. x_step = 1;
  34354. x_end = header.width;
  34355. y_start = 0;
  34356. y_step = 1;
  34357. y_end = header.height;
  34358. break;
  34359. case TGATools._ORIGIN_BL:
  34360. x_start = 0;
  34361. x_step = 1;
  34362. x_end = header.width;
  34363. y_start = header.height - 1;
  34364. y_step = -1;
  34365. y_end = -1;
  34366. break;
  34367. case TGATools._ORIGIN_UR:
  34368. x_start = header.width - 1;
  34369. x_step = -1;
  34370. x_end = -1;
  34371. y_start = 0;
  34372. y_step = 1;
  34373. y_end = header.height;
  34374. break;
  34375. case TGATools._ORIGIN_BR:
  34376. x_start = header.width - 1;
  34377. x_step = -1;
  34378. x_end = -1;
  34379. y_start = header.height - 1;
  34380. y_step = -1;
  34381. y_end = -1;
  34382. break;
  34383. }
  34384. // Load the specify method
  34385. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  34386. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  34387. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  34388. };
  34389. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34390. var image = pixel_data, colormap = palettes;
  34391. var width = header.width, height = header.height;
  34392. var color, i = 0, x, y;
  34393. var imageData = new Uint8Array(width * height * 4);
  34394. for (y = y_start; y !== y_end; y += y_step) {
  34395. for (x = x_start; x !== x_end; x += x_step, i++) {
  34396. color = image[i];
  34397. imageData[(x + width * y) * 4 + 3] = 255;
  34398. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  34399. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  34400. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  34401. }
  34402. }
  34403. return imageData;
  34404. };
  34405. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34406. var image = pixel_data;
  34407. var width = header.width, height = header.height;
  34408. var color, i = 0, x, y;
  34409. var imageData = new Uint8Array(width * height * 4);
  34410. for (y = y_start; y !== y_end; y += y_step) {
  34411. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34412. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  34413. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  34414. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  34415. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  34416. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  34417. }
  34418. }
  34419. return imageData;
  34420. };
  34421. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34422. var image = pixel_data;
  34423. var width = header.width, height = header.height;
  34424. var i = 0, x, y;
  34425. var imageData = new Uint8Array(width * height * 4);
  34426. for (y = y_start; y !== y_end; y += y_step) {
  34427. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  34428. imageData[(x + width * y) * 4 + 3] = 255;
  34429. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34430. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34431. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34432. }
  34433. }
  34434. return imageData;
  34435. };
  34436. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34437. var image = pixel_data;
  34438. var width = header.width, height = header.height;
  34439. var i = 0, x, y;
  34440. var imageData = new Uint8Array(width * height * 4);
  34441. for (y = y_start; y !== y_end; y += y_step) {
  34442. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  34443. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34444. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34445. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34446. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  34447. }
  34448. }
  34449. return imageData;
  34450. };
  34451. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34452. var image = pixel_data;
  34453. var width = header.width, height = header.height;
  34454. var color, i = 0, x, y;
  34455. var imageData = new Uint8Array(width * height * 4);
  34456. for (y = y_start; y !== y_end; y += y_step) {
  34457. for (x = x_start; x !== x_end; x += x_step, i++) {
  34458. color = image[i];
  34459. imageData[(x + width * y) * 4 + 0] = color;
  34460. imageData[(x + width * y) * 4 + 1] = color;
  34461. imageData[(x + width * y) * 4 + 2] = color;
  34462. imageData[(x + width * y) * 4 + 3] = 255;
  34463. }
  34464. }
  34465. return imageData;
  34466. };
  34467. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34468. var image = pixel_data;
  34469. var width = header.width, height = header.height;
  34470. var i = 0, x, y;
  34471. var imageData = new Uint8Array(width * height * 4);
  34472. for (y = y_start; y !== y_end; y += y_step) {
  34473. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34474. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  34475. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  34476. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34477. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  34478. }
  34479. }
  34480. return imageData;
  34481. };
  34482. TGATools._TYPE_NO_DATA = 0;
  34483. TGATools._TYPE_INDEXED = 1;
  34484. TGATools._TYPE_RGB = 2;
  34485. TGATools._TYPE_GREY = 3;
  34486. TGATools._TYPE_RLE_INDEXED = 9;
  34487. TGATools._TYPE_RLE_RGB = 10;
  34488. TGATools._TYPE_RLE_GREY = 11;
  34489. TGATools._ORIGIN_MASK = 0x30;
  34490. TGATools._ORIGIN_SHIFT = 0x04;
  34491. TGATools._ORIGIN_BL = 0x00;
  34492. TGATools._ORIGIN_BR = 0x01;
  34493. TGATools._ORIGIN_UL = 0x02;
  34494. TGATools._ORIGIN_UR = 0x03;
  34495. return TGATools;
  34496. }());
  34497. Internals.TGATools = TGATools;
  34498. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34499. })(BABYLON || (BABYLON = {}));
  34500. //# sourceMappingURL=babylon.tga.js.map
  34501. var BABYLON;
  34502. (function (BABYLON) {
  34503. var Internals;
  34504. (function (Internals) {
  34505. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34506. // All values and structures referenced from:
  34507. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34508. var DDS_MAGIC = 0x20534444;
  34509. 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;
  34510. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34511. 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;
  34512. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34513. function FourCCToInt32(value) {
  34514. return value.charCodeAt(0) +
  34515. (value.charCodeAt(1) << 8) +
  34516. (value.charCodeAt(2) << 16) +
  34517. (value.charCodeAt(3) << 24);
  34518. }
  34519. function Int32ToFourCC(value) {
  34520. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34521. }
  34522. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34523. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34524. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34525. var FOURCC_DX10 = FourCCToInt32("DX10");
  34526. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  34527. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  34528. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  34529. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  34530. var headerLengthInt = 31; // The header length in 32 bit ints
  34531. // Offsets into the header array
  34532. var off_magic = 0;
  34533. var off_size = 1;
  34534. var off_flags = 2;
  34535. var off_height = 3;
  34536. var off_width = 4;
  34537. var off_mipmapCount = 7;
  34538. var off_pfFlags = 20;
  34539. var off_pfFourCC = 21;
  34540. var off_RGBbpp = 22;
  34541. var off_RMask = 23;
  34542. var off_GMask = 24;
  34543. var off_BMask = 25;
  34544. var off_AMask = 26;
  34545. var off_caps1 = 27;
  34546. var off_caps2 = 28;
  34547. var off_caps3 = 29;
  34548. var off_caps4 = 30;
  34549. var off_dxgiFormat = 32;
  34550. ;
  34551. var DDSTools = (function () {
  34552. function DDSTools() {
  34553. }
  34554. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34555. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34556. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  34557. var mipmapCount = 1;
  34558. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34559. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34560. }
  34561. var fourCC = header[off_pfFourCC];
  34562. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  34563. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34564. switch (fourCC) {
  34565. case FOURCC_D3DFMT_R16G16B16A16F:
  34566. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34567. break;
  34568. case FOURCC_D3DFMT_R32G32B32A32F:
  34569. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34570. break;
  34571. case FOURCC_DX10:
  34572. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  34573. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34574. break;
  34575. }
  34576. }
  34577. return {
  34578. width: header[off_width],
  34579. height: header[off_height],
  34580. mipmapCount: mipmapCount,
  34581. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34582. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34583. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34584. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  34585. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  34586. dxgiFormat: dxgiFormat,
  34587. textureType: textureType
  34588. };
  34589. };
  34590. DDSTools._ToHalfFloat = function (value) {
  34591. if (!DDSTools._FloatView) {
  34592. DDSTools._FloatView = new Float32Array(1);
  34593. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  34594. }
  34595. DDSTools._FloatView[0] = value;
  34596. var x = DDSTools._Int32View[0];
  34597. var bits = (x >> 16) & 0x8000; /* Get the sign */
  34598. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  34599. var e = (x >> 23) & 0xff; /* Using int is faster here */
  34600. /* If zero, or denormal, or exponent underflows too much for a denormal
  34601. * half, return signed zero. */
  34602. if (e < 103) {
  34603. return bits;
  34604. }
  34605. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  34606. if (e > 142) {
  34607. bits |= 0x7c00;
  34608. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  34609. * not Inf, so make sure we set one mantissa bit too. */
  34610. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  34611. return bits;
  34612. }
  34613. /* If exponent underflows but not too much, return a denormal */
  34614. if (e < 113) {
  34615. m |= 0x0800;
  34616. /* Extra rounding may overflow and set mantissa to 0 and exponent
  34617. * to 1, which is OK. */
  34618. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  34619. return bits;
  34620. }
  34621. bits |= ((e - 112) << 10) | (m >> 1);
  34622. bits += m & 1;
  34623. return bits;
  34624. };
  34625. DDSTools._FromHalfFloat = function (value) {
  34626. var s = (value & 0x8000) >> 15;
  34627. var e = (value & 0x7C00) >> 10;
  34628. var f = value & 0x03FF;
  34629. if (e === 0) {
  34630. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  34631. }
  34632. else if (e == 0x1F) {
  34633. return f ? NaN : ((s ? -1 : 1) * Infinity);
  34634. }
  34635. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  34636. };
  34637. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34638. var destArray = new Float32Array(dataLength);
  34639. var srcData = new Uint16Array(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) * 4;
  34644. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  34645. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  34646. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  34647. if (DDSTools.StoreLODInAlphaChannel) {
  34648. destArray[index + 3] = lod;
  34649. }
  34650. else {
  34651. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  34652. }
  34653. index += 4;
  34654. }
  34655. }
  34656. return destArray;
  34657. };
  34658. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34659. if (DDSTools.StoreLODInAlphaChannel) {
  34660. var destArray = new Uint16Array(dataLength);
  34661. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34662. var index = 0;
  34663. for (var y = 0; y < height; y++) {
  34664. for (var x = 0; x < width; x++) {
  34665. var srcPos = (x + y * width) * 4;
  34666. destArray[index] = srcData[srcPos];
  34667. destArray[index + 1] = srcData[srcPos + 1];
  34668. destArray[index + 2] = srcData[srcPos + 2];
  34669. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  34670. index += 4;
  34671. }
  34672. }
  34673. return destArray;
  34674. }
  34675. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  34676. };
  34677. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34678. if (DDSTools.StoreLODInAlphaChannel) {
  34679. var destArray = new Float32Array(dataLength);
  34680. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34681. var index = 0;
  34682. for (var y = 0; y < height; y++) {
  34683. for (var x = 0; x < width; x++) {
  34684. var srcPos = (x + y * width) * 4;
  34685. destArray[index] = srcData[srcPos];
  34686. destArray[index + 1] = srcData[srcPos + 1];
  34687. destArray[index + 2] = srcData[srcPos + 2];
  34688. destArray[index + 3] = lod;
  34689. index += 4;
  34690. }
  34691. }
  34692. return destArray;
  34693. }
  34694. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  34695. };
  34696. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34697. var destArray = new Uint8Array(dataLength);
  34698. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34699. var index = 0;
  34700. for (var y = 0; y < height; y++) {
  34701. for (var x = 0; x < width; x++) {
  34702. var srcPos = (x + y * width) * 4;
  34703. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  34704. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  34705. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  34706. if (DDSTools.StoreLODInAlphaChannel) {
  34707. destArray[index + 3] = lod;
  34708. }
  34709. else {
  34710. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  34711. }
  34712. index += 4;
  34713. }
  34714. }
  34715. return destArray;
  34716. };
  34717. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34718. var destArray = new Uint8Array(dataLength);
  34719. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34720. var index = 0;
  34721. for (var y = 0; y < height; y++) {
  34722. for (var x = 0; x < width; x++) {
  34723. var srcPos = (x + y * width) * 4;
  34724. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  34725. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  34726. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  34727. if (DDSTools.StoreLODInAlphaChannel) {
  34728. destArray[index + 3] = lod;
  34729. }
  34730. else {
  34731. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  34732. }
  34733. index += 4;
  34734. }
  34735. }
  34736. return destArray;
  34737. };
  34738. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34739. var byteArray = new Uint8Array(dataLength);
  34740. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34741. var index = 0;
  34742. for (var y = 0; y < height; y++) {
  34743. for (var x = 0; x < width; x++) {
  34744. var srcPos = (x + y * width) * 4;
  34745. byteArray[index] = srcData[srcPos + 2];
  34746. byteArray[index + 1] = srcData[srcPos + 1];
  34747. byteArray[index + 2] = srcData[srcPos];
  34748. byteArray[index + 3] = srcData[srcPos + 3];
  34749. index += 4;
  34750. }
  34751. }
  34752. return byteArray;
  34753. };
  34754. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34755. var byteArray = new Uint8Array(dataLength);
  34756. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34757. var index = 0;
  34758. for (var y = 0; y < height; y++) {
  34759. for (var x = 0; x < width; x++) {
  34760. var srcPos = (x + y * width) * 3;
  34761. byteArray[index] = srcData[srcPos + 2];
  34762. byteArray[index + 1] = srcData[srcPos + 1];
  34763. byteArray[index + 2] = srcData[srcPos];
  34764. index += 3;
  34765. }
  34766. }
  34767. return byteArray;
  34768. };
  34769. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34770. var byteArray = new Uint8Array(dataLength);
  34771. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34772. var index = 0;
  34773. for (var y = 0; y < height; y++) {
  34774. for (var x = 0; x < width; x++) {
  34775. var srcPos = (x + y * width);
  34776. byteArray[index] = srcData[srcPos];
  34777. index++;
  34778. }
  34779. }
  34780. return byteArray;
  34781. };
  34782. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  34783. if (lodIndex === void 0) { lodIndex = -1; }
  34784. var ext = engine.getCaps().s3tc;
  34785. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  34786. if (header[off_magic] != DDS_MAGIC) {
  34787. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34788. return;
  34789. }
  34790. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34791. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34792. return;
  34793. }
  34794. if (info.isCompressed && !ext) {
  34795. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  34796. return;
  34797. }
  34798. var bpp = header[off_RGBbpp];
  34799. dataOffset = header[off_size] + 4;
  34800. var computeFormats = false;
  34801. if (info.isFourCC) {
  34802. fourCC = header[off_pfFourCC];
  34803. switch (fourCC) {
  34804. case FOURCC_DXT1:
  34805. blockBytes = 8;
  34806. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34807. break;
  34808. case FOURCC_DXT3:
  34809. blockBytes = 16;
  34810. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34811. break;
  34812. case FOURCC_DXT5:
  34813. blockBytes = 16;
  34814. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34815. break;
  34816. case FOURCC_D3DFMT_R16G16B16A16F:
  34817. computeFormats = true;
  34818. break;
  34819. case FOURCC_D3DFMT_R32G32B32A32F:
  34820. computeFormats = true;
  34821. break;
  34822. case FOURCC_DX10:
  34823. // There is an additionnal header so dataOffset need to be changed
  34824. dataOffset += 5 * 4; // 5 uints
  34825. var supported = false;
  34826. switch (info.dxgiFormat) {
  34827. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  34828. computeFormats = true;
  34829. supported = true;
  34830. break;
  34831. case DXGI_FORMAT_B8G8R8X8_UNORM:
  34832. info.isRGB = true;
  34833. info.isFourCC = false;
  34834. bpp = 32;
  34835. supported = true;
  34836. break;
  34837. }
  34838. if (supported) {
  34839. break;
  34840. }
  34841. default:
  34842. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34843. return;
  34844. }
  34845. }
  34846. if (computeFormats) {
  34847. format = engine._getWebGLTextureType(info.textureType);
  34848. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34849. }
  34850. mipmapCount = 1;
  34851. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34852. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34853. }
  34854. for (var face = 0; face < faces; face++) {
  34855. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34856. width = header[off_width];
  34857. height = header[off_height];
  34858. for (mip = 0; mip < mipmapCount; ++mip) {
  34859. if (lodIndex === -1 || lodIndex === mip) {
  34860. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  34861. var i = (lodIndex === -1) ? mip : 0;
  34862. if (!info.isCompressed && info.isFourCC) {
  34863. dataLength = width * height * 4;
  34864. var floatArray;
  34865. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  34866. if (bpp === 128) {
  34867. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34868. }
  34869. else if (bpp === 64) {
  34870. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34871. }
  34872. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34873. format = engine._getWebGLTextureType(info.textureType);
  34874. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34875. }
  34876. else {
  34877. if (bpp === 128) {
  34878. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34879. }
  34880. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  34881. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34882. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34883. format = engine._getWebGLTextureType(info.textureType);
  34884. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34885. }
  34886. else {
  34887. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34888. }
  34889. }
  34890. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  34891. }
  34892. else if (info.isRGB) {
  34893. if (bpp === 24) {
  34894. dataLength = width * height * 3;
  34895. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34896. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34897. }
  34898. else {
  34899. dataLength = width * height * 4;
  34900. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34901. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34902. }
  34903. }
  34904. else if (info.isLuminance) {
  34905. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34906. var unpaddedRowSize = width;
  34907. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34908. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34909. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34910. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34911. }
  34912. else {
  34913. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34914. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34915. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  34916. }
  34917. }
  34918. dataOffset += width * height * (bpp / 8);
  34919. width *= 0.5;
  34920. height *= 0.5;
  34921. width = Math.max(1.0, width);
  34922. height = Math.max(1.0, height);
  34923. }
  34924. }
  34925. };
  34926. DDSTools.StoreLODInAlphaChannel = false;
  34927. return DDSTools;
  34928. }());
  34929. Internals.DDSTools = DDSTools;
  34930. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34931. })(BABYLON || (BABYLON = {}));
  34932. //# sourceMappingURL=babylon.dds.js.map
  34933. var BABYLON;
  34934. (function (BABYLON) {
  34935. var Internals;
  34936. (function (Internals) {
  34937. /**
  34938. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  34939. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  34940. */
  34941. var KhronosTextureContainer = (function () {
  34942. /**
  34943. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  34944. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  34945. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  34946. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  34947. */
  34948. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  34949. this.arrayBuffer = arrayBuffer;
  34950. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  34951. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  34952. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  34953. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  34954. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  34955. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  34956. BABYLON.Tools.Error("texture missing KTX identifier");
  34957. return;
  34958. }
  34959. // load the reset of the header in native 32 bit int
  34960. var header = new Int32Array(this.arrayBuffer, 12, 13);
  34961. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  34962. var oppositeEndianess = header[0] === 0x01020304;
  34963. // read all the header elements in order they exist in the file, without modification (sans endainness)
  34964. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  34965. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  34966. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  34967. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  34968. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  34969. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  34970. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  34971. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  34972. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  34973. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  34974. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  34975. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  34976. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  34977. if (this.glType !== 0) {
  34978. BABYLON.Tools.Error("only compressed formats currently supported");
  34979. return;
  34980. }
  34981. else {
  34982. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  34983. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  34984. }
  34985. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  34986. BABYLON.Tools.Error("only 2D textures currently supported");
  34987. return;
  34988. }
  34989. if (this.numberOfArrayElements !== 0) {
  34990. BABYLON.Tools.Error("texture arrays not currently supported");
  34991. return;
  34992. }
  34993. if (this.numberOfFaces !== facesExpected) {
  34994. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  34995. return;
  34996. }
  34997. // we now have a completely validated file, so could use existence of loadType as success
  34998. // would need to make this more elaborate & adjust checks above to support more than one load type
  34999. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  35000. }
  35001. // not as fast hardware based, but will probably never need to use
  35002. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  35003. return ((val & 0xFF) << 24)
  35004. | ((val & 0xFF00) << 8)
  35005. | ((val >> 8) & 0xFF00)
  35006. | ((val >> 24) & 0xFF);
  35007. };
  35008. /**
  35009. * It is assumed that the texture has already been created & is currently bound
  35010. */
  35011. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  35012. switch (this.loadType) {
  35013. case KhronosTextureContainer.COMPRESSED_2D:
  35014. this._upload2DCompressedLevels(gl, loadMipmaps);
  35015. break;
  35016. case KhronosTextureContainer.TEX_2D:
  35017. case KhronosTextureContainer.COMPRESSED_3D:
  35018. case KhronosTextureContainer.TEX_3D:
  35019. }
  35020. };
  35021. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  35022. // initialize width & height for level 1
  35023. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  35024. var width = this.pixelWidth;
  35025. var height = this.pixelHeight;
  35026. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  35027. for (var level = 0; level < mipmapCount; level++) {
  35028. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  35029. for (var face = 0; face < this.numberOfFaces; face++) {
  35030. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  35031. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  35032. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  35033. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  35034. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  35035. }
  35036. width = Math.max(1.0, width * 0.5);
  35037. height = Math.max(1.0, height * 0.5);
  35038. }
  35039. };
  35040. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  35041. // load types
  35042. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  35043. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  35044. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  35045. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  35046. return KhronosTextureContainer;
  35047. }());
  35048. Internals.KhronosTextureContainer = KhronosTextureContainer;
  35049. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35050. })(BABYLON || (BABYLON = {}));
  35051. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  35052. var BABYLON;
  35053. (function (BABYLON) {
  35054. var PostProcess = (function () {
  35055. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  35056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  35057. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35058. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  35059. if (blockCompilation === void 0) { blockCompilation = false; }
  35060. this.name = name;
  35061. this.width = -1;
  35062. this.height = -1;
  35063. this.autoClear = true;
  35064. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  35065. /*
  35066. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  35067. Can only be used on a single postprocess or on the last one of a chain.
  35068. */
  35069. this.enablePixelPerfectMode = false;
  35070. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  35071. this.alwaysForcePOT = false;
  35072. this.samples = 1;
  35073. this._reusable = false;
  35074. this._textures = new BABYLON.SmartArray(2);
  35075. this._currentRenderTextureInd = 0;
  35076. this._scaleRatio = new BABYLON.Vector2(1, 1);
  35077. this._texelSize = BABYLON.Vector2.Zero();
  35078. // Events
  35079. /**
  35080. * An event triggered when the postprocess is activated.
  35081. * @type {BABYLON.Observable}
  35082. */
  35083. this.onActivateObservable = new BABYLON.Observable();
  35084. /**
  35085. * An event triggered when the postprocess changes its size.
  35086. * @type {BABYLON.Observable}
  35087. */
  35088. this.onSizeChangedObservable = new BABYLON.Observable();
  35089. /**
  35090. * An event triggered when the postprocess applies its effect.
  35091. * @type {BABYLON.Observable}
  35092. */
  35093. this.onApplyObservable = new BABYLON.Observable();
  35094. /**
  35095. * An event triggered before rendering the postprocess
  35096. * @type {BABYLON.Observable}
  35097. */
  35098. this.onBeforeRenderObservable = new BABYLON.Observable();
  35099. /**
  35100. * An event triggered after rendering the postprocess
  35101. * @type {BABYLON.Observable}
  35102. */
  35103. this.onAfterRenderObservable = new BABYLON.Observable();
  35104. if (camera != null) {
  35105. this._camera = camera;
  35106. this._scene = camera.getScene();
  35107. camera.attachPostProcess(this);
  35108. this._engine = this._scene.getEngine();
  35109. this._scene.postProcesses.push(this);
  35110. }
  35111. else {
  35112. this._engine = engine;
  35113. this._engine.postProcesses.push(this);
  35114. }
  35115. this._options = options;
  35116. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  35117. this._reusable = reusable || false;
  35118. this._textureType = textureType;
  35119. this._samplers = samplers || [];
  35120. this._samplers.push("textureSampler");
  35121. this._fragmentUrl = fragmentUrl;
  35122. this._vertexUrl = vertexUrl;
  35123. this._parameters = parameters || [];
  35124. this._parameters.push("scale");
  35125. this._indexParameters = indexParameters;
  35126. if (!blockCompilation) {
  35127. this.updateEffect(defines);
  35128. }
  35129. }
  35130. Object.defineProperty(PostProcess.prototype, "onActivate", {
  35131. set: function (callback) {
  35132. if (this._onActivateObserver) {
  35133. this.onActivateObservable.remove(this._onActivateObserver);
  35134. }
  35135. this._onActivateObserver = this.onActivateObservable.add(callback);
  35136. },
  35137. enumerable: true,
  35138. configurable: true
  35139. });
  35140. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  35141. set: function (callback) {
  35142. if (this._onSizeChangedObserver) {
  35143. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  35144. }
  35145. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  35146. },
  35147. enumerable: true,
  35148. configurable: true
  35149. });
  35150. Object.defineProperty(PostProcess.prototype, "onApply", {
  35151. set: function (callback) {
  35152. if (this._onApplyObserver) {
  35153. this.onApplyObservable.remove(this._onApplyObserver);
  35154. }
  35155. this._onApplyObserver = this.onApplyObservable.add(callback);
  35156. },
  35157. enumerable: true,
  35158. configurable: true
  35159. });
  35160. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  35161. set: function (callback) {
  35162. if (this._onBeforeRenderObserver) {
  35163. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  35164. }
  35165. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  35166. },
  35167. enumerable: true,
  35168. configurable: true
  35169. });
  35170. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  35171. set: function (callback) {
  35172. if (this._onAfterRenderObserver) {
  35173. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  35174. }
  35175. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  35176. },
  35177. enumerable: true,
  35178. configurable: true
  35179. });
  35180. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  35181. get: function () {
  35182. return this._textures.data[this._currentRenderTextureInd];
  35183. },
  35184. set: function (value) {
  35185. this._forcedOutputTexture = value;
  35186. },
  35187. enumerable: true,
  35188. configurable: true
  35189. });
  35190. PostProcess.prototype.getCamera = function () {
  35191. return this._camera;
  35192. };
  35193. Object.defineProperty(PostProcess.prototype, "texelSize", {
  35194. get: function () {
  35195. if (this._shareOutputWithPostProcess) {
  35196. return this._shareOutputWithPostProcess.texelSize;
  35197. }
  35198. if (this._forcedOutputTexture) {
  35199. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  35200. }
  35201. return this._texelSize;
  35202. },
  35203. enumerable: true,
  35204. configurable: true
  35205. });
  35206. PostProcess.prototype.getEngine = function () {
  35207. return this._engine;
  35208. };
  35209. PostProcess.prototype.getEffect = function () {
  35210. return this._effect;
  35211. };
  35212. PostProcess.prototype.shareOutputWith = function (postProcess) {
  35213. this._disposeTextures();
  35214. this._shareOutputWithPostProcess = postProcess;
  35215. return this;
  35216. };
  35217. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  35218. 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);
  35219. };
  35220. PostProcess.prototype.isReusable = function () {
  35221. return this._reusable;
  35222. };
  35223. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  35224. PostProcess.prototype.markTextureDirty = function () {
  35225. this.width = -1;
  35226. };
  35227. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  35228. var _this = this;
  35229. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  35230. camera = camera || this._camera;
  35231. var scene = camera.getScene();
  35232. var engine = scene.getEngine();
  35233. var maxSize = engine.getCaps().maxTextureSize;
  35234. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  35235. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  35236. var desiredWidth = this._options.width || requiredWidth;
  35237. var desiredHeight = this._options.height || requiredHeight;
  35238. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  35239. if (!this._options.width) {
  35240. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  35241. }
  35242. if (!this._options.height) {
  35243. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  35244. }
  35245. }
  35246. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  35247. if (this._textures.length > 0) {
  35248. for (var i = 0; i < this._textures.length; i++) {
  35249. this._engine._releaseTexture(this._textures.data[i]);
  35250. }
  35251. this._textures.reset();
  35252. }
  35253. this.width = desiredWidth;
  35254. this.height = desiredHeight;
  35255. var textureSize = { width: this.width, height: this.height };
  35256. var textureOptions = {
  35257. generateMipMaps: false,
  35258. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  35259. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  35260. samplingMode: this.renderTargetSamplingMode,
  35261. type: this._textureType
  35262. };
  35263. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35264. if (this._reusable) {
  35265. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35266. }
  35267. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  35268. this.onSizeChangedObservable.notifyObservers(this);
  35269. }
  35270. this._textures.forEach(function (texture) {
  35271. if (texture.samples !== _this.samples) {
  35272. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  35273. }
  35274. });
  35275. }
  35276. var target;
  35277. if (this._shareOutputWithPostProcess) {
  35278. target = this._shareOutputWithPostProcess.outputTexture;
  35279. }
  35280. else if (this._forcedOutputTexture) {
  35281. target = this._forcedOutputTexture;
  35282. this.width = this._forcedOutputTexture.width;
  35283. this.height = this._forcedOutputTexture.height;
  35284. }
  35285. else {
  35286. target = this.outputTexture;
  35287. }
  35288. if (this.enablePixelPerfectMode) {
  35289. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  35290. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  35291. }
  35292. else {
  35293. this._scaleRatio.copyFromFloats(1, 1);
  35294. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  35295. }
  35296. this.onActivateObservable.notifyObservers(camera);
  35297. // Clear
  35298. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  35299. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  35300. }
  35301. if (this._reusable) {
  35302. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  35303. }
  35304. };
  35305. Object.defineProperty(PostProcess.prototype, "isSupported", {
  35306. get: function () {
  35307. return this._effect.isSupported;
  35308. },
  35309. enumerable: true,
  35310. configurable: true
  35311. });
  35312. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  35313. get: function () {
  35314. if (this._shareOutputWithPostProcess) {
  35315. return this._shareOutputWithPostProcess.aspectRatio;
  35316. }
  35317. if (this._forcedOutputTexture) {
  35318. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  35319. }
  35320. return this.width / this.height;
  35321. },
  35322. enumerable: true,
  35323. configurable: true
  35324. });
  35325. PostProcess.prototype.apply = function () {
  35326. // Check
  35327. if (!this._effect || !this._effect.isReady())
  35328. return null;
  35329. // States
  35330. this._engine.enableEffect(this._effect);
  35331. this._engine.setState(false);
  35332. this._engine.setDepthBuffer(false);
  35333. this._engine.setDepthWrite(false);
  35334. // Alpha
  35335. this._engine.setAlphaMode(this.alphaMode);
  35336. if (this.alphaConstants) {
  35337. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  35338. }
  35339. // Texture
  35340. var source;
  35341. if (this._shareOutputWithPostProcess) {
  35342. source = this._shareOutputWithPostProcess.outputTexture;
  35343. }
  35344. else if (this._forcedOutputTexture) {
  35345. source = this._forcedOutputTexture;
  35346. }
  35347. else {
  35348. source = this.outputTexture;
  35349. }
  35350. this._effect._bindTexture("textureSampler", source);
  35351. // Parameters
  35352. this._effect.setVector2("scale", this._scaleRatio);
  35353. this.onApplyObservable.notifyObservers(this._effect);
  35354. return this._effect;
  35355. };
  35356. PostProcess.prototype._disposeTextures = function () {
  35357. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  35358. return;
  35359. }
  35360. if (this._textures.length > 0) {
  35361. for (var i = 0; i < this._textures.length; i++) {
  35362. this._engine._releaseTexture(this._textures.data[i]);
  35363. }
  35364. }
  35365. this._textures.dispose();
  35366. };
  35367. PostProcess.prototype.dispose = function (camera) {
  35368. camera = camera || this._camera;
  35369. this._disposeTextures();
  35370. if (this._scene) {
  35371. var index_1 = this._scene.postProcesses.indexOf(this);
  35372. if (index_1 !== -1) {
  35373. this._scene.postProcesses.splice(index_1, 1);
  35374. }
  35375. }
  35376. else {
  35377. var index_2 = this._engine.postProcesses.indexOf(this);
  35378. if (index_2 !== -1) {
  35379. this._engine.postProcesses.splice(index_2, 1);
  35380. }
  35381. }
  35382. if (!camera) {
  35383. return;
  35384. }
  35385. camera.detachPostProcess(this);
  35386. var index = camera._postProcesses.indexOf(this);
  35387. if (index === 0 && camera._postProcesses.length > 0) {
  35388. this._camera._postProcesses[0].markTextureDirty();
  35389. }
  35390. this.onActivateObservable.clear();
  35391. this.onAfterRenderObservable.clear();
  35392. this.onApplyObservable.clear();
  35393. this.onBeforeRenderObservable.clear();
  35394. this.onSizeChangedObservable.clear();
  35395. };
  35396. return PostProcess;
  35397. }());
  35398. BABYLON.PostProcess = PostProcess;
  35399. })(BABYLON || (BABYLON = {}));
  35400. //# sourceMappingURL=babylon.postProcess.js.map
  35401. var BABYLON;
  35402. (function (BABYLON) {
  35403. var PassPostProcess = (function (_super) {
  35404. __extends(PassPostProcess, _super);
  35405. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  35406. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35407. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  35408. }
  35409. return PassPostProcess;
  35410. }(BABYLON.PostProcess));
  35411. BABYLON.PassPostProcess = PassPostProcess;
  35412. })(BABYLON || (BABYLON = {}));
  35413. //# sourceMappingURL=babylon.passPostProcess.js.map
  35414. var BABYLON;
  35415. (function (BABYLON) {
  35416. var ShadowGenerator = (function () {
  35417. /**
  35418. * Creates a ShadowGenerator object.
  35419. * A ShadowGenerator is the required tool to use the shadows.
  35420. * Each light casting shadows needs to use its own ShadowGenerator.
  35421. * Required parameters :
  35422. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  35423. * - `light`: the light object generating the shadows.
  35424. * - `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.
  35425. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  35426. */
  35427. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  35428. // Members
  35429. this._bias = 0.00005;
  35430. this._blurBoxOffset = 1;
  35431. this._blurScale = 2;
  35432. this._blurKernel = 1;
  35433. this._useKernelBlur = false;
  35434. this._filter = ShadowGenerator.FILTER_NONE;
  35435. this._darkness = 0;
  35436. this._transparencyShadow = false;
  35437. /**
  35438. * Controls the extent to which the shadows fade out at the edge of the frustum
  35439. * Used only by directionals and spots
  35440. */
  35441. this.frustumEdgeFalloff = 0;
  35442. this.forceBackFacesOnly = false;
  35443. this._lightDirection = BABYLON.Vector3.Zero();
  35444. this._viewMatrix = BABYLON.Matrix.Zero();
  35445. this._projectionMatrix = BABYLON.Matrix.Zero();
  35446. this._transformMatrix = BABYLON.Matrix.Zero();
  35447. this._worldViewProjection = BABYLON.Matrix.Zero();
  35448. this._currentFaceIndex = 0;
  35449. this._currentFaceIndexCache = 0;
  35450. this._isCube = false;
  35451. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  35452. this._mapSize = mapSize;
  35453. this._light = light;
  35454. this._scene = light.getScene();
  35455. light._shadowGenerator = this;
  35456. // Texture type fallback from float to int if not supported.
  35457. var caps = this._scene.getEngine().getCaps();
  35458. if (!useFullFloatFirst) {
  35459. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35460. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35461. }
  35462. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35463. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35464. }
  35465. else {
  35466. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35467. }
  35468. }
  35469. else {
  35470. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35471. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35472. }
  35473. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35474. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35475. }
  35476. else {
  35477. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35478. }
  35479. }
  35480. this._initializeGenerator();
  35481. }
  35482. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  35483. // Static
  35484. get: function () {
  35485. return ShadowGenerator._FILTER_NONE;
  35486. },
  35487. enumerable: true,
  35488. configurable: true
  35489. });
  35490. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  35491. get: function () {
  35492. return ShadowGenerator._FILTER_POISSONSAMPLING;
  35493. },
  35494. enumerable: true,
  35495. configurable: true
  35496. });
  35497. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  35498. get: function () {
  35499. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  35500. },
  35501. enumerable: true,
  35502. configurable: true
  35503. });
  35504. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  35505. get: function () {
  35506. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  35507. },
  35508. enumerable: true,
  35509. configurable: true
  35510. });
  35511. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  35512. get: function () {
  35513. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35514. },
  35515. enumerable: true,
  35516. configurable: true
  35517. });
  35518. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  35519. get: function () {
  35520. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35521. },
  35522. enumerable: true,
  35523. configurable: true
  35524. });
  35525. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  35526. get: function () {
  35527. return this._bias;
  35528. },
  35529. set: function (bias) {
  35530. this._bias = bias;
  35531. },
  35532. enumerable: true,
  35533. configurable: true
  35534. });
  35535. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  35536. get: function () {
  35537. return this._blurBoxOffset;
  35538. },
  35539. set: function (value) {
  35540. if (this._blurBoxOffset === value) {
  35541. return;
  35542. }
  35543. this._blurBoxOffset = value;
  35544. this._disposeBlurPostProcesses();
  35545. },
  35546. enumerable: true,
  35547. configurable: true
  35548. });
  35549. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  35550. get: function () {
  35551. return this._blurScale;
  35552. },
  35553. set: function (value) {
  35554. if (this._blurScale === value) {
  35555. return;
  35556. }
  35557. this._blurScale = value;
  35558. this._disposeBlurPostProcesses();
  35559. },
  35560. enumerable: true,
  35561. configurable: true
  35562. });
  35563. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  35564. get: function () {
  35565. return this._blurKernel;
  35566. },
  35567. set: function (value) {
  35568. if (this._blurKernel === value) {
  35569. return;
  35570. }
  35571. this._blurKernel = value;
  35572. this._disposeBlurPostProcesses();
  35573. },
  35574. enumerable: true,
  35575. configurable: true
  35576. });
  35577. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  35578. get: function () {
  35579. return this._useKernelBlur;
  35580. },
  35581. set: function (value) {
  35582. if (this._useKernelBlur === value) {
  35583. return;
  35584. }
  35585. this._useKernelBlur = value;
  35586. this._disposeBlurPostProcesses();
  35587. },
  35588. enumerable: true,
  35589. configurable: true
  35590. });
  35591. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  35592. get: function () {
  35593. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  35594. },
  35595. set: function (value) {
  35596. this._depthScale = value;
  35597. },
  35598. enumerable: true,
  35599. configurable: true
  35600. });
  35601. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  35602. get: function () {
  35603. return this._filter;
  35604. },
  35605. set: function (value) {
  35606. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  35607. if (this._light.needCube()) {
  35608. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35609. this.useExponentialShadowMap = true;
  35610. return;
  35611. }
  35612. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35613. this.useCloseExponentialShadowMap = true;
  35614. return;
  35615. }
  35616. }
  35617. if (this._filter === value) {
  35618. return;
  35619. }
  35620. this._filter = value;
  35621. this._disposeBlurPostProcesses();
  35622. this._applyFilterValues();
  35623. this._light._markMeshesAsLightDirty();
  35624. },
  35625. enumerable: true,
  35626. configurable: true
  35627. });
  35628. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  35629. get: function () {
  35630. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  35631. },
  35632. set: function (value) {
  35633. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  35634. return;
  35635. }
  35636. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  35637. },
  35638. enumerable: true,
  35639. configurable: true
  35640. });
  35641. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  35642. get: function () {
  35643. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35644. return this.useExponentialShadowMap;
  35645. },
  35646. set: function (value) {
  35647. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35648. this.useExponentialShadowMap = value;
  35649. },
  35650. enumerable: true,
  35651. configurable: true
  35652. });
  35653. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  35654. get: function () {
  35655. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35656. return this.useBlurExponentialShadowMap;
  35657. },
  35658. set: function (value) {
  35659. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35660. this.useBlurExponentialShadowMap = value;
  35661. },
  35662. enumerable: true,
  35663. configurable: true
  35664. });
  35665. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  35666. get: function () {
  35667. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  35668. },
  35669. set: function (value) {
  35670. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  35671. return;
  35672. }
  35673. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35674. },
  35675. enumerable: true,
  35676. configurable: true
  35677. });
  35678. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  35679. get: function () {
  35680. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  35681. },
  35682. set: function (value) {
  35683. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35684. return;
  35685. }
  35686. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35687. },
  35688. enumerable: true,
  35689. configurable: true
  35690. });
  35691. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  35692. get: function () {
  35693. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35694. },
  35695. set: function (value) {
  35696. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  35697. return;
  35698. }
  35699. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35700. },
  35701. enumerable: true,
  35702. configurable: true
  35703. });
  35704. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  35705. get: function () {
  35706. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35707. },
  35708. set: function (value) {
  35709. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35710. return;
  35711. }
  35712. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35713. },
  35714. enumerable: true,
  35715. configurable: true
  35716. });
  35717. /**
  35718. * Returns the darkness value (float).
  35719. */
  35720. ShadowGenerator.prototype.getDarkness = function () {
  35721. return this._darkness;
  35722. };
  35723. /**
  35724. * Sets the ShadowGenerator darkness value (float <= 1.0).
  35725. * Returns the ShadowGenerator.
  35726. */
  35727. ShadowGenerator.prototype.setDarkness = function (darkness) {
  35728. if (darkness >= 1.0)
  35729. this._darkness = 1.0;
  35730. else if (darkness <= 0.0)
  35731. this._darkness = 0.0;
  35732. else
  35733. this._darkness = darkness;
  35734. return this;
  35735. };
  35736. /**
  35737. * Sets the ability to have transparent shadow (boolean).
  35738. * Returns the ShadowGenerator.
  35739. */
  35740. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  35741. this._transparencyShadow = hasShadow;
  35742. return this;
  35743. };
  35744. /**
  35745. * Returns a RenderTargetTexture object : the shadow map texture.
  35746. */
  35747. ShadowGenerator.prototype.getShadowMap = function () {
  35748. return this._shadowMap;
  35749. };
  35750. /**
  35751. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  35752. */
  35753. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  35754. if (this._shadowMap2) {
  35755. return this._shadowMap2;
  35756. }
  35757. return this._shadowMap;
  35758. };
  35759. /**
  35760. * Returns the associated light object.
  35761. */
  35762. ShadowGenerator.prototype.getLight = function () {
  35763. return this._light;
  35764. };
  35765. ShadowGenerator.prototype._initializeGenerator = function () {
  35766. this._light._markMeshesAsLightDirty();
  35767. this._initializeShadowMap();
  35768. };
  35769. ShadowGenerator.prototype._initializeShadowMap = function () {
  35770. var _this = this;
  35771. // Render target
  35772. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  35773. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35774. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35775. this._shadowMap.anisotropicFilteringLevel = 1;
  35776. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35777. this._shadowMap.renderParticles = false;
  35778. // Record Face Index before render.
  35779. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  35780. _this._currentFaceIndex = faceIndex;
  35781. });
  35782. // Custom render function.
  35783. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  35784. // Blur if required afer render.
  35785. this._shadowMap.onAfterUnbindObservable.add(function () {
  35786. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  35787. return;
  35788. }
  35789. if (!_this._blurPostProcesses) {
  35790. _this._initializeBlurRTTAndPostProcesses();
  35791. }
  35792. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  35793. });
  35794. // Clear according to the chosen filter.
  35795. this._shadowMap.onClearObservable.add(function (engine) {
  35796. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  35797. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  35798. }
  35799. else {
  35800. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  35801. }
  35802. });
  35803. };
  35804. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  35805. var _this = this;
  35806. var engine = this._scene.getEngine();
  35807. var targetSize = this._mapSize / this.blurScale;
  35808. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  35809. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  35810. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35811. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35812. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35813. }
  35814. if (this.useKernelBlur) {
  35815. 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);
  35816. this._kernelBlurXPostprocess.width = targetSize;
  35817. this._kernelBlurXPostprocess.height = targetSize;
  35818. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  35819. effect.setTexture("textureSampler", _this._shadowMap);
  35820. });
  35821. 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);
  35822. this._kernelBlurXPostprocess.autoClear = false;
  35823. this._kernelBlurYPostprocess.autoClear = false;
  35824. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35825. this._kernelBlurXPostprocess.packedFloat = true;
  35826. this._kernelBlurYPostprocess.packedFloat = true;
  35827. }
  35828. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  35829. }
  35830. else {
  35831. 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);
  35832. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  35833. effect.setFloat2("screenSize", targetSize, targetSize);
  35834. effect.setTexture("textureSampler", _this._shadowMap);
  35835. });
  35836. this._boxBlurPostprocess.autoClear = false;
  35837. this._blurPostProcesses = [this._boxBlurPostprocess];
  35838. }
  35839. };
  35840. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35841. var index;
  35842. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35843. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  35844. }
  35845. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35846. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  35847. }
  35848. if (this._transparencyShadow) {
  35849. for (index = 0; index < transparentSubMeshes.length; index++) {
  35850. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  35851. }
  35852. }
  35853. };
  35854. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  35855. var _this = this;
  35856. var mesh = subMesh.getRenderingMesh();
  35857. var scene = this._scene;
  35858. var engine = scene.getEngine();
  35859. // Culling
  35860. engine.setState(subMesh.getMaterial().backFaceCulling);
  35861. // Managing instances
  35862. var batch = mesh._getInstancesRenderList(subMesh._id);
  35863. if (batch.mustReturn) {
  35864. return;
  35865. }
  35866. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  35867. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  35868. engine.enableEffect(this._effect);
  35869. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  35870. var material = subMesh.getMaterial();
  35871. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  35872. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  35873. this._effect.setVector3("lightPosition", this.getLight().position);
  35874. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  35875. // Alpha test
  35876. if (material && material.needAlphaTesting()) {
  35877. var alphaTexture = material.getAlphaTestTexture();
  35878. if (alphaTexture) {
  35879. this._effect.setTexture("diffuseSampler", alphaTexture);
  35880. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  35881. }
  35882. }
  35883. // Bones
  35884. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35885. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35886. }
  35887. if (this.forceBackFacesOnly) {
  35888. engine.setState(true, 0, false, true);
  35889. }
  35890. // Draw
  35891. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35892. if (this.forceBackFacesOnly) {
  35893. engine.setState(true, 0, false, false);
  35894. }
  35895. }
  35896. else {
  35897. // Need to reset refresh rate of the shadowMap
  35898. this._shadowMap.resetRefreshCounter();
  35899. }
  35900. };
  35901. ShadowGenerator.prototype._applyFilterValues = function () {
  35902. if (this.filter === ShadowGenerator.FILTER_NONE) {
  35903. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  35904. }
  35905. else {
  35906. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35907. }
  35908. };
  35909. /**
  35910. * Force shader compilation including textures ready check
  35911. */
  35912. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  35913. var _this = this;
  35914. var scene = this._scene;
  35915. var engine = scene.getEngine();
  35916. var subMeshes = new Array();
  35917. var currentIndex = 0;
  35918. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  35919. var mesh = _a[_i];
  35920. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  35921. }
  35922. var checkReady = function () {
  35923. if (!_this._scene || !_this._scene.getEngine()) {
  35924. return;
  35925. }
  35926. var subMesh = subMeshes[currentIndex];
  35927. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  35928. currentIndex++;
  35929. if (currentIndex >= subMeshes.length) {
  35930. if (onCompiled) {
  35931. onCompiled(_this);
  35932. }
  35933. return;
  35934. }
  35935. }
  35936. setTimeout(checkReady, 16);
  35937. };
  35938. if (subMeshes.length > 0) {
  35939. checkReady();
  35940. }
  35941. };
  35942. /**
  35943. * Boolean : true when the ShadowGenerator is finally computed.
  35944. */
  35945. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  35946. var defines = [];
  35947. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35948. defines.push("#define FLOAT");
  35949. }
  35950. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35951. defines.push("#define ESM");
  35952. }
  35953. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35954. var mesh = subMesh.getMesh();
  35955. var material = subMesh.getMaterial();
  35956. // Alpha test
  35957. if (material && material.needAlphaTesting()) {
  35958. var alphaTexture = material.getAlphaTestTexture();
  35959. if (alphaTexture) {
  35960. defines.push("#define ALPHATEST");
  35961. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35962. attribs.push(BABYLON.VertexBuffer.UVKind);
  35963. defines.push("#define UV1");
  35964. }
  35965. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35966. if (alphaTexture.coordinatesIndex === 1) {
  35967. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35968. defines.push("#define UV2");
  35969. }
  35970. }
  35971. }
  35972. }
  35973. // Bones
  35974. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35975. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35976. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35977. if (mesh.numBoneInfluencers > 4) {
  35978. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35979. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35980. }
  35981. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35982. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35983. }
  35984. else {
  35985. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35986. }
  35987. // Instances
  35988. if (useInstances) {
  35989. defines.push("#define INSTANCES");
  35990. attribs.push("world0");
  35991. attribs.push("world1");
  35992. attribs.push("world2");
  35993. attribs.push("world3");
  35994. }
  35995. // Get correct effect
  35996. var join = defines.join("\n");
  35997. if (this._cachedDefines !== join) {
  35998. this._cachedDefines = join;
  35999. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  36000. }
  36001. return this._effect.isReady();
  36002. };
  36003. /**
  36004. * This creates the defines related to the standard BJS materials.
  36005. */
  36006. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  36007. var scene = this._scene;
  36008. var light = this._light;
  36009. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  36010. return;
  36011. }
  36012. defines["SHADOW" + lightIndex] = true;
  36013. if (this.usePoissonSampling) {
  36014. defines["SHADOWPCF" + lightIndex] = true;
  36015. }
  36016. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  36017. defines["SHADOWESM" + lightIndex] = true;
  36018. }
  36019. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  36020. defines["SHADOWCLOSEESM" + lightIndex] = true;
  36021. }
  36022. if (light.needCube()) {
  36023. defines["SHADOWCUBE" + lightIndex] = true;
  36024. }
  36025. };
  36026. /**
  36027. * This binds shadow lights related to the standard BJS materials.
  36028. * It implies the unifroms available on the materials are the standard BJS ones.
  36029. */
  36030. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  36031. var light = this._light;
  36032. var scene = this._scene;
  36033. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  36034. return;
  36035. }
  36036. if (!light.needCube()) {
  36037. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  36038. }
  36039. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  36040. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  36041. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  36042. };
  36043. // Methods
  36044. /**
  36045. * Returns a Matrix object : the updated transformation matrix.
  36046. */
  36047. ShadowGenerator.prototype.getTransformMatrix = function () {
  36048. var scene = this._scene;
  36049. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  36050. return this._transformMatrix;
  36051. }
  36052. this._currentRenderID = scene.getRenderId();
  36053. this._currentFaceIndexCache = this._currentFaceIndex;
  36054. var lightPosition = this._light.position;
  36055. if (this._light.computeTransformedInformation()) {
  36056. lightPosition = this._light.transformedPosition;
  36057. }
  36058. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  36059. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  36060. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  36061. }
  36062. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  36063. this._cachedPosition = lightPosition.clone();
  36064. this._cachedDirection = this._lightDirection.clone();
  36065. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  36066. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  36067. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  36068. }
  36069. return this._transformMatrix;
  36070. };
  36071. ShadowGenerator.prototype.recreateShadowMap = function () {
  36072. // Track render list.
  36073. var renderList = this._shadowMap.renderList;
  36074. // Clean up existing data.
  36075. this._disposeRTTandPostProcesses();
  36076. // Reinitializes.
  36077. this._initializeGenerator();
  36078. // Reaffect the filter to ensure a correct fallback if necessary.
  36079. this.filter = this.filter;
  36080. // Reaffect the filter.
  36081. this._applyFilterValues();
  36082. // Reaffect Render List.
  36083. this._shadowMap.renderList = renderList;
  36084. };
  36085. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  36086. if (this._shadowMap2) {
  36087. this._shadowMap2.dispose();
  36088. this._shadowMap2 = null;
  36089. }
  36090. if (this._downSamplePostprocess) {
  36091. this._downSamplePostprocess.dispose();
  36092. this._downSamplePostprocess = null;
  36093. }
  36094. if (this._boxBlurPostprocess) {
  36095. this._boxBlurPostprocess.dispose();
  36096. this._boxBlurPostprocess = null;
  36097. }
  36098. if (this._kernelBlurXPostprocess) {
  36099. this._kernelBlurXPostprocess.dispose();
  36100. this._kernelBlurXPostprocess = null;
  36101. }
  36102. if (this._kernelBlurYPostprocess) {
  36103. this._kernelBlurYPostprocess.dispose();
  36104. this._kernelBlurYPostprocess = null;
  36105. }
  36106. this._blurPostProcesses = null;
  36107. };
  36108. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  36109. if (this._shadowMap) {
  36110. this._shadowMap.dispose();
  36111. this._shadowMap = null;
  36112. }
  36113. this._disposeBlurPostProcesses();
  36114. };
  36115. /**
  36116. * Disposes the ShadowGenerator.
  36117. * Returns nothing.
  36118. */
  36119. ShadowGenerator.prototype.dispose = function () {
  36120. this._disposeRTTandPostProcesses();
  36121. this._light._shadowGenerator = null;
  36122. this._light._markMeshesAsLightDirty();
  36123. };
  36124. /**
  36125. * Serializes the ShadowGenerator and returns a serializationObject.
  36126. */
  36127. ShadowGenerator.prototype.serialize = function () {
  36128. var serializationObject = {};
  36129. var shadowMap = this.getShadowMap();
  36130. serializationObject.lightId = this._light.id;
  36131. serializationObject.mapSize = shadowMap.getRenderSize();
  36132. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  36133. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  36134. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  36135. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  36136. serializationObject.usePoissonSampling = this.usePoissonSampling;
  36137. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  36138. serializationObject.depthScale = this.depthScale;
  36139. serializationObject.darkness = this.getDarkness();
  36140. serializationObject.blurBoxOffset = this.blurBoxOffset;
  36141. serializationObject.blurKernel = this.blurKernel;
  36142. serializationObject.blurScale = this.blurScale;
  36143. serializationObject.useKernelBlur = this.useKernelBlur;
  36144. serializationObject.transparencyShadow = this._transparencyShadow;
  36145. serializationObject.renderList = [];
  36146. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  36147. var mesh = shadowMap.renderList[meshIndex];
  36148. serializationObject.renderList.push(mesh.id);
  36149. }
  36150. return serializationObject;
  36151. };
  36152. /**
  36153. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  36154. */
  36155. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  36156. //casting to point light, as light is missing the position attr and typescript complains.
  36157. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  36158. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  36159. var shadowMap = shadowGenerator.getShadowMap();
  36160. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  36161. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  36162. meshes.forEach(function (mesh) {
  36163. shadowMap.renderList.push(mesh);
  36164. });
  36165. }
  36166. if (parsedShadowGenerator.usePoissonSampling) {
  36167. shadowGenerator.usePoissonSampling = true;
  36168. }
  36169. else if (parsedShadowGenerator.useExponentialShadowMap) {
  36170. shadowGenerator.useExponentialShadowMap = true;
  36171. }
  36172. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  36173. shadowGenerator.useBlurExponentialShadowMap = true;
  36174. }
  36175. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  36176. shadowGenerator.useCloseExponentialShadowMap = true;
  36177. }
  36178. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  36179. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  36180. }
  36181. else if (parsedShadowGenerator.useVarianceShadowMap) {
  36182. shadowGenerator.useExponentialShadowMap = true;
  36183. }
  36184. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  36185. shadowGenerator.useBlurExponentialShadowMap = true;
  36186. }
  36187. if (parsedShadowGenerator.depthScale) {
  36188. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  36189. }
  36190. if (parsedShadowGenerator.blurScale) {
  36191. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  36192. }
  36193. if (parsedShadowGenerator.blurBoxOffset) {
  36194. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  36195. }
  36196. if (parsedShadowGenerator.useKernelBlur) {
  36197. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  36198. }
  36199. if (parsedShadowGenerator.blurKernel) {
  36200. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  36201. }
  36202. if (parsedShadowGenerator.bias !== undefined) {
  36203. shadowGenerator.bias = parsedShadowGenerator.bias;
  36204. }
  36205. if (parsedShadowGenerator.darkness) {
  36206. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  36207. }
  36208. if (parsedShadowGenerator.transparencyShadow) {
  36209. shadowGenerator.setTransparencyShadow(true);
  36210. }
  36211. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  36212. return shadowGenerator;
  36213. };
  36214. ShadowGenerator._FILTER_NONE = 0;
  36215. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  36216. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  36217. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  36218. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  36219. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  36220. return ShadowGenerator;
  36221. }());
  36222. BABYLON.ShadowGenerator = ShadowGenerator;
  36223. })(BABYLON || (BABYLON = {}));
  36224. //# sourceMappingURL=babylon.shadowGenerator.js.map
  36225. var BABYLON;
  36226. (function (BABYLON) {
  36227. var ShadowLight = (function (_super) {
  36228. __extends(ShadowLight, _super);
  36229. function ShadowLight() {
  36230. var _this = _super !== null && _super.apply(this, arguments) || this;
  36231. _this._needProjectionMatrixCompute = true;
  36232. return _this;
  36233. }
  36234. Object.defineProperty(ShadowLight.prototype, "direction", {
  36235. get: function () {
  36236. return this._direction;
  36237. },
  36238. set: function (value) {
  36239. this._direction = value;
  36240. },
  36241. enumerable: true,
  36242. configurable: true
  36243. });
  36244. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  36245. get: function () {
  36246. return this._shadowMinZ;
  36247. },
  36248. set: function (value) {
  36249. this._shadowMinZ = value;
  36250. this.forceProjectionMatrixCompute();
  36251. },
  36252. enumerable: true,
  36253. configurable: true
  36254. });
  36255. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  36256. get: function () {
  36257. return this._shadowMaxZ;
  36258. },
  36259. set: function (value) {
  36260. this._shadowMaxZ = value;
  36261. this.forceProjectionMatrixCompute();
  36262. },
  36263. enumerable: true,
  36264. configurable: true
  36265. });
  36266. /**
  36267. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36268. */
  36269. ShadowLight.prototype.computeTransformedInformation = function () {
  36270. if (this.parent && this.parent.getWorldMatrix) {
  36271. if (!this.transformedPosition) {
  36272. this.transformedPosition = BABYLON.Vector3.Zero();
  36273. }
  36274. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36275. // In case the direction is present.
  36276. if (this.direction) {
  36277. if (!this.transformedDirection) {
  36278. this.transformedDirection = BABYLON.Vector3.Zero();
  36279. }
  36280. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36281. }
  36282. return true;
  36283. }
  36284. return false;
  36285. };
  36286. /**
  36287. * Return the depth scale used for the shadow map.
  36288. */
  36289. ShadowLight.prototype.getDepthScale = function () {
  36290. return 50.0;
  36291. };
  36292. /**
  36293. * Returns the light direction (Vector3) for any passed face index.
  36294. */
  36295. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36296. return this.transformedDirection ? this.transformedDirection : this.direction;
  36297. };
  36298. /**
  36299. * Returns the DirectionalLight absolute position in the World.
  36300. */
  36301. ShadowLight.prototype.getAbsolutePosition = function () {
  36302. return this.transformedPosition ? this.transformedPosition : this.position;
  36303. };
  36304. /**
  36305. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36306. * Returns the updated DirectionalLight direction (Vector3).
  36307. */
  36308. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36309. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36310. return this.direction;
  36311. };
  36312. /**
  36313. * Returns the light rotation (Vector3).
  36314. */
  36315. ShadowLight.prototype.getRotation = function () {
  36316. this.direction.normalize();
  36317. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36318. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36319. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36320. };
  36321. /**
  36322. * Boolean : false by default.
  36323. */
  36324. ShadowLight.prototype.needCube = function () {
  36325. return false;
  36326. };
  36327. /**
  36328. * Specifies wether or not the projection matrix should be recomputed this frame.
  36329. */
  36330. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36331. return this._needProjectionMatrixCompute;
  36332. };
  36333. /**
  36334. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36335. */
  36336. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36337. this._needProjectionMatrixCompute = true;
  36338. };
  36339. /**
  36340. * Get the world matrix of the sahdow lights.
  36341. */
  36342. ShadowLight.prototype._getWorldMatrix = function () {
  36343. if (!this._worldMatrix) {
  36344. this._worldMatrix = BABYLON.Matrix.Identity();
  36345. }
  36346. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36347. return this._worldMatrix;
  36348. };
  36349. /**
  36350. * Gets the minZ used for shadow according to both the scene and the light.
  36351. * @param activeCamera
  36352. */
  36353. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36354. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36355. };
  36356. /**
  36357. * Gets the maxZ used for shadow according to both the scene and the light.
  36358. * @param activeCamera
  36359. */
  36360. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36361. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36362. };
  36363. /**
  36364. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36365. * Returns the light.
  36366. */
  36367. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36368. if (this.customProjectionMatrixBuilder) {
  36369. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36370. }
  36371. else {
  36372. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36373. }
  36374. return this;
  36375. };
  36376. __decorate([
  36377. BABYLON.serializeAsVector3()
  36378. ], ShadowLight.prototype, "position", void 0);
  36379. __decorate([
  36380. BABYLON.serializeAsVector3()
  36381. ], ShadowLight.prototype, "direction", null);
  36382. __decorate([
  36383. BABYLON.serialize()
  36384. ], ShadowLight.prototype, "shadowMinZ", null);
  36385. __decorate([
  36386. BABYLON.serialize()
  36387. ], ShadowLight.prototype, "shadowMaxZ", null);
  36388. return ShadowLight;
  36389. }(BABYLON.Light));
  36390. BABYLON.ShadowLight = ShadowLight;
  36391. })(BABYLON || (BABYLON = {}));
  36392. //# sourceMappingURL=babylon.shadowLight.js.map
  36393. var BABYLON;
  36394. (function (BABYLON) {
  36395. var PointLight = (function (_super) {
  36396. __extends(PointLight, _super);
  36397. /**
  36398. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36399. * A PointLight emits the light in every direction.
  36400. * It can cast shadows.
  36401. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36402. * ```javascript
  36403. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36404. * ```
  36405. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36406. */
  36407. function PointLight(name, position, scene) {
  36408. var _this = _super.call(this, name, scene) || this;
  36409. _this._shadowAngle = Math.PI / 2;
  36410. _this.position = position;
  36411. return _this;
  36412. }
  36413. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36414. /**
  36415. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36416. * This specifies what angle the shadow will use to be created.
  36417. *
  36418. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36419. */
  36420. get: function () {
  36421. return this._shadowAngle;
  36422. },
  36423. /**
  36424. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36425. * This specifies what angle the shadow will use to be created.
  36426. *
  36427. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36428. */
  36429. set: function (value) {
  36430. this._shadowAngle = value;
  36431. this.forceProjectionMatrixCompute();
  36432. },
  36433. enumerable: true,
  36434. configurable: true
  36435. });
  36436. Object.defineProperty(PointLight.prototype, "direction", {
  36437. get: function () {
  36438. return this._direction;
  36439. },
  36440. /**
  36441. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36442. */
  36443. set: function (value) {
  36444. var previousNeedCube = this.needCube();
  36445. this._direction = value;
  36446. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36447. this._shadowGenerator.recreateShadowMap();
  36448. }
  36449. },
  36450. enumerable: true,
  36451. configurable: true
  36452. });
  36453. /**
  36454. * Returns the string "PointLight"
  36455. */
  36456. PointLight.prototype.getClassName = function () {
  36457. return "PointLight";
  36458. };
  36459. /**
  36460. * Returns the integer 0.
  36461. */
  36462. PointLight.prototype.getTypeID = function () {
  36463. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36464. };
  36465. /**
  36466. * Specifies wether or not the shadowmap should be a cube texture.
  36467. */
  36468. PointLight.prototype.needCube = function () {
  36469. return !this.direction;
  36470. };
  36471. /**
  36472. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36473. */
  36474. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36475. if (this.direction) {
  36476. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36477. }
  36478. else {
  36479. switch (faceIndex) {
  36480. case 0:
  36481. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36482. case 1:
  36483. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36484. case 2:
  36485. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36486. case 3:
  36487. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36488. case 4:
  36489. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36490. case 5:
  36491. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36492. }
  36493. }
  36494. return BABYLON.Vector3.Zero();
  36495. };
  36496. /**
  36497. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36498. * - fov = PI / 2
  36499. * - aspect ratio : 1.0
  36500. * - z-near and far equal to the active camera minZ and maxZ.
  36501. * Returns the PointLight.
  36502. */
  36503. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36504. var activeCamera = this.getScene().activeCamera;
  36505. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36506. };
  36507. PointLight.prototype._buildUniformLayout = function () {
  36508. this._uniformBuffer.addUniform("vLightData", 4);
  36509. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36510. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36511. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36512. this._uniformBuffer.addUniform("depthValues", 2);
  36513. this._uniformBuffer.create();
  36514. };
  36515. /**
  36516. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36517. * Returns the PointLight.
  36518. */
  36519. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36520. if (this.computeTransformedInformation()) {
  36521. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36522. return this;
  36523. }
  36524. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36525. return this;
  36526. };
  36527. __decorate([
  36528. BABYLON.serialize()
  36529. ], PointLight.prototype, "shadowAngle", null);
  36530. return PointLight;
  36531. }(BABYLON.ShadowLight));
  36532. BABYLON.PointLight = PointLight;
  36533. })(BABYLON || (BABYLON = {}));
  36534. //# sourceMappingURL=babylon.pointLight.js.map
  36535. /// <reference path="babylon.light.ts" />
  36536. var BABYLON;
  36537. (function (BABYLON) {
  36538. var DirectionalLight = (function (_super) {
  36539. __extends(DirectionalLight, _super);
  36540. /**
  36541. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36542. * The directional light is emitted from everywhere in the given direction.
  36543. * It can cast shawdows.
  36544. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36545. */
  36546. function DirectionalLight(name, direction, scene) {
  36547. var _this = _super.call(this, name, scene) || this;
  36548. _this._shadowFrustumSize = 0;
  36549. _this._shadowOrthoScale = 0.5;
  36550. _this.autoUpdateExtends = true;
  36551. // Cache
  36552. _this._orthoLeft = Number.MAX_VALUE;
  36553. _this._orthoRight = Number.MIN_VALUE;
  36554. _this._orthoTop = Number.MIN_VALUE;
  36555. _this._orthoBottom = Number.MAX_VALUE;
  36556. _this.position = direction.scale(-1.0);
  36557. _this.direction = direction;
  36558. return _this;
  36559. }
  36560. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36561. /**
  36562. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36563. */
  36564. get: function () {
  36565. return this._shadowFrustumSize;
  36566. },
  36567. /**
  36568. * Specifies a fix frustum size for the shadow generation.
  36569. */
  36570. set: function (value) {
  36571. this._shadowFrustumSize = value;
  36572. this.forceProjectionMatrixCompute();
  36573. },
  36574. enumerable: true,
  36575. configurable: true
  36576. });
  36577. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36578. get: function () {
  36579. return this._shadowOrthoScale;
  36580. },
  36581. set: function (value) {
  36582. this._shadowOrthoScale = value;
  36583. this.forceProjectionMatrixCompute();
  36584. },
  36585. enumerable: true,
  36586. configurable: true
  36587. });
  36588. /**
  36589. * Returns the string "DirectionalLight".
  36590. */
  36591. DirectionalLight.prototype.getClassName = function () {
  36592. return "DirectionalLight";
  36593. };
  36594. /**
  36595. * Returns the integer 1.
  36596. */
  36597. DirectionalLight.prototype.getTypeID = function () {
  36598. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36599. };
  36600. /**
  36601. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36602. * Returns the DirectionalLight Shadow projection matrix.
  36603. */
  36604. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36605. if (this.shadowFrustumSize > 0) {
  36606. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36607. }
  36608. else {
  36609. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36610. }
  36611. };
  36612. /**
  36613. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36614. * Returns the DirectionalLight Shadow projection matrix.
  36615. */
  36616. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36617. var activeCamera = this.getScene().activeCamera;
  36618. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36619. };
  36620. /**
  36621. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36622. * Returns the DirectionalLight Shadow projection matrix.
  36623. */
  36624. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36625. var activeCamera = this.getScene().activeCamera;
  36626. // Check extends
  36627. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36628. var tempVector3 = BABYLON.Vector3.Zero();
  36629. this._orthoLeft = Number.MAX_VALUE;
  36630. this._orthoRight = Number.MIN_VALUE;
  36631. this._orthoTop = Number.MIN_VALUE;
  36632. this._orthoBottom = Number.MAX_VALUE;
  36633. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36634. var mesh = renderList[meshIndex];
  36635. if (!mesh) {
  36636. continue;
  36637. }
  36638. var boundingInfo = mesh.getBoundingInfo();
  36639. if (!boundingInfo) {
  36640. continue;
  36641. }
  36642. var boundingBox = boundingInfo.boundingBox;
  36643. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36644. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36645. if (tempVector3.x < this._orthoLeft)
  36646. this._orthoLeft = tempVector3.x;
  36647. if (tempVector3.y < this._orthoBottom)
  36648. this._orthoBottom = tempVector3.y;
  36649. if (tempVector3.x > this._orthoRight)
  36650. this._orthoRight = tempVector3.x;
  36651. if (tempVector3.y > this._orthoTop)
  36652. this._orthoTop = tempVector3.y;
  36653. }
  36654. }
  36655. }
  36656. var xOffset = this._orthoRight - this._orthoLeft;
  36657. var yOffset = this._orthoTop - this._orthoBottom;
  36658. 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);
  36659. };
  36660. DirectionalLight.prototype._buildUniformLayout = function () {
  36661. this._uniformBuffer.addUniform("vLightData", 4);
  36662. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36663. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36664. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36665. this._uniformBuffer.addUniform("depthValues", 2);
  36666. this._uniformBuffer.create();
  36667. };
  36668. /**
  36669. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36670. * Returns the DirectionalLight.
  36671. */
  36672. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36673. if (this.computeTransformedInformation()) {
  36674. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36675. return this;
  36676. }
  36677. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36678. return this;
  36679. };
  36680. /**
  36681. * Gets the minZ used for shadow according to both the scene and the light.
  36682. *
  36683. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36684. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36685. * @param activeCamera
  36686. */
  36687. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36688. return 1;
  36689. };
  36690. /**
  36691. * Gets the maxZ used for shadow according to both the scene and the light.
  36692. *
  36693. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36694. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36695. * @param activeCamera
  36696. */
  36697. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36698. return 1;
  36699. };
  36700. __decorate([
  36701. BABYLON.serialize()
  36702. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36703. __decorate([
  36704. BABYLON.serialize()
  36705. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36706. __decorate([
  36707. BABYLON.serialize()
  36708. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36709. return DirectionalLight;
  36710. }(BABYLON.ShadowLight));
  36711. BABYLON.DirectionalLight = DirectionalLight;
  36712. })(BABYLON || (BABYLON = {}));
  36713. //# sourceMappingURL=babylon.directionalLight.js.map
  36714. var BABYLON;
  36715. (function (BABYLON) {
  36716. var SpotLight = (function (_super) {
  36717. __extends(SpotLight, _super);
  36718. /**
  36719. * Creates a SpotLight object in the scene with the passed parameters :
  36720. * - `position` (Vector3) is the initial SpotLight position,
  36721. * - `direction` (Vector3) is the initial SpotLight direction,
  36722. * - `angle` (float, in radians) is the spot light cone angle,
  36723. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36724. * A spot light is a simply light oriented cone.
  36725. * It can cast shadows.
  36726. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36727. */
  36728. function SpotLight(name, position, direction, angle, exponent, scene) {
  36729. var _this = _super.call(this, name, scene) || this;
  36730. _this.position = position;
  36731. _this.direction = direction;
  36732. _this.angle = angle;
  36733. _this.exponent = exponent;
  36734. return _this;
  36735. }
  36736. Object.defineProperty(SpotLight.prototype, "angle", {
  36737. get: function () {
  36738. return this._angle;
  36739. },
  36740. set: function (value) {
  36741. this._angle = value;
  36742. this.forceProjectionMatrixCompute();
  36743. },
  36744. enumerable: true,
  36745. configurable: true
  36746. });
  36747. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36748. get: function () {
  36749. return this._shadowAngleScale;
  36750. },
  36751. /**
  36752. * Allows scaling the angle of the light for shadow generation only.
  36753. */
  36754. set: function (value) {
  36755. this._shadowAngleScale = value;
  36756. this.forceProjectionMatrixCompute();
  36757. },
  36758. enumerable: true,
  36759. configurable: true
  36760. });
  36761. /**
  36762. * Returns the string "SpotLight".
  36763. */
  36764. SpotLight.prototype.getClassName = function () {
  36765. return "SpotLight";
  36766. };
  36767. /**
  36768. * Returns the integer 2.
  36769. */
  36770. SpotLight.prototype.getTypeID = function () {
  36771. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36772. };
  36773. /**
  36774. * 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.
  36775. * Returns the SpotLight.
  36776. */
  36777. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36778. var activeCamera = this.getScene().activeCamera;
  36779. this._shadowAngleScale = this._shadowAngleScale || 1;
  36780. var angle = this._shadowAngleScale * this._angle;
  36781. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36782. };
  36783. SpotLight.prototype._buildUniformLayout = function () {
  36784. this._uniformBuffer.addUniform("vLightData", 4);
  36785. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36786. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36787. this._uniformBuffer.addUniform("vLightDirection", 3);
  36788. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36789. this._uniformBuffer.addUniform("depthValues", 2);
  36790. this._uniformBuffer.create();
  36791. };
  36792. /**
  36793. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36794. * Return the SpotLight.
  36795. */
  36796. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36797. var normalizeDirection;
  36798. if (this.computeTransformedInformation()) {
  36799. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36800. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36801. }
  36802. else {
  36803. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36804. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36805. }
  36806. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36807. return this;
  36808. };
  36809. __decorate([
  36810. BABYLON.serialize()
  36811. ], SpotLight.prototype, "angle", null);
  36812. __decorate([
  36813. BABYLON.serialize()
  36814. /**
  36815. * Allows scaling the angle of the light for shadow generation only.
  36816. */
  36817. ], SpotLight.prototype, "shadowAngleScale", null);
  36818. __decorate([
  36819. BABYLON.serialize()
  36820. ], SpotLight.prototype, "exponent", void 0);
  36821. return SpotLight;
  36822. }(BABYLON.ShadowLight));
  36823. BABYLON.SpotLight = SpotLight;
  36824. })(BABYLON || (BABYLON = {}));
  36825. //# sourceMappingURL=babylon.spotLight.js.map
  36826. var BABYLON;
  36827. (function (BABYLON) {
  36828. var MultiMaterial = (function (_super) {
  36829. __extends(MultiMaterial, _super);
  36830. function MultiMaterial(name, scene) {
  36831. var _this = _super.call(this, name, scene, true) || this;
  36832. scene.multiMaterials.push(_this);
  36833. _this.subMaterials = new Array();
  36834. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  36835. return _this;
  36836. }
  36837. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  36838. get: function () {
  36839. return this._subMaterials;
  36840. },
  36841. set: function (value) {
  36842. this._subMaterials = value;
  36843. this._hookArray(value);
  36844. },
  36845. enumerable: true,
  36846. configurable: true
  36847. });
  36848. MultiMaterial.prototype._hookArray = function (array) {
  36849. var _this = this;
  36850. var oldPush = array.push;
  36851. array.push = function () {
  36852. var items = [];
  36853. for (var _i = 0; _i < arguments.length; _i++) {
  36854. items[_i] = arguments[_i];
  36855. }
  36856. var result = oldPush.apply(array, items);
  36857. _this._markAllSubMeshesAsTexturesDirty();
  36858. return result;
  36859. };
  36860. var oldSplice = array.splice;
  36861. array.splice = function (index, deleteCount) {
  36862. var deleted = oldSplice.apply(array, [index, deleteCount]);
  36863. _this._markAllSubMeshesAsTexturesDirty();
  36864. return deleted;
  36865. };
  36866. };
  36867. // Properties
  36868. MultiMaterial.prototype.getSubMaterial = function (index) {
  36869. if (index < 0 || index >= this.subMaterials.length) {
  36870. return this.getScene().defaultMaterial;
  36871. }
  36872. return this.subMaterials[index];
  36873. };
  36874. MultiMaterial.prototype.getActiveTextures = function () {
  36875. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  36876. var _a;
  36877. };
  36878. // Methods
  36879. MultiMaterial.prototype.getClassName = function () {
  36880. return "MultiMaterial";
  36881. };
  36882. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36883. for (var index = 0; index < this.subMaterials.length; index++) {
  36884. var subMaterial = this.subMaterials[index];
  36885. if (subMaterial) {
  36886. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  36887. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  36888. return false;
  36889. }
  36890. continue;
  36891. }
  36892. if (!this.subMaterials[index].isReady(mesh)) {
  36893. return false;
  36894. }
  36895. }
  36896. }
  36897. return true;
  36898. };
  36899. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  36900. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  36901. for (var index = 0; index < this.subMaterials.length; index++) {
  36902. var subMaterial = null;
  36903. if (cloneChildren) {
  36904. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  36905. }
  36906. else {
  36907. subMaterial = this.subMaterials[index];
  36908. }
  36909. newMultiMaterial.subMaterials.push(subMaterial);
  36910. }
  36911. return newMultiMaterial;
  36912. };
  36913. MultiMaterial.prototype.serialize = function () {
  36914. var serializationObject = {};
  36915. serializationObject.name = this.name;
  36916. serializationObject.id = this.id;
  36917. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36918. serializationObject.materials = [];
  36919. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  36920. var subMat = this.subMaterials[matIndex];
  36921. if (subMat) {
  36922. serializationObject.materials.push(subMat.id);
  36923. }
  36924. else {
  36925. serializationObject.materials.push(null);
  36926. }
  36927. }
  36928. return serializationObject;
  36929. };
  36930. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36931. var scene = this.getScene();
  36932. if (!scene) {
  36933. return;
  36934. }
  36935. var index = scene.multiMaterials.indexOf(this);
  36936. if (index >= 0) {
  36937. scene.multiMaterials.splice(index, 1);
  36938. }
  36939. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36940. };
  36941. return MultiMaterial;
  36942. }(BABYLON.Material));
  36943. BABYLON.MultiMaterial = MultiMaterial;
  36944. })(BABYLON || (BABYLON = {}));
  36945. //# sourceMappingURL=babylon.multiMaterial.js.map
  36946. var BABYLON;
  36947. (function (BABYLON) {
  36948. var PBRMaterialDefines = (function (_super) {
  36949. __extends(PBRMaterialDefines, _super);
  36950. function PBRMaterialDefines() {
  36951. var _this = _super.call(this) || this;
  36952. _this.PBR = true;
  36953. _this.MAINUV1 = false;
  36954. _this.MAINUV2 = false;
  36955. _this.UV1 = false;
  36956. _this.UV2 = false;
  36957. _this.ALBEDO = false;
  36958. _this.ALBEDODIRECTUV = 0;
  36959. _this.VERTEXCOLOR = false;
  36960. _this.AMBIENT = false;
  36961. _this.AMBIENTDIRECTUV = 0;
  36962. _this.AMBIENTINGRAYSCALE = false;
  36963. _this.OPACITY = false;
  36964. _this.VERTEXALPHA = false;
  36965. _this.OPACITYDIRECTUV = 0;
  36966. _this.OPACITYRGB = false;
  36967. _this.ALPHATEST = false;
  36968. _this.ALPHABLEND = false;
  36969. _this.ALPHAFROMALBEDO = false;
  36970. _this.ALPHATESTVALUE = 0.5;
  36971. _this.SPECULAROVERALPHA = false;
  36972. _this.RADIANCEOVERALPHA = false;
  36973. _this.ALPHAFRESNEL = false;
  36974. _this.PREMULTIPLYALPHA = false;
  36975. _this.EMISSIVE = false;
  36976. _this.EMISSIVEDIRECTUV = 0;
  36977. _this.REFLECTIVITY = false;
  36978. _this.REFLECTIVITYDIRECTUV = 0;
  36979. _this.SPECULARTERM = false;
  36980. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36981. _this.MICROSURFACEAUTOMATIC = false;
  36982. _this.LODBASEDMICROSFURACE = false;
  36983. _this.MICROSURFACEMAP = false;
  36984. _this.MICROSURFACEMAPDIRECTUV = 0;
  36985. _this.METALLICWORKFLOW = false;
  36986. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36987. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36988. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36989. _this.AOSTOREINMETALMAPRED = false;
  36990. _this.ENVIRONMENTBRDF = false;
  36991. _this.NORMAL = false;
  36992. _this.TANGENT = false;
  36993. _this.BUMP = false;
  36994. _this.BUMPDIRECTUV = 0;
  36995. _this.PARALLAX = false;
  36996. _this.PARALLAXOCCLUSION = false;
  36997. _this.NORMALXYSCALE = true;
  36998. _this.LIGHTMAP = false;
  36999. _this.LIGHTMAPDIRECTUV = 0;
  37000. _this.USELIGHTMAPASSHADOWMAP = false;
  37001. _this.REFLECTION = false;
  37002. _this.REFLECTIONMAP_3D = false;
  37003. _this.REFLECTIONMAP_SPHERICAL = false;
  37004. _this.REFLECTIONMAP_PLANAR = false;
  37005. _this.REFLECTIONMAP_CUBIC = false;
  37006. _this.REFLECTIONMAP_PROJECTION = false;
  37007. _this.REFLECTIONMAP_SKYBOX = false;
  37008. _this.REFLECTIONMAP_EXPLICIT = false;
  37009. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37010. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37011. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37012. _this.INVERTCUBICMAP = false;
  37013. _this.USESPHERICALFROMREFLECTIONMAP = false;
  37014. _this.USESPHERICALINFRAGMENT = false;
  37015. _this.REFLECTIONMAP_OPPOSITEZ = false;
  37016. _this.LODINREFLECTIONALPHA = false;
  37017. _this.GAMMAREFLECTION = false;
  37018. _this.REFRACTION = false;
  37019. _this.REFRACTIONMAP_3D = false;
  37020. _this.REFRACTIONMAP_OPPOSITEZ = false;
  37021. _this.LODINREFRACTIONALPHA = false;
  37022. _this.GAMMAREFRACTION = false;
  37023. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  37024. _this.INSTANCES = false;
  37025. _this.NUM_BONE_INFLUENCERS = 0;
  37026. _this.BonesPerMesh = 0;
  37027. _this.MORPHTARGETS = false;
  37028. _this.MORPHTARGETS_NORMAL = false;
  37029. _this.MORPHTARGETS_TANGENT = false;
  37030. _this.NUM_MORPH_INFLUENCERS = 0;
  37031. _this.IMAGEPROCESSING = false;
  37032. _this.VIGNETTE = false;
  37033. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37034. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37035. _this.TONEMAPPING = false;
  37036. _this.CONTRAST = false;
  37037. _this.COLORCURVES = false;
  37038. _this.COLORGRADING = false;
  37039. _this.SAMPLER3DGREENDEPTH = false;
  37040. _this.SAMPLER3DBGRMAP = false;
  37041. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  37042. _this.EXPOSURE = false;
  37043. _this.USEPHYSICALLIGHTFALLOFF = false;
  37044. _this.TWOSIDEDLIGHTING = false;
  37045. _this.SHADOWFLOAT = false;
  37046. _this.USERIGHTHANDEDSYSTEM = false;
  37047. _this.CLIPPLANE = false;
  37048. _this.POINTSIZE = false;
  37049. _this.FOG = false;
  37050. _this.LOGARITHMICDEPTH = false;
  37051. _this.FORCENORMALFORWARD = false;
  37052. _this.rebuild();
  37053. return _this;
  37054. }
  37055. PBRMaterialDefines.prototype.reset = function () {
  37056. _super.prototype.reset.call(this);
  37057. this.ALPHATESTVALUE = 0.5;
  37058. this.PBR = true;
  37059. };
  37060. return PBRMaterialDefines;
  37061. }(BABYLON.MaterialDefines));
  37062. /**
  37063. * The Physically based material base class of BJS.
  37064. *
  37065. * This offers the main features of a standard PBR material.
  37066. * For more information, please refer to the documentation :
  37067. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37068. */
  37069. var PBRBaseMaterial = (function (_super) {
  37070. __extends(PBRBaseMaterial, _super);
  37071. /**
  37072. * Instantiates a new PBRMaterial instance.
  37073. *
  37074. * @param name The material name
  37075. * @param scene The scene the material will be use in.
  37076. */
  37077. function PBRBaseMaterial(name, scene) {
  37078. var _this = _super.call(this, name, scene) || this;
  37079. /**
  37080. * Intensity of the direct lights e.g. the four lights available in your scene.
  37081. * This impacts both the direct diffuse and specular highlights.
  37082. */
  37083. _this._directIntensity = 1.0;
  37084. /**
  37085. * Intensity of the emissive part of the material.
  37086. * This helps controlling the emissive effect without modifying the emissive color.
  37087. */
  37088. _this._emissiveIntensity = 1.0;
  37089. /**
  37090. * Intensity of the environment e.g. how much the environment will light the object
  37091. * either through harmonics for rough material or through the refelction for shiny ones.
  37092. */
  37093. _this._environmentIntensity = 1.0;
  37094. /**
  37095. * This is a special control allowing the reduction of the specular highlights coming from the
  37096. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37097. */
  37098. _this._specularIntensity = 1.0;
  37099. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  37100. /**
  37101. * Debug Control allowing disabling the bump map on this material.
  37102. */
  37103. _this._disableBumpMap = false;
  37104. /**
  37105. * AKA Occlusion Texture Intensity in other nomenclature.
  37106. */
  37107. _this._ambientTextureStrength = 1.0;
  37108. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  37109. /**
  37110. * AKA Diffuse Color in other nomenclature.
  37111. */
  37112. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  37113. /**
  37114. * AKA Specular Color in other nomenclature.
  37115. */
  37116. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37117. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  37118. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  37119. /**
  37120. * AKA Glossiness in other nomenclature.
  37121. */
  37122. _this._microSurface = 0.9;
  37123. /**
  37124. * source material index of refraction (IOR)' / 'destination material IOR.
  37125. */
  37126. _this._indexOfRefraction = 0.66;
  37127. /**
  37128. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37129. */
  37130. _this._invertRefractionY = false;
  37131. /**
  37132. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37133. * Materials half opaque for instance using refraction could benefit from this control.
  37134. */
  37135. _this._linkRefractionWithTransparency = false;
  37136. _this._useLightmapAsShadowmap = false;
  37137. /**
  37138. * Specifies that the alpha is coming form the albedo channel alpha channel.
  37139. */
  37140. _this._useAlphaFromAlbedoTexture = false;
  37141. /**
  37142. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37143. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37144. */
  37145. _this._useSpecularOverAlpha = true;
  37146. /**
  37147. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37148. */
  37149. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  37150. /**
  37151. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37152. */
  37153. _this._useRoughnessFromMetallicTextureAlpha = true;
  37154. /**
  37155. * Specifies if the metallic texture contains the roughness information in its green channel.
  37156. */
  37157. _this._useRoughnessFromMetallicTextureGreen = false;
  37158. /**
  37159. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37160. */
  37161. _this._useMetallnessFromMetallicTextureBlue = false;
  37162. /**
  37163. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37164. */
  37165. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  37166. /**
  37167. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37168. */
  37169. _this._useAmbientInGrayScale = false;
  37170. /**
  37171. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37172. * The material will try to infer what glossiness each pixel should be.
  37173. */
  37174. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  37175. /**
  37176. * BJS is using an harcoded light falloff based on a manually sets up range.
  37177. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37178. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37179. */
  37180. _this._usePhysicalLightFalloff = true;
  37181. /**
  37182. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37183. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37184. */
  37185. _this._useRadianceOverAlpha = true;
  37186. /**
  37187. * Allows using the bump map in parallax mode.
  37188. */
  37189. _this._useParallax = false;
  37190. /**
  37191. * Allows using the bump map in parallax occlusion mode.
  37192. */
  37193. _this._useParallaxOcclusion = false;
  37194. /**
  37195. * Controls the scale bias of the parallax mode.
  37196. */
  37197. _this._parallaxScaleBias = 0.05;
  37198. /**
  37199. * If sets to true, disables all the lights affecting the material.
  37200. */
  37201. _this._disableLighting = false;
  37202. /**
  37203. * Number of Simultaneous lights allowed on the material.
  37204. */
  37205. _this._maxSimultaneousLights = 4;
  37206. /**
  37207. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  37208. */
  37209. _this._invertNormalMapX = false;
  37210. /**
  37211. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  37212. */
  37213. _this._invertNormalMapY = false;
  37214. /**
  37215. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37216. */
  37217. _this._twoSidedLighting = false;
  37218. /**
  37219. * Defines the alpha limits in alpha test mode.
  37220. */
  37221. _this._alphaCutOff = 0.4;
  37222. /**
  37223. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37224. */
  37225. _this._forceAlphaTest = false;
  37226. /**
  37227. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  37228. * in your scene composition.
  37229. */
  37230. _this._preMultiplyAlpha = false;
  37231. /**
  37232. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37233. * And/Or occlude the blended part.
  37234. */
  37235. _this._useAlphaFresnel = false;
  37236. /**
  37237. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  37238. * from cos thetav and roughness:
  37239. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  37240. */
  37241. _this._environmentBRDFTexture = null;
  37242. /**
  37243. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37244. */
  37245. _this._forceIrradianceInFragment = false;
  37246. /**
  37247. * Force normal to face away from face.
  37248. * (Temporary internal fix to remove before 3.1)
  37249. */
  37250. _this._forceNormalForward = false;
  37251. _this._renderTargets = new BABYLON.SmartArray(16);
  37252. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  37253. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37254. _this._tempColor = new BABYLON.Color3();
  37255. // Setup the default processing configuration to the scene.
  37256. _this._attachImageProcessingConfiguration(null);
  37257. _this.getRenderTargetTextures = function () {
  37258. _this._renderTargets.reset();
  37259. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37260. _this._renderTargets.push(_this._reflectionTexture);
  37261. }
  37262. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37263. _this._renderTargets.push(_this._refractionTexture);
  37264. }
  37265. return _this._renderTargets;
  37266. };
  37267. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37268. return _this;
  37269. }
  37270. /**
  37271. * Attaches a new image processing configuration to the PBR Material.
  37272. * @param configuration
  37273. */
  37274. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37275. var _this = this;
  37276. if (configuration === this._imageProcessingConfiguration) {
  37277. return;
  37278. }
  37279. // Detaches observer.
  37280. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37281. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37282. }
  37283. // Pick the scene configuration if needed.
  37284. if (!configuration) {
  37285. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37286. }
  37287. else {
  37288. this._imageProcessingConfiguration = configuration;
  37289. }
  37290. // Attaches observer.
  37291. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37292. _this._markAllSubMeshesAsImageProcessingDirty();
  37293. });
  37294. };
  37295. PBRBaseMaterial.prototype.getClassName = function () {
  37296. return "PBRBaseMaterial";
  37297. };
  37298. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  37299. get: function () {
  37300. return this._useLogarithmicDepth;
  37301. },
  37302. set: function (value) {
  37303. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37304. },
  37305. enumerable: true,
  37306. configurable: true
  37307. });
  37308. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  37309. if (this._linkRefractionWithTransparency) {
  37310. return false;
  37311. }
  37312. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  37313. };
  37314. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  37315. if (this._forceAlphaTest) {
  37316. return true;
  37317. }
  37318. if (this._linkRefractionWithTransparency) {
  37319. return false;
  37320. }
  37321. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  37322. };
  37323. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37324. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  37325. };
  37326. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  37327. return this._albedoTexture;
  37328. };
  37329. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37330. if (this.isFrozen) {
  37331. if (this._wasPreviouslyReady) {
  37332. return true;
  37333. }
  37334. }
  37335. if (!subMesh._materialDefines) {
  37336. subMesh._materialDefines = new PBRMaterialDefines();
  37337. }
  37338. var scene = this.getScene();
  37339. var defines = subMesh._materialDefines;
  37340. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37341. if (defines._renderId === scene.getRenderId()) {
  37342. return true;
  37343. }
  37344. }
  37345. var engine = scene.getEngine();
  37346. // Lights
  37347. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37348. defines._needNormals = true;
  37349. // Textures
  37350. if (defines._areTexturesDirty) {
  37351. defines._needUVs = false;
  37352. if (scene.texturesEnabled) {
  37353. if (scene.getEngine().getCaps().textureLOD) {
  37354. defines.LODBASEDMICROSFURACE = true;
  37355. }
  37356. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37357. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  37358. return false;
  37359. }
  37360. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  37361. }
  37362. else {
  37363. defines.ALBEDO = false;
  37364. }
  37365. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37366. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37367. return false;
  37368. }
  37369. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37370. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  37371. }
  37372. else {
  37373. defines.AMBIENT = false;
  37374. }
  37375. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37376. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37377. return false;
  37378. }
  37379. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37380. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37381. }
  37382. else {
  37383. defines.OPACITY = false;
  37384. }
  37385. var reflectionTexture = this._getReflectionTexture();
  37386. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37387. if (!reflectionTexture.isReadyOrNotBlocking()) {
  37388. return false;
  37389. }
  37390. defines.REFLECTION = true;
  37391. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  37392. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  37393. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37394. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  37395. defines.INVERTCUBICMAP = true;
  37396. }
  37397. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  37398. switch (reflectionTexture.coordinatesMode) {
  37399. case BABYLON.Texture.CUBIC_MODE:
  37400. case BABYLON.Texture.INVCUBIC_MODE:
  37401. defines.REFLECTIONMAP_CUBIC = true;
  37402. break;
  37403. case BABYLON.Texture.EXPLICIT_MODE:
  37404. defines.REFLECTIONMAP_EXPLICIT = true;
  37405. break;
  37406. case BABYLON.Texture.PLANAR_MODE:
  37407. defines.REFLECTIONMAP_PLANAR = true;
  37408. break;
  37409. case BABYLON.Texture.PROJECTION_MODE:
  37410. defines.REFLECTIONMAP_PROJECTION = true;
  37411. break;
  37412. case BABYLON.Texture.SKYBOX_MODE:
  37413. defines.REFLECTIONMAP_SKYBOX = true;
  37414. break;
  37415. case BABYLON.Texture.SPHERICAL_MODE:
  37416. defines.REFLECTIONMAP_SPHERICAL = true;
  37417. break;
  37418. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37419. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37420. break;
  37421. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37422. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37423. break;
  37424. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37425. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37426. break;
  37427. }
  37428. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37429. if (reflectionTexture.sphericalPolynomial) {
  37430. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37431. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37432. defines.USESPHERICALINFRAGMENT = true;
  37433. }
  37434. }
  37435. }
  37436. }
  37437. else {
  37438. defines.REFLECTION = false;
  37439. defines.REFLECTIONMAP_3D = false;
  37440. defines.REFLECTIONMAP_SPHERICAL = false;
  37441. defines.REFLECTIONMAP_PLANAR = false;
  37442. defines.REFLECTIONMAP_CUBIC = false;
  37443. defines.REFLECTIONMAP_PROJECTION = false;
  37444. defines.REFLECTIONMAP_SKYBOX = false;
  37445. defines.REFLECTIONMAP_EXPLICIT = false;
  37446. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37447. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37448. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37449. defines.INVERTCUBICMAP = false;
  37450. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37451. defines.USESPHERICALINFRAGMENT = false;
  37452. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37453. defines.LODINREFLECTIONALPHA = false;
  37454. defines.GAMMAREFLECTION = false;
  37455. }
  37456. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37457. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37458. return false;
  37459. }
  37460. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37461. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37462. }
  37463. else {
  37464. defines.LIGHTMAP = false;
  37465. }
  37466. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37467. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37468. return false;
  37469. }
  37470. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37471. }
  37472. else {
  37473. defines.EMISSIVE = false;
  37474. }
  37475. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37476. if (this._metallicTexture) {
  37477. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37478. return false;
  37479. }
  37480. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37481. defines.METALLICWORKFLOW = true;
  37482. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37483. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37484. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37485. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37486. }
  37487. else if (this._reflectivityTexture) {
  37488. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37489. return false;
  37490. }
  37491. defines.METALLICWORKFLOW = false;
  37492. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37493. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37494. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37495. }
  37496. else {
  37497. defines.METALLICWORKFLOW = false;
  37498. defines.REFLECTIVITY = false;
  37499. }
  37500. if (this._microSurfaceTexture) {
  37501. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37502. return false;
  37503. }
  37504. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37505. }
  37506. else {
  37507. defines.MICROSURFACEMAP = false;
  37508. }
  37509. }
  37510. else {
  37511. defines.REFLECTIVITY = false;
  37512. defines.MICROSURFACEMAP = false;
  37513. }
  37514. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37515. // Bump texure can not be none blocking.
  37516. if (!this._bumpTexture.isReady()) {
  37517. return false;
  37518. }
  37519. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37520. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37521. defines.PARALLAX = true;
  37522. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37523. }
  37524. else {
  37525. defines.PARALLAX = false;
  37526. }
  37527. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  37528. }
  37529. else {
  37530. defines.BUMP = false;
  37531. }
  37532. var refractionTexture = this._getRefractionTexture();
  37533. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37534. if (!refractionTexture.isReadyOrNotBlocking()) {
  37535. return false;
  37536. }
  37537. defines.REFRACTION = true;
  37538. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37539. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37540. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  37541. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37542. if (this._linkRefractionWithTransparency) {
  37543. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37544. }
  37545. }
  37546. else {
  37547. defines.REFRACTION = false;
  37548. }
  37549. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37550. // This is blocking.
  37551. if (!this._environmentBRDFTexture.isReady()) {
  37552. return false;
  37553. }
  37554. defines.ENVIRONMENTBRDF = true;
  37555. }
  37556. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37557. defines.ALPHAFROMALBEDO = true;
  37558. }
  37559. }
  37560. if (this._useSpecularOverAlpha) {
  37561. defines.SPECULAROVERALPHA = true;
  37562. }
  37563. if (this._usePhysicalLightFalloff) {
  37564. defines.USEPHYSICALLIGHTFALLOFF = true;
  37565. }
  37566. if (this._useRadianceOverAlpha) {
  37567. defines.RADIANCEOVERALPHA = true;
  37568. }
  37569. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37570. defines.METALLICWORKFLOW = true;
  37571. }
  37572. if (!this.backFaceCulling && this._twoSidedLighting) {
  37573. defines.TWOSIDEDLIGHTING = true;
  37574. }
  37575. defines.ALPHATESTVALUE = this._alphaCutOff;
  37576. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  37577. defines.ALPHABLEND = this.needAlphaBlending();
  37578. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  37579. }
  37580. if (defines._areImageProcessingDirty) {
  37581. if (!this._imageProcessingConfiguration.isReady()) {
  37582. return false;
  37583. }
  37584. this._imageProcessingConfiguration.prepareDefines(defines);
  37585. }
  37586. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37587. // Misc.
  37588. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37589. // Values that need to be evaluated on every frame
  37590. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  37591. // Attribs
  37592. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  37593. if (mesh) {
  37594. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37595. mesh.createNormals(true);
  37596. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  37597. }
  37598. }
  37599. }
  37600. // Get correct effect
  37601. if (defines.isDirty) {
  37602. defines.markAsProcessed();
  37603. scene.resetCachedMaterial();
  37604. // Fallbacks
  37605. var fallbacks = new BABYLON.EffectFallbacks();
  37606. if (defines.ENVIRONMENTBRDF) {
  37607. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  37608. }
  37609. if (defines.REFLECTION) {
  37610. fallbacks.addFallback(0, "REFLECTION");
  37611. }
  37612. if (defines.REFRACTION) {
  37613. fallbacks.addFallback(0, "REFRACTION");
  37614. }
  37615. if (defines.REFLECTIVITY) {
  37616. fallbacks.addFallback(0, "REFLECTIVITY");
  37617. }
  37618. if (defines.BUMP) {
  37619. fallbacks.addFallback(0, "BUMP");
  37620. }
  37621. if (defines.PARALLAX) {
  37622. fallbacks.addFallback(1, "PARALLAX");
  37623. }
  37624. if (defines.PARALLAXOCCLUSION) {
  37625. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37626. }
  37627. if (defines.SPECULAROVERALPHA) {
  37628. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37629. }
  37630. if (defines.FOG) {
  37631. fallbacks.addFallback(1, "FOG");
  37632. }
  37633. if (defines.POINTSIZE) {
  37634. fallbacks.addFallback(0, "POINTSIZE");
  37635. }
  37636. if (defines.LOGARITHMICDEPTH) {
  37637. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37638. }
  37639. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37640. if (defines.SPECULARTERM) {
  37641. fallbacks.addFallback(0, "SPECULARTERM");
  37642. }
  37643. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37644. fallbacks.addCPUSkinningFallback(0, mesh);
  37645. }
  37646. //Attributes
  37647. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37648. if (defines.NORMAL) {
  37649. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37650. }
  37651. if (defines.TANGENT) {
  37652. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37653. }
  37654. if (defines.UV1) {
  37655. attribs.push(BABYLON.VertexBuffer.UVKind);
  37656. }
  37657. if (defines.UV2) {
  37658. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37659. }
  37660. if (defines.VERTEXCOLOR) {
  37661. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37662. }
  37663. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37664. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37665. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37666. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37667. "vFogInfos", "vFogColor", "pointSize",
  37668. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37669. "mBones",
  37670. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37671. "vLightingIntensity",
  37672. "logarithmicDepthConstant",
  37673. "vSphericalX", "vSphericalY", "vSphericalZ",
  37674. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37675. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37676. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37677. "vNormalReoderParams"
  37678. ];
  37679. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37680. "bumpSampler", "lightmapSampler", "opacitySampler",
  37681. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37682. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37683. "microSurfaceSampler", "environmentBrdfSampler"];
  37684. var uniformBuffers = ["Material", "Scene"];
  37685. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37686. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37687. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37688. uniformsNames: uniforms,
  37689. uniformBuffersNames: uniformBuffers,
  37690. samplers: samplers,
  37691. defines: defines,
  37692. maxSimultaneousLights: this._maxSimultaneousLights
  37693. });
  37694. var onCompiled = function (effect) {
  37695. if (this.onCompiled) {
  37696. this.onCompiled(effect);
  37697. }
  37698. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37699. }.bind(this);
  37700. var join = defines.toString();
  37701. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37702. attributes: attribs,
  37703. uniformsNames: uniforms,
  37704. uniformBuffersNames: uniformBuffers,
  37705. samplers: samplers,
  37706. defines: join,
  37707. fallbacks: fallbacks,
  37708. onCompiled: onCompiled,
  37709. onError: this.onError,
  37710. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37711. }, engine), defines);
  37712. this.buildUniformLayout();
  37713. }
  37714. if (!subMesh.effect.isReady()) {
  37715. return false;
  37716. }
  37717. defines._renderId = scene.getRenderId();
  37718. this._wasPreviouslyReady = true;
  37719. return true;
  37720. };
  37721. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37722. // Order is important !
  37723. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37724. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37725. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37726. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37727. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37728. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37729. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37730. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37731. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37732. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37733. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37734. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37735. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37736. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37737. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37738. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37739. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37740. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37741. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  37742. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37743. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37744. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37745. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37746. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37747. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37748. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37749. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37750. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37751. this._uniformBuffer.addUniform("pointSize", 1);
  37752. this._uniformBuffer.create();
  37753. };
  37754. PBRBaseMaterial.prototype.unbind = function () {
  37755. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37756. this._uniformBuffer.setTexture("reflectionSampler", null);
  37757. }
  37758. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37759. this._uniformBuffer.setTexture("refractionSampler", null);
  37760. }
  37761. _super.prototype.unbind.call(this);
  37762. };
  37763. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37764. this._activeEffect.setMatrix("world", world);
  37765. };
  37766. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37767. var scene = this.getScene();
  37768. var defines = subMesh._materialDefines;
  37769. if (!defines) {
  37770. return;
  37771. }
  37772. var effect = subMesh.effect;
  37773. this._activeEffect = effect;
  37774. // Matrices
  37775. this.bindOnlyWorldMatrix(world);
  37776. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37777. // Bones
  37778. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37779. if (mustRebind) {
  37780. this._uniformBuffer.bindToEffect(effect, "Material");
  37781. this.bindViewProjection(effect);
  37782. var reflectionTexture = this._getReflectionTexture();
  37783. var refractionTexture = this._getRefractionTexture();
  37784. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37785. // Texture uniforms
  37786. if (scene.texturesEnabled) {
  37787. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37788. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37789. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37790. }
  37791. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37792. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37793. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37794. }
  37795. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37796. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37797. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37798. }
  37799. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37800. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37801. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37802. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37803. var polynomials = reflectionTexture.sphericalPolynomial;
  37804. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37805. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37806. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37807. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37808. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37809. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37810. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37811. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37812. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37813. }
  37814. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37815. }
  37816. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37817. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37818. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37819. }
  37820. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37821. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37822. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37823. }
  37824. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37825. if (this._metallicTexture) {
  37826. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37827. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37828. }
  37829. else if (this._reflectivityTexture) {
  37830. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37831. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37832. }
  37833. if (this._microSurfaceTexture) {
  37834. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37835. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37836. }
  37837. }
  37838. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37839. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37840. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37841. if (scene._mirroredCameraPosition) {
  37842. 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);
  37843. }
  37844. else {
  37845. 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);
  37846. }
  37847. }
  37848. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37849. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37850. var depth = 1.0;
  37851. if (!refractionTexture.isCube) {
  37852. if (refractionTexture.depth) {
  37853. depth = refractionTexture.depth;
  37854. }
  37855. }
  37856. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37857. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37858. }
  37859. }
  37860. // Point size
  37861. if (this.pointsCloud) {
  37862. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37863. }
  37864. // Colors
  37865. if (defines.METALLICWORKFLOW) {
  37866. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37867. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37868. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37869. }
  37870. else {
  37871. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37872. }
  37873. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37874. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37875. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37876. // Misc
  37877. this._lightingInfos.x = this._directIntensity;
  37878. this._lightingInfos.y = this._emissiveIntensity;
  37879. this._lightingInfos.z = this._environmentIntensity;
  37880. this._lightingInfos.w = this._specularIntensity;
  37881. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37882. }
  37883. // Textures
  37884. if (scene.texturesEnabled) {
  37885. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37886. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37887. }
  37888. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37889. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37890. }
  37891. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37892. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37893. }
  37894. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37895. if (defines.LODBASEDMICROSFURACE) {
  37896. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37897. }
  37898. else {
  37899. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37900. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37901. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37902. }
  37903. }
  37904. if (defines.ENVIRONMENTBRDF) {
  37905. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37906. }
  37907. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37908. if (defines.LODBASEDMICROSFURACE) {
  37909. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37910. }
  37911. else {
  37912. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37913. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37914. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37915. }
  37916. }
  37917. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37918. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37919. }
  37920. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37921. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37922. }
  37923. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37924. if (this._metallicTexture) {
  37925. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37926. }
  37927. else if (this._reflectivityTexture) {
  37928. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37929. }
  37930. if (this._microSurfaceTexture) {
  37931. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37932. }
  37933. }
  37934. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37935. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37936. }
  37937. }
  37938. // Clip plane
  37939. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37940. // Colors
  37941. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37942. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  37943. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  37944. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37945. }
  37946. if (mustRebind || !this.isFrozen) {
  37947. // Lights
  37948. if (scene.lightsEnabled && !this._disableLighting) {
  37949. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37950. }
  37951. // View
  37952. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37953. this.bindView(effect);
  37954. }
  37955. // Fog
  37956. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37957. // Morph targets
  37958. if (defines.NUM_MORPH_INFLUENCERS) {
  37959. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37960. }
  37961. // image processing
  37962. this._imageProcessingConfiguration.bind(this._activeEffect);
  37963. // Log. depth
  37964. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37965. }
  37966. this._uniformBuffer.update();
  37967. this._afterBind(mesh);
  37968. scene = null;
  37969. };
  37970. PBRBaseMaterial.prototype.getAnimatables = function () {
  37971. var results = [];
  37972. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37973. results.push(this._albedoTexture);
  37974. }
  37975. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37976. results.push(this._ambientTexture);
  37977. }
  37978. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37979. results.push(this._opacityTexture);
  37980. }
  37981. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37982. results.push(this._reflectionTexture);
  37983. }
  37984. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37985. results.push(this._emissiveTexture);
  37986. }
  37987. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37988. results.push(this._metallicTexture);
  37989. }
  37990. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37991. results.push(this._reflectivityTexture);
  37992. }
  37993. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37994. results.push(this._bumpTexture);
  37995. }
  37996. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37997. results.push(this._lightmapTexture);
  37998. }
  37999. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  38000. results.push(this._refractionTexture);
  38001. }
  38002. return results;
  38003. };
  38004. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  38005. if (this._reflectionTexture) {
  38006. return this._reflectionTexture;
  38007. }
  38008. return this.getScene().environmentTexture;
  38009. };
  38010. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  38011. if (this._refractionTexture) {
  38012. return this._refractionTexture;
  38013. }
  38014. if (this._linkRefractionWithTransparency) {
  38015. return this.getScene().environmentTexture;
  38016. }
  38017. return null;
  38018. };
  38019. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38020. if (forceDisposeTextures) {
  38021. if (this._albedoTexture) {
  38022. this._albedoTexture.dispose();
  38023. }
  38024. if (this._ambientTexture) {
  38025. this._ambientTexture.dispose();
  38026. }
  38027. if (this._opacityTexture) {
  38028. this._opacityTexture.dispose();
  38029. }
  38030. if (this._reflectionTexture) {
  38031. this._reflectionTexture.dispose();
  38032. }
  38033. if (this._environmentBRDFTexture) {
  38034. this._environmentBRDFTexture.dispose();
  38035. }
  38036. if (this._emissiveTexture) {
  38037. this._emissiveTexture.dispose();
  38038. }
  38039. if (this._metallicTexture) {
  38040. this._metallicTexture.dispose();
  38041. }
  38042. if (this._reflectivityTexture) {
  38043. this._reflectivityTexture.dispose();
  38044. }
  38045. if (this._bumpTexture) {
  38046. this._bumpTexture.dispose();
  38047. }
  38048. if (this._lightmapTexture) {
  38049. this._lightmapTexture.dispose();
  38050. }
  38051. if (this._refractionTexture) {
  38052. this._refractionTexture.dispose();
  38053. }
  38054. }
  38055. this._renderTargets.dispose();
  38056. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38057. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38058. }
  38059. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38060. };
  38061. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  38062. __decorate([
  38063. BABYLON.serializeAsImageProcessingConfiguration()
  38064. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  38065. __decorate([
  38066. BABYLON.serialize()
  38067. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  38068. return PBRBaseMaterial;
  38069. }(BABYLON.PushMaterial));
  38070. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  38071. })(BABYLON || (BABYLON = {}));
  38072. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  38073. var BABYLON;
  38074. (function (BABYLON) {
  38075. var Internals;
  38076. (function (Internals) {
  38077. /**
  38078. * The Physically based simple base material of BJS.
  38079. *
  38080. * This enables better naming and convention enforcements on top of the pbrMaterial.
  38081. * It is used as the base class for both the specGloss and metalRough conventions.
  38082. */
  38083. var PBRBaseSimpleMaterial = (function (_super) {
  38084. __extends(PBRBaseSimpleMaterial, _super);
  38085. /**
  38086. * Instantiates a new PBRMaterial instance.
  38087. *
  38088. * @param name The material name
  38089. * @param scene The scene the material will be use in.
  38090. */
  38091. function PBRBaseSimpleMaterial(name, scene) {
  38092. var _this = _super.call(this, name, scene) || this;
  38093. /**
  38094. * Number of Simultaneous lights allowed on the material.
  38095. */
  38096. _this.maxSimultaneousLights = 4;
  38097. /**
  38098. * If sets to true, disables all the lights affecting the material.
  38099. */
  38100. _this.disableLighting = false;
  38101. /**
  38102. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38103. */
  38104. _this.invertNormalMapX = false;
  38105. /**
  38106. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38107. */
  38108. _this.invertNormalMapY = false;
  38109. /**
  38110. * Emissivie color used to self-illuminate the model.
  38111. */
  38112. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38113. /**
  38114. * Occlusion Channel Strenght.
  38115. */
  38116. _this.occlusionStrength = 1.0;
  38117. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38118. _this._useAmbientInGrayScale = true;
  38119. return _this;
  38120. }
  38121. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  38122. /**
  38123. * Gets the current transparency mode.
  38124. */
  38125. get: function () {
  38126. return this._transparencyMode;
  38127. },
  38128. /**
  38129. * Sets the transparency mode of the material.
  38130. */
  38131. set: function (value) {
  38132. if (this._transparencyMode === value) {
  38133. return;
  38134. }
  38135. this._transparencyMode = value;
  38136. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  38137. this._forceAlphaTest = true;
  38138. }
  38139. else {
  38140. this._forceAlphaTest = false;
  38141. }
  38142. this._markAllSubMeshesAsTexturesDirty();
  38143. },
  38144. enumerable: true,
  38145. configurable: true
  38146. });
  38147. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  38148. /**
  38149. * Gets the current double sided mode.
  38150. */
  38151. get: function () {
  38152. return this._twoSidedLighting;
  38153. },
  38154. /**
  38155. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38156. */
  38157. set: function (value) {
  38158. if (this._twoSidedLighting === value) {
  38159. return;
  38160. }
  38161. this._twoSidedLighting = value;
  38162. this.backFaceCulling = !value;
  38163. this._markAllSubMeshesAsTexturesDirty();
  38164. },
  38165. enumerable: true,
  38166. configurable: true
  38167. });
  38168. /**
  38169. * Specifies wether or not the alpha value of the albedo texture should be used.
  38170. */
  38171. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38172. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38173. };
  38174. /**
  38175. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  38176. */
  38177. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  38178. if (this._linkRefractionWithTransparency) {
  38179. return false;
  38180. }
  38181. return (this.alpha < 1.0) ||
  38182. (this._shouldUseAlphaFromAlbedoTexture() &&
  38183. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  38184. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  38185. };
  38186. /**
  38187. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  38188. */
  38189. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  38190. if (this._linkRefractionWithTransparency) {
  38191. return false;
  38192. }
  38193. return this._shouldUseAlphaFromAlbedoTexture() &&
  38194. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  38195. };
  38196. /**
  38197. * Return the active textures of the material.
  38198. */
  38199. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  38200. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38201. if (this.environmentTexture) {
  38202. activeTextures.push(this.environmentTexture);
  38203. }
  38204. if (this.normalTexture) {
  38205. activeTextures.push(this.normalTexture);
  38206. }
  38207. if (this.emissiveTexture) {
  38208. activeTextures.push(this.emissiveTexture);
  38209. }
  38210. if (this.occlusionTexture) {
  38211. activeTextures.push(this.occlusionTexture);
  38212. }
  38213. return activeTextures;
  38214. };
  38215. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  38216. return "PBRBaseSimpleMaterial";
  38217. };
  38218. __decorate([
  38219. BABYLON.serialize(),
  38220. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38221. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  38222. __decorate([
  38223. BABYLON.serialize(),
  38224. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38225. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  38226. __decorate([
  38227. BABYLON.serializeAsTexture(),
  38228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  38229. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  38230. __decorate([
  38231. BABYLON.serialize(),
  38232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38233. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  38234. __decorate([
  38235. BABYLON.serialize(),
  38236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38237. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  38238. __decorate([
  38239. BABYLON.serializeAsTexture(),
  38240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  38241. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  38242. __decorate([
  38243. BABYLON.serializeAsColor3("emissive"),
  38244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38245. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  38246. __decorate([
  38247. BABYLON.serializeAsTexture(),
  38248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38249. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  38250. __decorate([
  38251. BABYLON.serialize(),
  38252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  38253. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  38254. __decorate([
  38255. BABYLON.serializeAsTexture(),
  38256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  38257. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  38258. __decorate([
  38259. BABYLON.serialize(),
  38260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  38261. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  38262. __decorate([
  38263. BABYLON.serialize()
  38264. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  38265. __decorate([
  38266. BABYLON.serialize()
  38267. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  38268. return PBRBaseSimpleMaterial;
  38269. }(BABYLON.PBRBaseMaterial));
  38270. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  38271. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38272. })(BABYLON || (BABYLON = {}));
  38273. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  38274. var BABYLON;
  38275. (function (BABYLON) {
  38276. /**
  38277. * The Physically based material of BJS.
  38278. *
  38279. * This offers the main features of a standard PBR material.
  38280. * For more information, please refer to the documentation :
  38281. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38282. */
  38283. var PBRMaterial = (function (_super) {
  38284. __extends(PBRMaterial, _super);
  38285. /**
  38286. * Instantiates a new PBRMaterial instance.
  38287. *
  38288. * @param name The material name
  38289. * @param scene The scene the material will be use in.
  38290. */
  38291. function PBRMaterial(name, scene) {
  38292. var _this = _super.call(this, name, scene) || this;
  38293. /**
  38294. * Intensity of the direct lights e.g. the four lights available in your scene.
  38295. * This impacts both the direct diffuse and specular highlights.
  38296. */
  38297. _this.directIntensity = 1.0;
  38298. /**
  38299. * Intensity of the emissive part of the material.
  38300. * This helps controlling the emissive effect without modifying the emissive color.
  38301. */
  38302. _this.emissiveIntensity = 1.0;
  38303. /**
  38304. * Intensity of the environment e.g. how much the environment will light the object
  38305. * either through harmonics for rough material or through the refelction for shiny ones.
  38306. */
  38307. _this.environmentIntensity = 1.0;
  38308. /**
  38309. * This is a special control allowing the reduction of the specular highlights coming from the
  38310. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38311. */
  38312. _this.specularIntensity = 1.0;
  38313. /**
  38314. * Debug Control allowing disabling the bump map on this material.
  38315. */
  38316. _this.disableBumpMap = false;
  38317. /**
  38318. * AKA Occlusion Texture Intensity in other nomenclature.
  38319. */
  38320. _this.ambientTextureStrength = 1.0;
  38321. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38322. /**
  38323. * AKA Diffuse Color in other nomenclature.
  38324. */
  38325. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  38326. /**
  38327. * AKA Specular Color in other nomenclature.
  38328. */
  38329. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38330. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  38331. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38332. /**
  38333. * AKA Glossiness in other nomenclature.
  38334. */
  38335. _this.microSurface = 1.0;
  38336. /**
  38337. * source material index of refraction (IOR)' / 'destination material IOR.
  38338. */
  38339. _this.indexOfRefraction = 0.66;
  38340. /**
  38341. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38342. */
  38343. _this.invertRefractionY = false;
  38344. /**
  38345. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38346. * Materials half opaque for instance using refraction could benefit from this control.
  38347. */
  38348. _this.linkRefractionWithTransparency = false;
  38349. _this.useLightmapAsShadowmap = false;
  38350. /**
  38351. * Specifies that the alpha is coming form the albedo channel alpha channel.
  38352. */
  38353. _this.useAlphaFromAlbedoTexture = false;
  38354. /**
  38355. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38356. */
  38357. _this.forceAlphaTest = false;
  38358. /**
  38359. * Defines the alpha limits in alpha test mode.
  38360. */
  38361. _this.alphaCutOff = 0.4;
  38362. /**
  38363. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38364. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38365. */
  38366. _this.useSpecularOverAlpha = true;
  38367. /**
  38368. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38369. */
  38370. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  38371. /**
  38372. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38373. */
  38374. _this.useRoughnessFromMetallicTextureAlpha = true;
  38375. /**
  38376. * Specifies if the metallic texture contains the roughness information in its green channel.
  38377. */
  38378. _this.useRoughnessFromMetallicTextureGreen = false;
  38379. /**
  38380. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38381. */
  38382. _this.useMetallnessFromMetallicTextureBlue = false;
  38383. /**
  38384. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38385. */
  38386. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38387. /**
  38388. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38389. */
  38390. _this.useAmbientInGrayScale = false;
  38391. /**
  38392. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38393. * The material will try to infer what glossiness each pixel should be.
  38394. */
  38395. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38396. /**
  38397. * BJS is using an harcoded light falloff based on a manually sets up range.
  38398. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38399. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38400. */
  38401. _this.usePhysicalLightFalloff = true;
  38402. /**
  38403. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38404. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38405. */
  38406. _this.useRadianceOverAlpha = true;
  38407. /**
  38408. * Allows using the bump map in parallax mode.
  38409. */
  38410. _this.useParallax = false;
  38411. /**
  38412. * Allows using the bump map in parallax occlusion mode.
  38413. */
  38414. _this.useParallaxOcclusion = false;
  38415. /**
  38416. * Controls the scale bias of the parallax mode.
  38417. */
  38418. _this.parallaxScaleBias = 0.05;
  38419. /**
  38420. * If sets to true, disables all the lights affecting the material.
  38421. */
  38422. _this.disableLighting = false;
  38423. /**
  38424. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38425. */
  38426. _this.forceIrradianceInFragment = false;
  38427. /**
  38428. * Number of Simultaneous lights allowed on the material.
  38429. */
  38430. _this.maxSimultaneousLights = 4;
  38431. /**
  38432. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38433. */
  38434. _this.invertNormalMapX = false;
  38435. /**
  38436. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38437. */
  38438. _this.invertNormalMapY = false;
  38439. /**
  38440. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38441. */
  38442. _this.twoSidedLighting = false;
  38443. /**
  38444. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  38445. * in your scene composition.
  38446. */
  38447. _this.preMultiplyAlpha = false;
  38448. /**
  38449. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38450. * And/Or occlude the blended part.
  38451. */
  38452. _this.useAlphaFresnel = false;
  38453. /**
  38454. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38455. * And/Or occlude the blended part.
  38456. */
  38457. _this.environmentBRDFTexture = null;
  38458. /**
  38459. * Force normal to face away from face.
  38460. * (Temporary internal fix to remove before 3.1)
  38461. */
  38462. _this.forceNormalForward = false;
  38463. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38464. return _this;
  38465. }
  38466. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38467. /**
  38468. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38469. */
  38470. get: function () {
  38471. return this._PBRMATERIAL_OPAQUE;
  38472. },
  38473. enumerable: true,
  38474. configurable: true
  38475. });
  38476. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38477. /**
  38478. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38479. */
  38480. get: function () {
  38481. return this._PBRMATERIAL_ALPHATEST;
  38482. },
  38483. enumerable: true,
  38484. configurable: true
  38485. });
  38486. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38487. /**
  38488. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38489. */
  38490. get: function () {
  38491. return this._PBRMATERIAL_ALPHABLEND;
  38492. },
  38493. enumerable: true,
  38494. configurable: true
  38495. });
  38496. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38497. /**
  38498. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38499. * They are also discarded below the alpha cutoff threshold to improve performances.
  38500. */
  38501. get: function () {
  38502. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38503. },
  38504. enumerable: true,
  38505. configurable: true
  38506. });
  38507. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38508. /**
  38509. * Gets the image processing configuration used either in this material.
  38510. */
  38511. get: function () {
  38512. return this._imageProcessingConfiguration;
  38513. },
  38514. /**
  38515. * Sets the Default image processing configuration used either in the this material.
  38516. *
  38517. * If sets to null, the scene one is in use.
  38518. */
  38519. set: function (value) {
  38520. this._attachImageProcessingConfiguration(value);
  38521. // Ensure the effect will be rebuilt.
  38522. this._markAllSubMeshesAsTexturesDirty();
  38523. },
  38524. enumerable: true,
  38525. configurable: true
  38526. });
  38527. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38528. /**
  38529. * Gets wether the color curves effect is enabled.
  38530. */
  38531. get: function () {
  38532. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38533. },
  38534. /**
  38535. * Sets wether the color curves effect is enabled.
  38536. */
  38537. set: function (value) {
  38538. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38539. },
  38540. enumerable: true,
  38541. configurable: true
  38542. });
  38543. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38544. /**
  38545. * Gets wether the color grading effect is enabled.
  38546. */
  38547. get: function () {
  38548. return this.imageProcessingConfiguration.colorGradingEnabled;
  38549. },
  38550. /**
  38551. * Gets wether the color grading effect is enabled.
  38552. */
  38553. set: function (value) {
  38554. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38555. },
  38556. enumerable: true,
  38557. configurable: true
  38558. });
  38559. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38560. /**
  38561. * Gets wether tonemapping is enabled or not.
  38562. */
  38563. get: function () {
  38564. return this._imageProcessingConfiguration.toneMappingEnabled;
  38565. },
  38566. /**
  38567. * Sets wether tonemapping is enabled or not
  38568. */
  38569. set: function (value) {
  38570. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38571. },
  38572. enumerable: true,
  38573. configurable: true
  38574. });
  38575. ;
  38576. ;
  38577. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38578. /**
  38579. * The camera exposure used on this material.
  38580. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38581. * This corresponds to a photographic exposure.
  38582. */
  38583. get: function () {
  38584. return this._imageProcessingConfiguration.exposure;
  38585. },
  38586. /**
  38587. * The camera exposure used on this material.
  38588. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38589. * This corresponds to a photographic exposure.
  38590. */
  38591. set: function (value) {
  38592. this._imageProcessingConfiguration.exposure = value;
  38593. },
  38594. enumerable: true,
  38595. configurable: true
  38596. });
  38597. ;
  38598. ;
  38599. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38600. /**
  38601. * Gets The camera contrast used on this material.
  38602. */
  38603. get: function () {
  38604. return this._imageProcessingConfiguration.contrast;
  38605. },
  38606. /**
  38607. * Sets The camera contrast used on this material.
  38608. */
  38609. set: function (value) {
  38610. this._imageProcessingConfiguration.contrast = value;
  38611. },
  38612. enumerable: true,
  38613. configurable: true
  38614. });
  38615. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38616. /**
  38617. * Gets the Color Grading 2D Lookup Texture.
  38618. */
  38619. get: function () {
  38620. return this._imageProcessingConfiguration.colorGradingTexture;
  38621. },
  38622. /**
  38623. * Sets the Color Grading 2D Lookup Texture.
  38624. */
  38625. set: function (value) {
  38626. this._imageProcessingConfiguration.colorGradingTexture = value;
  38627. },
  38628. enumerable: true,
  38629. configurable: true
  38630. });
  38631. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38632. /**
  38633. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38634. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38635. * 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;
  38636. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38637. */
  38638. get: function () {
  38639. return this._imageProcessingConfiguration.colorCurves;
  38640. },
  38641. /**
  38642. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38643. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38644. * 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;
  38645. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38646. */
  38647. set: function (value) {
  38648. this._imageProcessingConfiguration.colorCurves = value;
  38649. },
  38650. enumerable: true,
  38651. configurable: true
  38652. });
  38653. PBRMaterial.prototype.getClassName = function () {
  38654. return "PBRMaterial";
  38655. };
  38656. PBRMaterial.prototype.getActiveTextures = function () {
  38657. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38658. if (this._albedoTexture) {
  38659. activeTextures.push(this._albedoTexture);
  38660. }
  38661. if (this._ambientTexture) {
  38662. activeTextures.push(this._ambientTexture);
  38663. }
  38664. if (this._opacityTexture) {
  38665. activeTextures.push(this._opacityTexture);
  38666. }
  38667. if (this._reflectionTexture) {
  38668. activeTextures.push(this._reflectionTexture);
  38669. }
  38670. if (this._emissiveTexture) {
  38671. activeTextures.push(this._emissiveTexture);
  38672. }
  38673. if (this._reflectivityTexture) {
  38674. activeTextures.push(this._reflectivityTexture);
  38675. }
  38676. if (this._metallicTexture) {
  38677. activeTextures.push(this._metallicTexture);
  38678. }
  38679. if (this._microSurfaceTexture) {
  38680. activeTextures.push(this._microSurfaceTexture);
  38681. }
  38682. if (this._bumpTexture) {
  38683. activeTextures.push(this._bumpTexture);
  38684. }
  38685. if (this._lightmapTexture) {
  38686. activeTextures.push(this._lightmapTexture);
  38687. }
  38688. if (this._refractionTexture) {
  38689. activeTextures.push(this._refractionTexture);
  38690. }
  38691. return activeTextures;
  38692. };
  38693. PBRMaterial.prototype.hasTexture = function (texture) {
  38694. if (_super.prototype.hasTexture.call(this, texture)) {
  38695. return true;
  38696. }
  38697. if (this._albedoTexture === texture) {
  38698. return true;
  38699. }
  38700. if (this._ambientTexture === texture) {
  38701. return true;
  38702. }
  38703. if (this._opacityTexture === texture) {
  38704. return true;
  38705. }
  38706. if (this._reflectionTexture === texture) {
  38707. return true;
  38708. }
  38709. if (this._reflectivityTexture === texture) {
  38710. return true;
  38711. }
  38712. if (this._metallicTexture === texture) {
  38713. return true;
  38714. }
  38715. if (this._microSurfaceTexture === texture) {
  38716. return true;
  38717. }
  38718. if (this._bumpTexture === texture) {
  38719. return true;
  38720. }
  38721. if (this._lightmapTexture === texture) {
  38722. return true;
  38723. }
  38724. if (this._refractionTexture === texture) {
  38725. return true;
  38726. }
  38727. return false;
  38728. };
  38729. PBRMaterial.prototype.clone = function (name) {
  38730. var _this = this;
  38731. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38732. };
  38733. PBRMaterial.prototype.serialize = function () {
  38734. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38735. serializationObject.customType = "BABYLON.PBRMaterial";
  38736. return serializationObject;
  38737. };
  38738. // Statics
  38739. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38740. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38741. };
  38742. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38743. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38744. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38745. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38746. __decorate([
  38747. BABYLON.serialize(),
  38748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38749. ], PBRMaterial.prototype, "directIntensity", void 0);
  38750. __decorate([
  38751. BABYLON.serialize(),
  38752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38753. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38754. __decorate([
  38755. BABYLON.serialize(),
  38756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38757. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38758. __decorate([
  38759. BABYLON.serialize(),
  38760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38761. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38762. __decorate([
  38763. BABYLON.serialize(),
  38764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38765. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38766. __decorate([
  38767. BABYLON.serializeAsTexture(),
  38768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38769. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38770. __decorate([
  38771. BABYLON.serializeAsTexture(),
  38772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38773. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38774. __decorate([
  38775. BABYLON.serialize(),
  38776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38777. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38778. __decorate([
  38779. BABYLON.serializeAsTexture(),
  38780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38781. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38782. __decorate([
  38783. BABYLON.serializeAsTexture(),
  38784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38785. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38786. __decorate([
  38787. BABYLON.serializeAsTexture(),
  38788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38789. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38790. __decorate([
  38791. BABYLON.serializeAsTexture(),
  38792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38793. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38794. __decorate([
  38795. BABYLON.serializeAsTexture(),
  38796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38797. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38798. __decorate([
  38799. BABYLON.serialize(),
  38800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38801. ], PBRMaterial.prototype, "metallic", void 0);
  38802. __decorate([
  38803. BABYLON.serialize(),
  38804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38805. ], PBRMaterial.prototype, "roughness", void 0);
  38806. __decorate([
  38807. BABYLON.serializeAsTexture(),
  38808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38809. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38810. __decorate([
  38811. BABYLON.serializeAsTexture(),
  38812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38813. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38814. __decorate([
  38815. BABYLON.serializeAsTexture(),
  38816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38817. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38818. __decorate([
  38819. BABYLON.serializeAsTexture(),
  38820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38821. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38822. __decorate([
  38823. BABYLON.serializeAsColor3("ambient"),
  38824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38825. ], PBRMaterial.prototype, "ambientColor", void 0);
  38826. __decorate([
  38827. BABYLON.serializeAsColor3("albedo"),
  38828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38829. ], PBRMaterial.prototype, "albedoColor", void 0);
  38830. __decorate([
  38831. BABYLON.serializeAsColor3("reflectivity"),
  38832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38833. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38834. __decorate([
  38835. BABYLON.serializeAsColor3("reflection"),
  38836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38837. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38838. __decorate([
  38839. BABYLON.serializeAsColor3("emissive"),
  38840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38841. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38842. __decorate([
  38843. BABYLON.serialize(),
  38844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38845. ], PBRMaterial.prototype, "microSurface", void 0);
  38846. __decorate([
  38847. BABYLON.serialize(),
  38848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38849. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38850. __decorate([
  38851. BABYLON.serialize(),
  38852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38853. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38854. __decorate([
  38855. BABYLON.serialize(),
  38856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38857. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38858. __decorate([
  38859. BABYLON.serialize(),
  38860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38861. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38862. __decorate([
  38863. BABYLON.serialize(),
  38864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38865. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38866. __decorate([
  38867. BABYLON.serialize(),
  38868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38869. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38870. __decorate([
  38871. BABYLON.serialize(),
  38872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38873. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38874. __decorate([
  38875. BABYLON.serialize(),
  38876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38877. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38878. __decorate([
  38879. BABYLON.serialize(),
  38880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38881. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38882. __decorate([
  38883. BABYLON.serialize(),
  38884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38885. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38886. __decorate([
  38887. BABYLON.serialize(),
  38888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38889. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38890. __decorate([
  38891. BABYLON.serialize(),
  38892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38893. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38894. __decorate([
  38895. BABYLON.serialize(),
  38896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38897. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38898. __decorate([
  38899. BABYLON.serialize(),
  38900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38901. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38902. __decorate([
  38903. BABYLON.serialize(),
  38904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38905. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38906. __decorate([
  38907. BABYLON.serialize(),
  38908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38909. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38910. __decorate([
  38911. BABYLON.serialize(),
  38912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38913. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38914. __decorate([
  38915. BABYLON.serialize(),
  38916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38917. ], PBRMaterial.prototype, "useParallax", void 0);
  38918. __decorate([
  38919. BABYLON.serialize(),
  38920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38921. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38922. __decorate([
  38923. BABYLON.serialize(),
  38924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38925. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38926. __decorate([
  38927. BABYLON.serialize(),
  38928. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38929. ], PBRMaterial.prototype, "disableLighting", void 0);
  38930. __decorate([
  38931. BABYLON.serialize(),
  38932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38933. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38934. __decorate([
  38935. BABYLON.serialize(),
  38936. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38937. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38938. __decorate([
  38939. BABYLON.serialize(),
  38940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38941. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38942. __decorate([
  38943. BABYLON.serialize(),
  38944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38945. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38946. __decorate([
  38947. BABYLON.serialize(),
  38948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38949. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38950. __decorate([
  38951. BABYLON.serialize(),
  38952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38953. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  38954. __decorate([
  38955. BABYLON.serialize(),
  38956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38957. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38958. __decorate([
  38959. BABYLON.serializeAsTexture(),
  38960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38961. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38962. __decorate([
  38963. BABYLON.serialize(),
  38964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38965. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38966. return PBRMaterial;
  38967. }(BABYLON.PBRBaseMaterial));
  38968. BABYLON.PBRMaterial = PBRMaterial;
  38969. })(BABYLON || (BABYLON = {}));
  38970. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38971. var BABYLON;
  38972. (function (BABYLON) {
  38973. /**
  38974. * The PBR material of BJS following the metal roughness convention.
  38975. *
  38976. * This fits to the PBR convention in the GLTF definition:
  38977. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38978. */
  38979. var PBRMetallicRoughnessMaterial = (function (_super) {
  38980. __extends(PBRMetallicRoughnessMaterial, _super);
  38981. /**
  38982. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38983. *
  38984. * @param name The material name
  38985. * @param scene The scene the material will be use in.
  38986. */
  38987. function PBRMetallicRoughnessMaterial(name, scene) {
  38988. var _this = _super.call(this, name, scene) || this;
  38989. _this._useRoughnessFromMetallicTextureAlpha = false;
  38990. _this._useRoughnessFromMetallicTextureGreen = true;
  38991. _this._useMetallnessFromMetallicTextureBlue = true;
  38992. return _this;
  38993. }
  38994. /**
  38995. * Return the currrent class name of the material.
  38996. */
  38997. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38998. return "PBRMetallicRoughnessMaterial";
  38999. };
  39000. /**
  39001. * Return the active textures of the material.
  39002. */
  39003. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  39004. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39005. if (this.baseTexture) {
  39006. activeTextures.push(this.baseTexture);
  39007. }
  39008. if (this.metallicRoughnessTexture) {
  39009. activeTextures.push(this.metallicRoughnessTexture);
  39010. }
  39011. return activeTextures;
  39012. };
  39013. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  39014. if (_super.prototype.hasTexture.call(this, texture)) {
  39015. return true;
  39016. }
  39017. if (this.baseTexture === texture) {
  39018. return true;
  39019. }
  39020. if (this.metallicRoughnessTexture === texture) {
  39021. return true;
  39022. }
  39023. return false;
  39024. };
  39025. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  39026. var _this = this;
  39027. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  39028. };
  39029. /**
  39030. * Serialize the material to a parsable JSON object.
  39031. */
  39032. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  39033. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39034. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  39035. return serializationObject;
  39036. };
  39037. /**
  39038. * Parses a JSON object correponding to the serialize function.
  39039. */
  39040. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  39041. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  39042. };
  39043. __decorate([
  39044. BABYLON.serializeAsColor3(),
  39045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39046. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  39047. __decorate([
  39048. BABYLON.serializeAsTexture(),
  39049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39050. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  39051. __decorate([
  39052. BABYLON.serialize(),
  39053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39054. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  39055. __decorate([
  39056. BABYLON.serialize(),
  39057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39058. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  39059. __decorate([
  39060. BABYLON.serializeAsTexture(),
  39061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  39062. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  39063. return PBRMetallicRoughnessMaterial;
  39064. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  39065. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  39066. })(BABYLON || (BABYLON = {}));
  39067. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  39068. var BABYLON;
  39069. (function (BABYLON) {
  39070. /**
  39071. * The PBR material of BJS following the specular glossiness convention.
  39072. *
  39073. * This fits to the PBR convention in the GLTF definition:
  39074. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  39075. */
  39076. var PBRSpecularGlossinessMaterial = (function (_super) {
  39077. __extends(PBRSpecularGlossinessMaterial, _super);
  39078. /**
  39079. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  39080. *
  39081. * @param name The material name
  39082. * @param scene The scene the material will be use in.
  39083. */
  39084. function PBRSpecularGlossinessMaterial(name, scene) {
  39085. var _this = _super.call(this, name, scene) || this;
  39086. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  39087. return _this;
  39088. }
  39089. /**
  39090. * Return the currrent class name of the material.
  39091. */
  39092. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  39093. return "PBRSpecularGlossinessMaterial";
  39094. };
  39095. /**
  39096. * Return the active textures of the material.
  39097. */
  39098. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  39099. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39100. if (this.diffuseTexture) {
  39101. activeTextures.push(this.diffuseTexture);
  39102. }
  39103. if (this.specularGlossinessTexture) {
  39104. activeTextures.push(this.specularGlossinessTexture);
  39105. }
  39106. return activeTextures;
  39107. };
  39108. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  39109. if (_super.prototype.hasTexture.call(this, texture)) {
  39110. return true;
  39111. }
  39112. if (this.diffuseTexture === texture) {
  39113. return true;
  39114. }
  39115. if (this.specularGlossinessTexture === texture) {
  39116. return true;
  39117. }
  39118. return false;
  39119. };
  39120. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  39121. var _this = this;
  39122. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  39123. };
  39124. /**
  39125. * Serialize the material to a parsable JSON object.
  39126. */
  39127. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  39128. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39129. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  39130. return serializationObject;
  39131. };
  39132. /**
  39133. * Parses a JSON object correponding to the serialize function.
  39134. */
  39135. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  39136. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  39137. };
  39138. __decorate([
  39139. BABYLON.serializeAsColor3("diffuse"),
  39140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39141. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  39142. __decorate([
  39143. BABYLON.serializeAsTexture(),
  39144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39145. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  39146. __decorate([
  39147. BABYLON.serializeAsColor3("specular"),
  39148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  39149. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  39150. __decorate([
  39151. BABYLON.serialize(),
  39152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  39153. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  39154. __decorate([
  39155. BABYLON.serializeAsTexture(),
  39156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  39157. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  39158. return PBRSpecularGlossinessMaterial;
  39159. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  39160. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  39161. })(BABYLON || (BABYLON = {}));
  39162. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  39163. var BABYLON;
  39164. (function (BABYLON) {
  39165. var ShaderMaterial = (function (_super) {
  39166. __extends(ShaderMaterial, _super);
  39167. function ShaderMaterial(name, scene, shaderPath, options) {
  39168. var _this = _super.call(this, name, scene) || this;
  39169. _this._textures = {};
  39170. _this._textureArrays = {};
  39171. _this._floats = {};
  39172. _this._floatsArrays = {};
  39173. _this._colors3 = {};
  39174. _this._colors3Arrays = {};
  39175. _this._colors4 = {};
  39176. _this._vectors2 = {};
  39177. _this._vectors3 = {};
  39178. _this._vectors4 = {};
  39179. _this._matrices = {};
  39180. _this._matrices3x3 = {};
  39181. _this._matrices2x2 = {};
  39182. _this._vectors3Arrays = {};
  39183. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39184. _this._shaderPath = shaderPath;
  39185. options.needAlphaBlending = options.needAlphaBlending || false;
  39186. options.needAlphaTesting = options.needAlphaTesting || false;
  39187. options.attributes = options.attributes || ["position", "normal", "uv"];
  39188. options.uniforms = options.uniforms || ["worldViewProjection"];
  39189. options.uniformBuffers = options.uniformBuffers || [];
  39190. options.samplers = options.samplers || [];
  39191. options.defines = options.defines || [];
  39192. _this._options = options;
  39193. return _this;
  39194. }
  39195. ShaderMaterial.prototype.getClassName = function () {
  39196. return "ShaderMaterial";
  39197. };
  39198. ShaderMaterial.prototype.needAlphaBlending = function () {
  39199. return this._options.needAlphaBlending;
  39200. };
  39201. ShaderMaterial.prototype.needAlphaTesting = function () {
  39202. return this._options.needAlphaTesting;
  39203. };
  39204. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39205. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39206. this._options.uniforms.push(uniformName);
  39207. }
  39208. };
  39209. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39210. if (this._options.samplers.indexOf(name) === -1) {
  39211. this._options.samplers.push(name);
  39212. }
  39213. this._textures[name] = texture;
  39214. return this;
  39215. };
  39216. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39217. if (this._options.samplers.indexOf(name) === -1) {
  39218. this._options.samplers.push(name);
  39219. }
  39220. this._checkUniform(name);
  39221. this._textureArrays[name] = textures;
  39222. return this;
  39223. };
  39224. ShaderMaterial.prototype.setFloat = function (name, value) {
  39225. this._checkUniform(name);
  39226. this._floats[name] = value;
  39227. return this;
  39228. };
  39229. ShaderMaterial.prototype.setFloats = function (name, value) {
  39230. this._checkUniform(name);
  39231. this._floatsArrays[name] = value;
  39232. return this;
  39233. };
  39234. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39235. this._checkUniform(name);
  39236. this._colors3[name] = value;
  39237. return this;
  39238. };
  39239. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  39240. this._checkUniform(name);
  39241. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  39242. color.toArray(arr, arr.length);
  39243. return arr;
  39244. }, []);
  39245. return this;
  39246. };
  39247. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39248. this._checkUniform(name);
  39249. this._colors4[name] = value;
  39250. return this;
  39251. };
  39252. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39253. this._checkUniform(name);
  39254. this._vectors2[name] = value;
  39255. return this;
  39256. };
  39257. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39258. this._checkUniform(name);
  39259. this._vectors3[name] = value;
  39260. return this;
  39261. };
  39262. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39263. this._checkUniform(name);
  39264. this._vectors4[name] = value;
  39265. return this;
  39266. };
  39267. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39268. this._checkUniform(name);
  39269. this._matrices[name] = value;
  39270. return this;
  39271. };
  39272. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39273. this._checkUniform(name);
  39274. this._matrices3x3[name] = value;
  39275. return this;
  39276. };
  39277. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39278. this._checkUniform(name);
  39279. this._matrices2x2[name] = value;
  39280. return this;
  39281. };
  39282. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39283. this._checkUniform(name);
  39284. this._vectors3Arrays[name] = value;
  39285. return this;
  39286. };
  39287. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  39288. if (!mesh) {
  39289. return true;
  39290. }
  39291. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  39292. return false;
  39293. }
  39294. return false;
  39295. };
  39296. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39297. var scene = this.getScene();
  39298. var engine = scene.getEngine();
  39299. if (!this.checkReadyOnEveryCall) {
  39300. if (this._renderId === scene.getRenderId()) {
  39301. if (this._checkCache(scene, mesh, useInstances)) {
  39302. return true;
  39303. }
  39304. }
  39305. }
  39306. // Instances
  39307. var defines = [];
  39308. var attribs = [];
  39309. var fallbacks = new BABYLON.EffectFallbacks();
  39310. if (useInstances) {
  39311. defines.push("#define INSTANCES");
  39312. }
  39313. for (var index = 0; index < this._options.defines.length; index++) {
  39314. defines.push(this._options.defines[index]);
  39315. }
  39316. for (var index = 0; index < this._options.attributes.length; index++) {
  39317. attribs.push(this._options.attributes[index]);
  39318. }
  39319. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39320. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39321. defines.push("#define VERTEXCOLOR");
  39322. }
  39323. // Bones
  39324. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39325. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39326. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39327. if (mesh.numBoneInfluencers > 4) {
  39328. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39329. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39330. }
  39331. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39332. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39333. fallbacks.addCPUSkinningFallback(0, mesh);
  39334. if (this._options.uniforms.indexOf("mBones") === -1) {
  39335. this._options.uniforms.push("mBones");
  39336. }
  39337. }
  39338. else {
  39339. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39340. }
  39341. // Textures
  39342. for (var name in this._textures) {
  39343. if (!this._textures[name].isReady()) {
  39344. return false;
  39345. }
  39346. }
  39347. // Alpha test
  39348. if (engine.getAlphaTesting()) {
  39349. defines.push("#define ALPHATEST");
  39350. }
  39351. var previousEffect = this._effect;
  39352. var join = defines.join("\n");
  39353. this._effect = engine.createEffect(this._shaderPath, {
  39354. attributes: attribs,
  39355. uniformsNames: this._options.uniforms,
  39356. uniformBuffersNames: this._options.uniformBuffers,
  39357. samplers: this._options.samplers,
  39358. defines: join,
  39359. fallbacks: fallbacks,
  39360. onCompiled: this.onCompiled,
  39361. onError: this.onError
  39362. }, engine);
  39363. if (!this._effect.isReady()) {
  39364. return false;
  39365. }
  39366. if (previousEffect !== this._effect) {
  39367. scene.resetCachedMaterial();
  39368. }
  39369. this._renderId = scene.getRenderId();
  39370. return true;
  39371. };
  39372. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39373. var scene = this.getScene();
  39374. if (this._options.uniforms.indexOf("world") !== -1) {
  39375. this._effect.setMatrix("world", world);
  39376. }
  39377. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39378. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39379. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39380. }
  39381. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39382. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39383. }
  39384. };
  39385. ShaderMaterial.prototype.bind = function (world, mesh) {
  39386. // Std values
  39387. this.bindOnlyWorldMatrix(world);
  39388. if (this.getScene().getCachedMaterial() !== this) {
  39389. if (this._options.uniforms.indexOf("view") !== -1) {
  39390. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39391. }
  39392. if (this._options.uniforms.indexOf("projection") !== -1) {
  39393. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39394. }
  39395. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39396. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39397. }
  39398. // Bones
  39399. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39400. var name;
  39401. // Texture
  39402. for (name in this._textures) {
  39403. this._effect.setTexture(name, this._textures[name]);
  39404. }
  39405. // Texture arrays
  39406. for (name in this._textureArrays) {
  39407. this._effect.setTextureArray(name, this._textureArrays[name]);
  39408. }
  39409. // Float
  39410. for (name in this._floats) {
  39411. this._effect.setFloat(name, this._floats[name]);
  39412. }
  39413. // Float s
  39414. for (name in this._floatsArrays) {
  39415. this._effect.setArray(name, this._floatsArrays[name]);
  39416. }
  39417. // Color3
  39418. for (name in this._colors3) {
  39419. this._effect.setColor3(name, this._colors3[name]);
  39420. }
  39421. for (name in this._colors3Arrays) {
  39422. this._effect.setArray3(name, this._colors3Arrays[name]);
  39423. }
  39424. // Color4
  39425. for (name in this._colors4) {
  39426. var color = this._colors4[name];
  39427. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39428. }
  39429. // Vector2
  39430. for (name in this._vectors2) {
  39431. this._effect.setVector2(name, this._vectors2[name]);
  39432. }
  39433. // Vector3
  39434. for (name in this._vectors3) {
  39435. this._effect.setVector3(name, this._vectors3[name]);
  39436. }
  39437. // Vector4
  39438. for (name in this._vectors4) {
  39439. this._effect.setVector4(name, this._vectors4[name]);
  39440. }
  39441. // Matrix
  39442. for (name in this._matrices) {
  39443. this._effect.setMatrix(name, this._matrices[name]);
  39444. }
  39445. // Matrix 3x3
  39446. for (name in this._matrices3x3) {
  39447. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39448. }
  39449. // Matrix 2x2
  39450. for (name in this._matrices2x2) {
  39451. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39452. }
  39453. // Vector3Array
  39454. for (name in this._vectors3Arrays) {
  39455. this._effect.setArray3(name, this._vectors3Arrays[name]);
  39456. }
  39457. }
  39458. this._afterBind(mesh);
  39459. };
  39460. ShaderMaterial.prototype.getActiveTextures = function () {
  39461. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39462. for (var name in this._textures) {
  39463. activeTextures.push(this._textures[name]);
  39464. }
  39465. for (var name in this._textureArrays) {
  39466. var array = this._textureArrays[name];
  39467. for (var index = 0; index < array.length; index++) {
  39468. activeTextures.push(array[index]);
  39469. }
  39470. }
  39471. return activeTextures;
  39472. };
  39473. ShaderMaterial.prototype.hasTexture = function (texture) {
  39474. if (_super.prototype.hasTexture.call(this, texture)) {
  39475. return true;
  39476. }
  39477. for (var name in this._textures) {
  39478. if (this._textures[name] === texture) {
  39479. return true;
  39480. }
  39481. }
  39482. for (var name in this._textureArrays) {
  39483. var array = this._textureArrays[name];
  39484. for (var index = 0; index < array.length; index++) {
  39485. if (array[index] === texture) {
  39486. return true;
  39487. }
  39488. }
  39489. }
  39490. return false;
  39491. };
  39492. ShaderMaterial.prototype.clone = function (name) {
  39493. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39494. return newShaderMaterial;
  39495. };
  39496. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39497. if (forceDisposeTextures) {
  39498. var name;
  39499. for (name in this._textures) {
  39500. this._textures[name].dispose();
  39501. }
  39502. for (name in this._textureArrays) {
  39503. var array = this._textureArrays[name];
  39504. for (var index = 0; index < array.length; index++) {
  39505. array[index].dispose();
  39506. }
  39507. }
  39508. }
  39509. this._textures = {};
  39510. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39511. };
  39512. ShaderMaterial.prototype.serialize = function () {
  39513. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39514. serializationObject.customType = "BABYLON.ShaderMaterial";
  39515. serializationObject.options = this._options;
  39516. serializationObject.shaderPath = this._shaderPath;
  39517. var name;
  39518. // Texture
  39519. serializationObject.textures = {};
  39520. for (name in this._textures) {
  39521. serializationObject.textures[name] = this._textures[name].serialize();
  39522. }
  39523. // Texture arrays
  39524. serializationObject.textureArrays = {};
  39525. for (name in this._textureArrays) {
  39526. serializationObject.textureArrays[name] = [];
  39527. var array = this._textureArrays[name];
  39528. for (var index = 0; index < array.length; index++) {
  39529. serializationObject.textureArrays[name].push(array[index].serialize());
  39530. }
  39531. }
  39532. // Float
  39533. serializationObject.floats = {};
  39534. for (name in this._floats) {
  39535. serializationObject.floats[name] = this._floats[name];
  39536. }
  39537. // Float s
  39538. serializationObject.floatArrays = {};
  39539. for (name in this._floatsArrays) {
  39540. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39541. }
  39542. // Color3
  39543. serializationObject.colors3 = {};
  39544. for (name in this._colors3) {
  39545. serializationObject.colors3[name] = this._colors3[name].asArray();
  39546. }
  39547. // Color3 array
  39548. serializationObject.colors3Arrays = {};
  39549. for (name in this._colors3Arrays) {
  39550. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  39551. }
  39552. // Color4
  39553. serializationObject.colors4 = {};
  39554. for (name in this._colors4) {
  39555. serializationObject.colors4[name] = this._colors4[name].asArray();
  39556. }
  39557. // Vector2
  39558. serializationObject.vectors2 = {};
  39559. for (name in this._vectors2) {
  39560. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  39561. }
  39562. // Vector3
  39563. serializationObject.vectors3 = {};
  39564. for (name in this._vectors3) {
  39565. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  39566. }
  39567. // Vector4
  39568. serializationObject.vectors4 = {};
  39569. for (name in this._vectors4) {
  39570. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  39571. }
  39572. // Matrix
  39573. serializationObject.matrices = {};
  39574. for (name in this._matrices) {
  39575. serializationObject.matrices[name] = this._matrices[name].asArray();
  39576. }
  39577. // Matrix 3x3
  39578. serializationObject.matrices3x3 = {};
  39579. for (name in this._matrices3x3) {
  39580. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  39581. }
  39582. // Matrix 2x2
  39583. serializationObject.matrices2x2 = {};
  39584. for (name in this._matrices2x2) {
  39585. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  39586. }
  39587. // Vector3Array
  39588. serializationObject.vectors3Arrays = {};
  39589. for (name in this._vectors3Arrays) {
  39590. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  39591. }
  39592. return serializationObject;
  39593. };
  39594. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  39595. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  39596. var name;
  39597. // Texture
  39598. for (name in source.textures) {
  39599. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  39600. }
  39601. // Texture arrays
  39602. for (name in source.textureArrays) {
  39603. var array = source.textureArrays[name];
  39604. var textureArray = new Array();
  39605. for (var index = 0; index < array.length; index++) {
  39606. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  39607. }
  39608. material.setTextureArray(name, textureArray);
  39609. }
  39610. // Float
  39611. for (name in source.floats) {
  39612. material.setFloat(name, source.floats[name]);
  39613. }
  39614. // Float s
  39615. for (name in source.floatsArrays) {
  39616. material.setFloats(name, source.floatsArrays[name]);
  39617. }
  39618. // Color3
  39619. for (name in source.colors3) {
  39620. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  39621. }
  39622. // Color3 arrays
  39623. for (name in source.colors3Arrays) {
  39624. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  39625. if (i % 3 === 0) {
  39626. arr.push([num]);
  39627. }
  39628. else {
  39629. arr[arr.length - 1].push(num);
  39630. }
  39631. return arr;
  39632. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  39633. material.setColor3Array(name, colors);
  39634. }
  39635. // Color4
  39636. for (name in source.colors4) {
  39637. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  39638. }
  39639. // Vector2
  39640. for (name in source.vectors2) {
  39641. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  39642. }
  39643. // Vector3
  39644. for (name in source.vectors3) {
  39645. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  39646. }
  39647. // Vector4
  39648. for (name in source.vectors4) {
  39649. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  39650. }
  39651. // Matrix
  39652. for (name in source.matrices) {
  39653. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  39654. }
  39655. // Matrix 3x3
  39656. for (name in source.matrices3x3) {
  39657. material.setMatrix3x3(name, source.matrices3x3[name]);
  39658. }
  39659. // Matrix 2x2
  39660. for (name in source.matrices2x2) {
  39661. material.setMatrix2x2(name, source.matrices2x2[name]);
  39662. }
  39663. // Vector3Array
  39664. for (name in source.vectors3Arrays) {
  39665. material.setArray3(name, source.vectors3Arrays[name]);
  39666. }
  39667. return material;
  39668. };
  39669. return ShaderMaterial;
  39670. }(BABYLON.Material));
  39671. BABYLON.ShaderMaterial = ShaderMaterial;
  39672. })(BABYLON || (BABYLON = {}));
  39673. //# sourceMappingURL=babylon.shaderMaterial.js.map
  39674. var BABYLON;
  39675. (function (BABYLON) {
  39676. var MeshBuilder = (function () {
  39677. function MeshBuilder() {
  39678. }
  39679. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  39680. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  39681. return BABYLON.Mesh.DOUBLESIDE;
  39682. }
  39683. if (orientation === undefined || orientation === null) {
  39684. return BABYLON.Mesh.FRONTSIDE;
  39685. }
  39686. return orientation;
  39687. };
  39688. /**
  39689. * Creates a box mesh.
  39690. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  39691. * The parameter `size` sets the size (float) of each box side (default 1).
  39692. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  39693. * 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).
  39694. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  39695. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39696. * 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).
  39697. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39698. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39699. */
  39700. MeshBuilder.CreateBox = function (name, options, scene) {
  39701. var box = new BABYLON.Mesh(name, scene);
  39702. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39703. box.sideOrientation = options.sideOrientation;
  39704. var vertexData = BABYLON.VertexData.CreateBox(options);
  39705. vertexData.applyToMesh(box, options.updatable);
  39706. return box;
  39707. };
  39708. /**
  39709. * Creates a sphere mesh.
  39710. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  39711. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  39712. * 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`).
  39713. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  39714. * 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
  39715. * 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).
  39716. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39717. * 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).
  39718. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39720. */
  39721. MeshBuilder.CreateSphere = function (name, options, scene) {
  39722. var sphere = new BABYLON.Mesh(name, scene);
  39723. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39724. sphere.sideOrientation = options.sideOrientation;
  39725. var vertexData = BABYLON.VertexData.CreateSphere(options);
  39726. vertexData.applyToMesh(sphere, options.updatable);
  39727. return sphere;
  39728. };
  39729. /**
  39730. * Creates a plane polygonal mesh. By default, this is a disc.
  39731. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  39732. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  39733. * 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.
  39734. * 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
  39735. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39736. * 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).
  39737. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39738. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39739. */
  39740. MeshBuilder.CreateDisc = function (name, options, scene) {
  39741. var disc = new BABYLON.Mesh(name, scene);
  39742. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39743. disc.sideOrientation = options.sideOrientation;
  39744. var vertexData = BABYLON.VertexData.CreateDisc(options);
  39745. vertexData.applyToMesh(disc, options.updatable);
  39746. return disc;
  39747. };
  39748. /**
  39749. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  39750. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  39751. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  39752. * 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`).
  39753. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  39754. * 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.
  39755. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39756. * 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).
  39757. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39758. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39759. */
  39760. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  39761. var sphere = new BABYLON.Mesh(name, scene);
  39762. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39763. sphere.sideOrientation = options.sideOrientation;
  39764. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  39765. vertexData.applyToMesh(sphere, options.updatable);
  39766. return sphere;
  39767. };
  39768. ;
  39769. /**
  39770. * Creates a ribbon mesh.
  39771. * 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.
  39772. *
  39773. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  39774. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  39775. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  39776. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  39777. * 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.
  39778. * 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.
  39779. * 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
  39780. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39781. * 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).
  39782. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39783. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39784. * 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.
  39785. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  39786. * 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
  39787. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  39788. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  39789. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39790. */
  39791. MeshBuilder.CreateRibbon = function (name, options, scene) {
  39792. var pathArray = options.pathArray;
  39793. var closeArray = options.closeArray;
  39794. var closePath = options.closePath;
  39795. var offset = options.offset;
  39796. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39797. var instance = options.instance;
  39798. var updatable = options.updatable;
  39799. if (instance) {
  39800. // positionFunction : ribbon case
  39801. // only pathArray and sideOrientation parameters are taken into account for positions update
  39802. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  39803. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  39804. var positionFunction = function (positions) {
  39805. var minlg = pathArray[0].length;
  39806. var i = 0;
  39807. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  39808. for (var si = 1; si <= ns; si++) {
  39809. for (var p = 0; p < pathArray.length; p++) {
  39810. var path = pathArray[p];
  39811. var l = path.length;
  39812. minlg = (minlg < l) ? minlg : l;
  39813. var j = 0;
  39814. while (j < minlg) {
  39815. positions[i] = path[j].x;
  39816. positions[i + 1] = path[j].y;
  39817. positions[i + 2] = path[j].z;
  39818. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  39819. BABYLON.Tmp.Vector3[0].x = path[j].x;
  39820. }
  39821. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  39822. BABYLON.Tmp.Vector3[1].x = path[j].x;
  39823. }
  39824. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  39825. BABYLON.Tmp.Vector3[0].y = path[j].y;
  39826. }
  39827. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  39828. BABYLON.Tmp.Vector3[1].y = path[j].y;
  39829. }
  39830. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  39831. BABYLON.Tmp.Vector3[0].z = path[j].z;
  39832. }
  39833. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  39834. BABYLON.Tmp.Vector3[1].z = path[j].z;
  39835. }
  39836. j++;
  39837. i += 3;
  39838. }
  39839. if (instance._closePath) {
  39840. positions[i] = path[0].x;
  39841. positions[i + 1] = path[0].y;
  39842. positions[i + 2] = path[0].z;
  39843. i += 3;
  39844. }
  39845. }
  39846. }
  39847. };
  39848. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39849. positionFunction(positions);
  39850. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  39851. instance._boundingInfo.update(instance._worldMatrix);
  39852. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  39853. if (options.colors) {
  39854. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39855. for (var c = 0; c < options.colors.length; c++) {
  39856. colors[c * 4] = options.colors[c].r;
  39857. colors[c * 4 + 1] = options.colors[c].g;
  39858. colors[c * 4 + 2] = options.colors[c].b;
  39859. colors[c * 4 + 3] = options.colors[c].a;
  39860. }
  39861. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  39862. }
  39863. if (options.uvs) {
  39864. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39865. for (var i = 0; i < options.uvs.length; i++) {
  39866. uvs[i * 2] = options.uvs[i].x;
  39867. uvs[i * 2 + 1] = options.uvs[i].y;
  39868. }
  39869. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  39870. }
  39871. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  39872. var indices = instance.getIndices();
  39873. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39874. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  39875. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  39876. if (instance._closePath) {
  39877. var indexFirst = 0;
  39878. var indexLast = 0;
  39879. for (var p = 0; p < pathArray.length; p++) {
  39880. indexFirst = instance._idx[p] * 3;
  39881. if (p + 1 < pathArray.length) {
  39882. indexLast = (instance._idx[p + 1] - 1) * 3;
  39883. }
  39884. else {
  39885. indexLast = normals.length - 3;
  39886. }
  39887. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  39888. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  39889. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  39890. normals[indexLast] = normals[indexFirst];
  39891. normals[indexLast + 1] = normals[indexFirst + 1];
  39892. normals[indexLast + 2] = normals[indexFirst + 2];
  39893. }
  39894. }
  39895. if (!(instance.areNormalsFrozen)) {
  39896. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  39897. }
  39898. }
  39899. return instance;
  39900. }
  39901. else {
  39902. var ribbon = new BABYLON.Mesh(name, scene);
  39903. ribbon.sideOrientation = sideOrientation;
  39904. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  39905. if (closePath) {
  39906. ribbon._idx = vertexData._idx;
  39907. }
  39908. ribbon._closePath = closePath;
  39909. ribbon._closeArray = closeArray;
  39910. vertexData.applyToMesh(ribbon, updatable);
  39911. return ribbon;
  39912. }
  39913. };
  39914. /**
  39915. * Creates a cylinder or a cone mesh.
  39916. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  39917. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  39918. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  39919. * 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.
  39920. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  39921. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  39922. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  39923. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  39924. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  39925. * 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).
  39926. * 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
  39927. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  39928. * 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
  39929. * 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.
  39930. * If `enclose` is false, a ring surface is one element.
  39931. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  39932. * 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
  39933. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39934. * 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).
  39935. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39936. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39937. */
  39938. MeshBuilder.CreateCylinder = function (name, options, scene) {
  39939. var cylinder = new BABYLON.Mesh(name, scene);
  39940. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39941. cylinder.sideOrientation = options.sideOrientation;
  39942. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  39943. vertexData.applyToMesh(cylinder, options.updatable);
  39944. return cylinder;
  39945. };
  39946. /**
  39947. * Creates a torus mesh.
  39948. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  39949. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  39950. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  39951. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  39952. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39953. * 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).
  39954. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39956. */
  39957. MeshBuilder.CreateTorus = function (name, options, scene) {
  39958. var torus = new BABYLON.Mesh(name, scene);
  39959. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39960. torus.sideOrientation = options.sideOrientation;
  39961. var vertexData = BABYLON.VertexData.CreateTorus(options);
  39962. vertexData.applyToMesh(torus, options.updatable);
  39963. return torus;
  39964. };
  39965. /**
  39966. * Creates a torus knot mesh.
  39967. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  39968. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  39969. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  39970. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  39971. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  39972. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39973. * 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).
  39974. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39975. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39976. */
  39977. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  39978. var torusKnot = new BABYLON.Mesh(name, scene);
  39979. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39980. torusKnot.sideOrientation = options.sideOrientation;
  39981. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  39982. vertexData.applyToMesh(torusKnot, options.updatable);
  39983. return torusKnot;
  39984. };
  39985. /**
  39986. * Creates a line system mesh.
  39987. * A line system is a pool of many lines gathered in a single mesh.
  39988. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  39989. * 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.
  39990. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  39991. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  39992. * 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
  39993. * 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
  39994. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  39995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39996. */
  39997. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  39998. var instance = options.instance;
  39999. var lines = options.lines;
  40000. if (instance) {
  40001. var positionFunction = function (positions) {
  40002. var i = 0;
  40003. for (var l = 0; l < lines.length; l++) {
  40004. var points = lines[l];
  40005. for (var p = 0; p < points.length; p++) {
  40006. positions[i] = points[p].x;
  40007. positions[i + 1] = points[p].y;
  40008. positions[i + 2] = points[p].z;
  40009. i += 3;
  40010. }
  40011. }
  40012. };
  40013. instance.updateMeshPositions(positionFunction, false);
  40014. return instance;
  40015. }
  40016. // line system creation
  40017. var lineSystem = new BABYLON.LinesMesh(name, scene);
  40018. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  40019. vertexData.applyToMesh(lineSystem, options.updatable);
  40020. return lineSystem;
  40021. };
  40022. /**
  40023. * Creates a line mesh.
  40024. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  40025. * 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.
  40026. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40027. * The parameter `points` is an array successive Vector3.
  40028. * 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
  40029. * When updating an instance, remember that only point positions can change, not the number of points.
  40030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40031. */
  40032. MeshBuilder.CreateLines = function (name, options, scene) {
  40033. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  40034. return lines;
  40035. };
  40036. /**
  40037. * Creates a dashed line mesh.
  40038. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  40039. * 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.
  40040. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40041. * The parameter `points` is an array successive Vector3.
  40042. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  40043. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  40044. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  40045. * 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
  40046. * When updating an instance, remember that only point positions can change, not the number of points.
  40047. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40048. */
  40049. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  40050. var points = options.points;
  40051. var instance = options.instance;
  40052. var gapSize = options.gapSize;
  40053. var dashNb = options.dashNb;
  40054. var dashSize = options.dashSize;
  40055. if (instance) {
  40056. var positionFunction = function (positions) {
  40057. var curvect = BABYLON.Vector3.Zero();
  40058. var nbSeg = positions.length / 6;
  40059. var lg = 0;
  40060. var nb = 0;
  40061. var shft = 0;
  40062. var dashshft = 0;
  40063. var curshft = 0;
  40064. var p = 0;
  40065. var i = 0;
  40066. var j = 0;
  40067. for (i = 0; i < points.length - 1; i++) {
  40068. points[i + 1].subtractToRef(points[i], curvect);
  40069. lg += curvect.length();
  40070. }
  40071. shft = lg / nbSeg;
  40072. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  40073. for (i = 0; i < points.length - 1; i++) {
  40074. points[i + 1].subtractToRef(points[i], curvect);
  40075. nb = Math.floor(curvect.length() / shft);
  40076. curvect.normalize();
  40077. j = 0;
  40078. while (j < nb && p < positions.length) {
  40079. curshft = shft * j;
  40080. positions[p] = points[i].x + curshft * curvect.x;
  40081. positions[p + 1] = points[i].y + curshft * curvect.y;
  40082. positions[p + 2] = points[i].z + curshft * curvect.z;
  40083. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  40084. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  40085. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  40086. p += 6;
  40087. j++;
  40088. }
  40089. }
  40090. while (p < positions.length) {
  40091. positions[p] = points[i].x;
  40092. positions[p + 1] = points[i].y;
  40093. positions[p + 2] = points[i].z;
  40094. p += 3;
  40095. }
  40096. };
  40097. instance.updateMeshPositions(positionFunction, false);
  40098. return instance;
  40099. }
  40100. // dashed lines creation
  40101. var dashedLines = new BABYLON.LinesMesh(name, scene);
  40102. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  40103. vertexData.applyToMesh(dashedLines, options.updatable);
  40104. dashedLines.dashSize = dashSize;
  40105. dashedLines.gapSize = gapSize;
  40106. return dashedLines;
  40107. };
  40108. /**
  40109. * Creates an extruded shape mesh.
  40110. * 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.
  40111. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  40112. *
  40113. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40114. * 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
  40115. * extruded along the Z axis.
  40116. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40117. * 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.
  40118. * The parameter `scale` (float, default 1) is the value to scale the shape.
  40119. * 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
  40120. * 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
  40121. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40122. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40123. * 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).
  40124. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40125. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40126. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40127. */
  40128. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  40129. var path = options.path;
  40130. var shape = options.shape;
  40131. var scale = options.scale || 1;
  40132. var rotation = options.rotation || 0;
  40133. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40134. var updatable = options.updatable;
  40135. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40136. var instance = options.instance;
  40137. var invertUV = options.invertUV || false;
  40138. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40139. };
  40140. /**
  40141. * Creates an custom extruded shape mesh.
  40142. * 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.
  40143. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  40144. *
  40145. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40146. * 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
  40147. * extruded along the Z axis.
  40148. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40149. * 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
  40150. * and the distance of this point from the begining of the path :
  40151. * ```javascript
  40152. * var rotationFunction = function(i, distance) {
  40153. * // do things
  40154. * return rotationValue; }
  40155. * ```
  40156. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  40157. * 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
  40158. * and the distance of this point from the begining of the path :
  40159. * ```javascript
  40160. * var scaleFunction = function(i, distance) {
  40161. * // do things
  40162. * return scaleValue;}
  40163. * ```
  40164. * It must returns a float value that will be the scale value applied to the shape on each path point.
  40165. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  40166. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  40167. * 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
  40168. * 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
  40169. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40171. * 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).
  40172. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40173. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40175. */
  40176. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  40177. var path = options.path;
  40178. var shape = options.shape;
  40179. var scaleFunction = options.scaleFunction || (function () { return 1; });
  40180. var rotationFunction = options.rotationFunction || (function () { return 0; });
  40181. var ribbonCloseArray = options.ribbonCloseArray || false;
  40182. var ribbonClosePath = options.ribbonClosePath || false;
  40183. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40184. var updatable = options.updatable;
  40185. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40186. var instance = options.instance;
  40187. var invertUV = options.invertUV || false;
  40188. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40189. };
  40190. /**
  40191. * Creates lathe mesh.
  40192. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  40193. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  40194. *
  40195. * 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
  40196. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  40197. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  40198. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  40199. * 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.
  40200. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  40201. * 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
  40202. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40203. * 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).
  40204. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40205. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40207. */
  40208. MeshBuilder.CreateLathe = function (name, options, scene) {
  40209. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  40210. var closed = (options.closed === undefined) ? true : options.closed;
  40211. var shape = options.shape;
  40212. var radius = options.radius || 1;
  40213. var tessellation = options.tessellation || 64;
  40214. var updatable = options.updatable;
  40215. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40216. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40217. var pi2 = Math.PI * 2;
  40218. var paths = new Array();
  40219. var invertUV = options.invertUV || false;
  40220. var i = 0;
  40221. var p = 0;
  40222. var step = pi2 / tessellation * arc;
  40223. var rotated;
  40224. var path = new Array();
  40225. ;
  40226. for (i = 0; i <= tessellation; i++) {
  40227. var path = [];
  40228. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  40229. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  40230. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  40231. }
  40232. for (p = 0; p < shape.length; p++) {
  40233. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  40234. path.push(rotated);
  40235. }
  40236. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  40237. 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));
  40238. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  40239. }
  40240. paths.push(path);
  40241. }
  40242. // lathe ribbon
  40243. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40244. return lathe;
  40245. };
  40246. /**
  40247. * Creates a plane mesh.
  40248. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40249. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  40250. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  40251. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  40252. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40253. * 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).
  40254. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40256. */
  40257. MeshBuilder.CreatePlane = function (name, options, scene) {
  40258. var plane = new BABYLON.Mesh(name, scene);
  40259. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40260. plane.sideOrientation = options.sideOrientation;
  40261. var vertexData = BABYLON.VertexData.CreatePlane(options);
  40262. vertexData.applyToMesh(plane, options.updatable);
  40263. if (options.sourcePlane) {
  40264. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  40265. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  40266. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  40267. plane.rotate(vectorProduct, product);
  40268. }
  40269. return plane;
  40270. };
  40271. /**
  40272. * Creates a ground mesh.
  40273. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40274. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  40275. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  40276. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40277. */
  40278. MeshBuilder.CreateGround = function (name, options, scene) {
  40279. var ground = new BABYLON.GroundMesh(name, scene);
  40280. ground._setReady(false);
  40281. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  40282. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  40283. ground._width = options.width || 1;
  40284. ground._height = options.height || 1;
  40285. ground._maxX = ground._width / 2;
  40286. ground._maxZ = ground._height / 2;
  40287. ground._minX = -ground._maxX;
  40288. ground._minZ = -ground._maxZ;
  40289. var vertexData = BABYLON.VertexData.CreateGround(options);
  40290. vertexData.applyToMesh(ground, options.updatable);
  40291. ground._setReady(true);
  40292. return ground;
  40293. };
  40294. /**
  40295. * Creates a tiled ground mesh.
  40296. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  40297. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  40298. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  40299. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  40300. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  40301. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  40302. * numbers of subdivisions on the ground width and height of each tile.
  40303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40304. */
  40305. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  40306. var tiledGround = new BABYLON.Mesh(name, scene);
  40307. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  40308. vertexData.applyToMesh(tiledGround, options.updatable);
  40309. return tiledGround;
  40310. };
  40311. /**
  40312. * Creates a ground mesh from a height map.
  40313. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  40314. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  40315. * The parameter `url` sets the URL of the height map image resource.
  40316. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  40317. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  40318. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  40319. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  40320. * 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.
  40321. * 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).
  40322. * This function is passed the newly built mesh :
  40323. * ```javascript
  40324. * function(mesh) { // do things
  40325. * return; }
  40326. * ```
  40327. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40328. */
  40329. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  40330. var width = options.width || 10.0;
  40331. var height = options.height || 10.0;
  40332. var subdivisions = options.subdivisions || 1 | 0;
  40333. var minHeight = options.minHeight || 0.0;
  40334. var maxHeight = options.maxHeight || 10.0;
  40335. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  40336. var updatable = options.updatable;
  40337. var onReady = options.onReady;
  40338. var ground = new BABYLON.GroundMesh(name, scene);
  40339. ground._subdivisionsX = subdivisions;
  40340. ground._subdivisionsY = subdivisions;
  40341. ground._width = width;
  40342. ground._height = height;
  40343. ground._maxX = ground._width / 2.0;
  40344. ground._maxZ = ground._height / 2.0;
  40345. ground._minX = -ground._maxX;
  40346. ground._minZ = -ground._maxZ;
  40347. ground._setReady(false);
  40348. var onload = function (img) {
  40349. // Getting height map data
  40350. var canvas = document.createElement("canvas");
  40351. var context = canvas.getContext("2d");
  40352. var bufferWidth = img.width;
  40353. var bufferHeight = img.height;
  40354. canvas.width = bufferWidth;
  40355. canvas.height = bufferHeight;
  40356. context.drawImage(img, 0, 0);
  40357. // Create VertexData from map data
  40358. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  40359. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  40360. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  40361. width: width, height: height,
  40362. subdivisions: subdivisions,
  40363. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  40364. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  40365. });
  40366. vertexData.applyToMesh(ground, updatable);
  40367. ground._setReady(true);
  40368. //execute ready callback, if set
  40369. if (onReady) {
  40370. onReady(ground);
  40371. }
  40372. };
  40373. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  40374. return ground;
  40375. };
  40376. /**
  40377. * Creates a polygon mesh.
  40378. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  40379. * 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.
  40380. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40381. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40382. * 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).
  40383. * Remember you can only change the shape positions, not their number when updating a polygon.
  40384. */
  40385. MeshBuilder.CreatePolygon = function (name, options, scene) {
  40386. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40387. var shape = options.shape;
  40388. var holes = options.holes || [];
  40389. var depth = options.depth || 0;
  40390. var contours = [];
  40391. var hole = [];
  40392. for (var i = 0; i < shape.length; i++) {
  40393. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  40394. }
  40395. var epsilon = 0.00000001;
  40396. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  40397. contours.pop();
  40398. }
  40399. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  40400. for (var hNb = 0; hNb < holes.length; hNb++) {
  40401. hole = [];
  40402. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  40403. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  40404. }
  40405. polygonTriangulation.addHole(hole);
  40406. }
  40407. var polygon = polygonTriangulation.build(options.updatable, depth);
  40408. polygon.sideOrientation = options.sideOrientation;
  40409. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  40410. vertexData.applyToMesh(polygon, options.updatable);
  40411. return polygon;
  40412. };
  40413. ;
  40414. /**
  40415. * Creates an extruded polygon mesh, with depth in the Y direction.
  40416. * 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).
  40417. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40418. */
  40419. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  40420. return MeshBuilder.CreatePolygon(name, options, scene);
  40421. };
  40422. ;
  40423. /**
  40424. * Creates a tube mesh.
  40425. * 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.
  40426. *
  40427. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  40428. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  40429. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  40430. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  40431. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  40432. * 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.
  40433. * It must return a radius value (positive float) :
  40434. * ```javascript
  40435. * var radiusFunction = function(i, distance) {
  40436. * // do things
  40437. * return radius; }
  40438. * ```
  40439. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  40440. * 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
  40441. * 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
  40442. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40443. * 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).
  40444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40445. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40446. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40447. */
  40448. MeshBuilder.CreateTube = function (name, options, scene) {
  40449. var path = options.path;
  40450. var radius = options.radius || 1.0;
  40451. var tessellation = options.tessellation || 64 | 0;
  40452. var radiusFunction = options.radiusFunction;
  40453. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40454. var invertUV = options.invertUV || false;
  40455. var updatable = options.updatable;
  40456. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40457. var instance = options.instance;
  40458. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  40459. // tube geometry
  40460. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  40461. var tangents = path3D.getTangents();
  40462. var normals = path3D.getNormals();
  40463. var distances = path3D.getDistances();
  40464. var pi2 = Math.PI * 2;
  40465. var step = pi2 / tessellation * arc;
  40466. var returnRadius = function () { return radius; };
  40467. var radiusFunctionFinal = radiusFunction || returnRadius;
  40468. var circlePath;
  40469. var rad;
  40470. var normal;
  40471. var rotated;
  40472. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40473. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40474. for (var i = 0; i < path.length; i++) {
  40475. rad = radiusFunctionFinal(i, distances[i]); // current radius
  40476. circlePath = Array(); // current circle array
  40477. normal = normals[i]; // current normal
  40478. for (var t = 0; t < tessellation; t++) {
  40479. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  40480. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  40481. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  40482. rotated.scaleInPlace(rad).addInPlace(path[i]);
  40483. circlePath[t] = rotated;
  40484. }
  40485. circlePaths[index] = circlePath;
  40486. index++;
  40487. }
  40488. // cap
  40489. var capPath = function (nbPoints, pathIndex) {
  40490. var pointCap = Array();
  40491. for (var i = 0; i < nbPoints; i++) {
  40492. pointCap.push(path[pathIndex]);
  40493. }
  40494. return pointCap;
  40495. };
  40496. switch (cap) {
  40497. case BABYLON.Mesh.NO_CAP:
  40498. break;
  40499. case BABYLON.Mesh.CAP_START:
  40500. circlePaths[0] = capPath(tessellation, 0);
  40501. circlePaths[1] = circlePaths[2].slice(0);
  40502. break;
  40503. case BABYLON.Mesh.CAP_END:
  40504. circlePaths[index] = circlePaths[index - 1].slice(0);
  40505. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40506. break;
  40507. case BABYLON.Mesh.CAP_ALL:
  40508. circlePaths[0] = capPath(tessellation, 0);
  40509. circlePaths[1] = circlePaths[2].slice(0);
  40510. circlePaths[index] = circlePaths[index - 1].slice(0);
  40511. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40512. break;
  40513. default:
  40514. break;
  40515. }
  40516. return circlePaths;
  40517. };
  40518. var path3D;
  40519. var pathArray;
  40520. if (instance) {
  40521. var arc = options.arc || instance.arc;
  40522. path3D = (instance.path3D).update(path);
  40523. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  40524. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  40525. instance.path3D = path3D;
  40526. instance.pathArray = pathArray;
  40527. instance.arc = arc;
  40528. return instance;
  40529. }
  40530. // tube creation
  40531. path3D = new BABYLON.Path3D(path);
  40532. var newPathArray = new Array();
  40533. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40534. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  40535. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40536. tube.pathArray = pathArray;
  40537. tube.path3D = path3D;
  40538. tube.tessellation = tessellation;
  40539. tube.cap = cap;
  40540. tube.arc = options.arc;
  40541. return tube;
  40542. };
  40543. /**
  40544. * Creates a polyhedron mesh.
  40545. *
  40546. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  40547. * 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
  40548. * to choose the wanted type.
  40549. * The parameter `size` (positive float, default 1) sets the polygon size.
  40550. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  40551. * 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`.
  40552. * 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
  40553. * 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)`).
  40554. * 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
  40555. * 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.
  40556. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40557. * 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).
  40558. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40560. */
  40561. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  40562. var polyhedron = new BABYLON.Mesh(name, scene);
  40563. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40564. polyhedron.sideOrientation = options.sideOrientation;
  40565. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  40566. vertexData.applyToMesh(polyhedron, options.updatable);
  40567. return polyhedron;
  40568. };
  40569. /**
  40570. * Creates a decal mesh.
  40571. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  40572. * 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.
  40573. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  40574. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  40575. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  40576. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  40577. */
  40578. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  40579. var indices = sourceMesh.getIndices();
  40580. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40581. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40582. var position = options.position || BABYLON.Vector3.Zero();
  40583. var normal = options.normal || BABYLON.Vector3.Up();
  40584. var size = options.size || BABYLON.Vector3.One();
  40585. var angle = options.angle || 0;
  40586. // Getting correct rotation
  40587. if (!normal) {
  40588. var target = new BABYLON.Vector3(0, 0, 1);
  40589. var camera = sourceMesh.getScene().activeCamera;
  40590. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  40591. normal = camera.globalPosition.subtract(cameraWorldTarget);
  40592. }
  40593. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  40594. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  40595. var pitch = Math.atan2(normal.y, len);
  40596. // Matrix
  40597. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  40598. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  40599. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  40600. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  40601. var vertexData = new BABYLON.VertexData();
  40602. vertexData.indices = [];
  40603. vertexData.positions = [];
  40604. vertexData.normals = [];
  40605. vertexData.uvs = [];
  40606. var currentVertexDataIndex = 0;
  40607. var extractDecalVector3 = function (indexId) {
  40608. var vertexId = indices[indexId];
  40609. var result = new BABYLON.PositionNormalVertex();
  40610. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  40611. // Send vector to decal local world
  40612. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  40613. // Get normal
  40614. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  40615. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  40616. return result;
  40617. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  40618. var clip = function (vertices, axis) {
  40619. if (vertices.length === 0) {
  40620. return vertices;
  40621. }
  40622. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  40623. var clipVertices = function (v0, v1) {
  40624. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  40625. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  40626. };
  40627. var result = new Array();
  40628. for (var index = 0; index < vertices.length; index += 3) {
  40629. var v1Out;
  40630. var v2Out;
  40631. var v3Out;
  40632. var total = 0;
  40633. var nV1, nV2, nV3, nV4;
  40634. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  40635. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  40636. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  40637. v1Out = d1 > 0;
  40638. v2Out = d2 > 0;
  40639. v3Out = d3 > 0;
  40640. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  40641. switch (total) {
  40642. case 0:
  40643. result.push(vertices[index]);
  40644. result.push(vertices[index + 1]);
  40645. result.push(vertices[index + 2]);
  40646. break;
  40647. case 1:
  40648. if (v1Out) {
  40649. nV1 = vertices[index + 1];
  40650. nV2 = vertices[index + 2];
  40651. nV3 = clipVertices(vertices[index], nV1);
  40652. nV4 = clipVertices(vertices[index], nV2);
  40653. }
  40654. if (v2Out) {
  40655. nV1 = vertices[index];
  40656. nV2 = vertices[index + 2];
  40657. nV3 = clipVertices(vertices[index + 1], nV1);
  40658. nV4 = clipVertices(vertices[index + 1], nV2);
  40659. result.push(nV3);
  40660. result.push(nV2.clone());
  40661. result.push(nV1.clone());
  40662. result.push(nV2.clone());
  40663. result.push(nV3.clone());
  40664. result.push(nV4);
  40665. break;
  40666. }
  40667. if (v3Out) {
  40668. nV1 = vertices[index];
  40669. nV2 = vertices[index + 1];
  40670. nV3 = clipVertices(vertices[index + 2], nV1);
  40671. nV4 = clipVertices(vertices[index + 2], nV2);
  40672. }
  40673. result.push(nV1.clone());
  40674. result.push(nV2.clone());
  40675. result.push(nV3);
  40676. result.push(nV4);
  40677. result.push(nV3.clone());
  40678. result.push(nV2.clone());
  40679. break;
  40680. case 2:
  40681. if (!v1Out) {
  40682. nV1 = vertices[index].clone();
  40683. nV2 = clipVertices(nV1, vertices[index + 1]);
  40684. nV3 = clipVertices(nV1, vertices[index + 2]);
  40685. result.push(nV1);
  40686. result.push(nV2);
  40687. result.push(nV3);
  40688. }
  40689. if (!v2Out) {
  40690. nV1 = vertices[index + 1].clone();
  40691. nV2 = clipVertices(nV1, vertices[index + 2]);
  40692. nV3 = clipVertices(nV1, vertices[index]);
  40693. result.push(nV1);
  40694. result.push(nV2);
  40695. result.push(nV3);
  40696. }
  40697. if (!v3Out) {
  40698. nV1 = vertices[index + 2].clone();
  40699. nV2 = clipVertices(nV1, vertices[index]);
  40700. nV3 = clipVertices(nV1, vertices[index + 1]);
  40701. result.push(nV1);
  40702. result.push(nV2);
  40703. result.push(nV3);
  40704. }
  40705. break;
  40706. case 3:
  40707. break;
  40708. }
  40709. }
  40710. return result;
  40711. };
  40712. for (var index = 0; index < indices.length; index += 3) {
  40713. var faceVertices = new Array();
  40714. faceVertices.push(extractDecalVector3(index));
  40715. faceVertices.push(extractDecalVector3(index + 1));
  40716. faceVertices.push(extractDecalVector3(index + 2));
  40717. // Clip
  40718. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  40719. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  40720. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  40721. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  40722. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  40723. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  40724. if (faceVertices.length === 0) {
  40725. continue;
  40726. }
  40727. // Add UVs and get back to world
  40728. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  40729. var vertex = faceVertices[vIndex];
  40730. //TODO check for Int32Array | Uint32Array | Uint16Array
  40731. vertexData.indices.push(currentVertexDataIndex);
  40732. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  40733. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  40734. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  40735. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  40736. currentVertexDataIndex++;
  40737. }
  40738. }
  40739. // Return mesh
  40740. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  40741. vertexData.applyToMesh(decal);
  40742. decal.position = position.clone();
  40743. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  40744. return decal;
  40745. };
  40746. // Privates
  40747. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  40748. // extrusion geometry
  40749. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  40750. var tangents = path3D.getTangents();
  40751. var normals = path3D.getNormals();
  40752. var binormals = path3D.getBinormals();
  40753. var distances = path3D.getDistances();
  40754. var angle = 0;
  40755. var returnScale = function () { return scale; };
  40756. var returnRotation = function () { return rotation; };
  40757. var rotate = custom ? rotateFunction : returnRotation;
  40758. var scl = custom ? scaleFunction : returnScale;
  40759. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40760. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40761. for (var i = 0; i < curve.length; i++) {
  40762. var shapePath = new Array();
  40763. var angleStep = rotate(i, distances[i]);
  40764. var scaleRatio = scl(i, distances[i]);
  40765. for (var p = 0; p < shape.length; p++) {
  40766. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  40767. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  40768. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  40769. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  40770. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  40771. shapePath[p] = rotated;
  40772. }
  40773. shapePaths[index] = shapePath;
  40774. angle += angleStep;
  40775. index++;
  40776. }
  40777. // cap
  40778. var capPath = function (shapePath) {
  40779. var pointCap = Array();
  40780. var barycenter = BABYLON.Vector3.Zero();
  40781. var i;
  40782. for (i = 0; i < shapePath.length; i++) {
  40783. barycenter.addInPlace(shapePath[i]);
  40784. }
  40785. barycenter.scaleInPlace(1.0 / shapePath.length);
  40786. for (i = 0; i < shapePath.length; i++) {
  40787. pointCap.push(barycenter);
  40788. }
  40789. return pointCap;
  40790. };
  40791. switch (cap) {
  40792. case BABYLON.Mesh.NO_CAP:
  40793. break;
  40794. case BABYLON.Mesh.CAP_START:
  40795. shapePaths[0] = capPath(shapePaths[2]);
  40796. shapePaths[1] = shapePaths[2];
  40797. break;
  40798. case BABYLON.Mesh.CAP_END:
  40799. shapePaths[index] = shapePaths[index - 1];
  40800. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40801. break;
  40802. case BABYLON.Mesh.CAP_ALL:
  40803. shapePaths[0] = capPath(shapePaths[2]);
  40804. shapePaths[1] = shapePaths[2];
  40805. shapePaths[index] = shapePaths[index - 1];
  40806. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40807. break;
  40808. default:
  40809. break;
  40810. }
  40811. return shapePaths;
  40812. };
  40813. var path3D;
  40814. var pathArray;
  40815. if (instance) {
  40816. path3D = (instance.path3D).update(curve);
  40817. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  40818. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  40819. return instance;
  40820. }
  40821. // extruded shape creation
  40822. path3D = new BABYLON.Path3D(curve);
  40823. var newShapePaths = new Array();
  40824. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40825. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  40826. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  40827. extrudedGeneric.pathArray = pathArray;
  40828. extrudedGeneric.path3D = path3D;
  40829. extrudedGeneric.cap = cap;
  40830. return extrudedGeneric;
  40831. };
  40832. return MeshBuilder;
  40833. }());
  40834. BABYLON.MeshBuilder = MeshBuilder;
  40835. })(BABYLON || (BABYLON = {}));
  40836. //# sourceMappingURL=babylon.meshBuilder.js.map
  40837. var BABYLON;
  40838. (function (BABYLON) {
  40839. var Layer = (function () {
  40840. function Layer(name, imgUrl, scene, isBackground, color) {
  40841. this.name = name;
  40842. this.scale = new BABYLON.Vector2(1, 1);
  40843. this.offset = new BABYLON.Vector2(0, 0);
  40844. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  40845. this.layerMask = 0x0FFFFFFF;
  40846. this._vertexBuffers = {};
  40847. // Events
  40848. /**
  40849. * An event triggered when the layer is disposed.
  40850. * @type {BABYLON.Observable}
  40851. */
  40852. this.onDisposeObservable = new BABYLON.Observable();
  40853. /**
  40854. * An event triggered before rendering the scene
  40855. * @type {BABYLON.Observable}
  40856. */
  40857. this.onBeforeRenderObservable = new BABYLON.Observable();
  40858. /**
  40859. * An event triggered after rendering the scene
  40860. * @type {BABYLON.Observable}
  40861. */
  40862. this.onAfterRenderObservable = new BABYLON.Observable();
  40863. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  40864. this.isBackground = isBackground === undefined ? true : isBackground;
  40865. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  40866. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40867. this._scene.layers.push(this);
  40868. var engine = this._scene.getEngine();
  40869. // VBO
  40870. var vertices = [];
  40871. vertices.push(1, 1);
  40872. vertices.push(-1, 1);
  40873. vertices.push(-1, -1);
  40874. vertices.push(1, -1);
  40875. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40876. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  40877. this._createIndexBuffer();
  40878. // Effects
  40879. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  40880. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  40881. }
  40882. Object.defineProperty(Layer.prototype, "onDispose", {
  40883. set: function (callback) {
  40884. if (this._onDisposeObserver) {
  40885. this.onDisposeObservable.remove(this._onDisposeObserver);
  40886. }
  40887. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40888. },
  40889. enumerable: true,
  40890. configurable: true
  40891. });
  40892. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  40893. set: function (callback) {
  40894. if (this._onBeforeRenderObserver) {
  40895. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40896. }
  40897. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40898. },
  40899. enumerable: true,
  40900. configurable: true
  40901. });
  40902. Object.defineProperty(Layer.prototype, "onAfterRender", {
  40903. set: function (callback) {
  40904. if (this._onAfterRenderObserver) {
  40905. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40906. }
  40907. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40908. },
  40909. enumerable: true,
  40910. configurable: true
  40911. });
  40912. Layer.prototype._createIndexBuffer = function () {
  40913. var engine = this._scene.getEngine();
  40914. // Indices
  40915. var indices = [];
  40916. indices.push(0);
  40917. indices.push(1);
  40918. indices.push(2);
  40919. indices.push(0);
  40920. indices.push(2);
  40921. indices.push(3);
  40922. this._indexBuffer = engine.createIndexBuffer(indices);
  40923. };
  40924. Layer.prototype._rebuild = function () {
  40925. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  40926. this._createIndexBuffer();
  40927. };
  40928. Layer.prototype.render = function () {
  40929. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  40930. // Check
  40931. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  40932. return;
  40933. var engine = this._scene.getEngine();
  40934. this.onBeforeRenderObservable.notifyObservers(this);
  40935. // Render
  40936. engine.enableEffect(currentEffect);
  40937. engine.setState(false);
  40938. // Texture
  40939. currentEffect.setTexture("textureSampler", this.texture);
  40940. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  40941. // Color
  40942. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  40943. // Scale / offset
  40944. currentEffect.setVector2("offset", this.offset);
  40945. currentEffect.setVector2("scale", this.scale);
  40946. // VBOs
  40947. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  40948. // Draw order
  40949. if (!this.alphaTest) {
  40950. engine.setAlphaMode(this.alphaBlendingMode);
  40951. engine.draw(true, 0, 6);
  40952. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40953. }
  40954. else {
  40955. engine.draw(true, 0, 6);
  40956. }
  40957. this.onAfterRenderObservable.notifyObservers(this);
  40958. };
  40959. Layer.prototype.dispose = function () {
  40960. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40961. if (vertexBuffer) {
  40962. vertexBuffer.dispose();
  40963. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40964. }
  40965. if (this._indexBuffer) {
  40966. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40967. this._indexBuffer = null;
  40968. }
  40969. if (this.texture) {
  40970. this.texture.dispose();
  40971. this.texture = null;
  40972. }
  40973. // Remove from scene
  40974. var index = this._scene.layers.indexOf(this);
  40975. this._scene.layers.splice(index, 1);
  40976. // Callback
  40977. this.onDisposeObservable.notifyObservers(this);
  40978. this.onDisposeObservable.clear();
  40979. this.onAfterRenderObservable.clear();
  40980. this.onBeforeRenderObservable.clear();
  40981. };
  40982. return Layer;
  40983. }());
  40984. BABYLON.Layer = Layer;
  40985. })(BABYLON || (BABYLON = {}));
  40986. //# sourceMappingURL=babylon.layer.js.map
  40987. var BABYLON;
  40988. (function (BABYLON) {
  40989. var BlurPostProcess = (function (_super) {
  40990. __extends(BlurPostProcess, _super);
  40991. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  40992. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40993. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40994. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  40995. _this.direction = direction;
  40996. _this._packedFloat = false;
  40997. _this.onApplyObservable.add(function (effect) {
  40998. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  40999. });
  41000. _this.kernel = kernel;
  41001. return _this;
  41002. }
  41003. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  41004. /**
  41005. * Gets the length in pixels of the blur sample region
  41006. */
  41007. get: function () {
  41008. return this._idealKernel;
  41009. },
  41010. /**
  41011. * Sets the length in pixels of the blur sample region
  41012. */
  41013. set: function (v) {
  41014. if (this._idealKernel === v) {
  41015. return;
  41016. }
  41017. v = Math.max(v, 1);
  41018. this._idealKernel = v;
  41019. this._kernel = this._nearestBestKernel(v);
  41020. this._updateParameters();
  41021. },
  41022. enumerable: true,
  41023. configurable: true
  41024. });
  41025. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  41026. /**
  41027. * Gets wether or not the blur is unpacking/repacking floats
  41028. */
  41029. get: function () {
  41030. return this._packedFloat;
  41031. },
  41032. /**
  41033. * Sets wether or not the blur needs to unpack/repack floats
  41034. */
  41035. set: function (v) {
  41036. if (this._packedFloat === v) {
  41037. return;
  41038. }
  41039. this._packedFloat = v;
  41040. this._updateParameters();
  41041. },
  41042. enumerable: true,
  41043. configurable: true
  41044. });
  41045. BlurPostProcess.prototype._updateParameters = function () {
  41046. // Generate sampling offsets and weights
  41047. var N = this._kernel;
  41048. var centerIndex = (N - 1) / 2;
  41049. // Generate Gaussian sampling weights over kernel
  41050. var offsets = [];
  41051. var weights = [];
  41052. var totalWeight = 0;
  41053. for (var i = 0; i < N; i++) {
  41054. var u = i / (N - 1);
  41055. var w = this._gaussianWeight(u * 2.0 - 1);
  41056. offsets[i] = (i - centerIndex);
  41057. weights[i] = w;
  41058. totalWeight += w;
  41059. }
  41060. // Normalize weights
  41061. for (var i = 0; i < weights.length; i++) {
  41062. weights[i] /= totalWeight;
  41063. }
  41064. // Optimize: combine samples to take advantage of hardware linear sampling
  41065. // Walk from left to center, combining pairs (symmetrically)
  41066. var linearSamplingWeights = [];
  41067. var linearSamplingOffsets = [];
  41068. var linearSamplingMap = [];
  41069. for (var i = 0; i <= centerIndex; i += 2) {
  41070. var j = Math.min(i + 1, Math.floor(centerIndex));
  41071. var singleCenterSample = i === j;
  41072. if (singleCenterSample) {
  41073. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  41074. }
  41075. else {
  41076. var sharedCell = j === centerIndex;
  41077. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  41078. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  41079. if (offsetLinear === 0) {
  41080. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  41081. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  41082. }
  41083. else {
  41084. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  41085. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  41086. }
  41087. }
  41088. }
  41089. for (var i = 0; i < linearSamplingMap.length; i++) {
  41090. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  41091. linearSamplingWeights[i] = linearSamplingMap[i].w;
  41092. }
  41093. // Replace with optimized
  41094. offsets = linearSamplingOffsets;
  41095. weights = linearSamplingWeights;
  41096. // Generate shaders
  41097. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  41098. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  41099. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  41100. var defines = "";
  41101. for (var i = 0; i < varyingCount; i++) {
  41102. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  41103. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  41104. }
  41105. var depCount = 0;
  41106. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  41107. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  41108. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  41109. depCount++;
  41110. }
  41111. if (this.packedFloat) {
  41112. defines += "#define PACKEDFLOAT 1";
  41113. }
  41114. this.updateEffect(defines, null, null, {
  41115. varyingCount: varyingCount,
  41116. depCount: depCount
  41117. });
  41118. };
  41119. /**
  41120. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  41121. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  41122. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  41123. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  41124. * The gaps between physical kernels are compensated for in the weighting of the samples
  41125. * @param idealKernel Ideal blur kernel.
  41126. * @return Nearest best kernel.
  41127. */
  41128. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  41129. var v = Math.round(idealKernel);
  41130. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  41131. var k = _a[_i];
  41132. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  41133. return Math.max(k, 3);
  41134. }
  41135. }
  41136. return Math.max(v, 3);
  41137. };
  41138. /**
  41139. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  41140. * @param x The point on the Gaussian distribution to sample.
  41141. * @return the value of the Gaussian function at x.
  41142. */
  41143. BlurPostProcess.prototype._gaussianWeight = function (x) {
  41144. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  41145. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  41146. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  41147. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  41148. // truncated at around 1.3% of peak strength.
  41149. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  41150. var sigma = (1 / 3);
  41151. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  41152. var exponent = -((x * x) / (2.0 * sigma * sigma));
  41153. var weight = (1.0 / denominator) * Math.exp(exponent);
  41154. return weight;
  41155. };
  41156. /**
  41157. * Generates a string that can be used as a floating point number in GLSL.
  41158. * @param x Value to print.
  41159. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  41160. * @return GLSL float string.
  41161. */
  41162. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  41163. if (decimalFigures === void 0) { decimalFigures = 8; }
  41164. return x.toFixed(decimalFigures).replace(/0+$/, '');
  41165. };
  41166. return BlurPostProcess;
  41167. }(BABYLON.PostProcess));
  41168. BABYLON.BlurPostProcess = BlurPostProcess;
  41169. })(BABYLON || (BABYLON = {}));
  41170. //# sourceMappingURL=babylon.blurPostProcess.js.map
  41171. var BABYLON;
  41172. (function (BABYLON) {
  41173. var FxaaPostProcess = (function (_super) {
  41174. __extends(FxaaPostProcess, _super);
  41175. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41176. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41177. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  41178. _this.onApplyObservable.add(function (effect) {
  41179. var texelSize = _this.texelSize;
  41180. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  41181. });
  41182. return _this;
  41183. }
  41184. return FxaaPostProcess;
  41185. }(BABYLON.PostProcess));
  41186. BABYLON.FxaaPostProcess = FxaaPostProcess;
  41187. })(BABYLON || (BABYLON = {}));
  41188. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  41189. var BABYLON;
  41190. (function (BABYLON) {
  41191. var HighlightsPostProcess = (function (_super) {
  41192. __extends(HighlightsPostProcess, _super);
  41193. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41194. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41195. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41196. }
  41197. return HighlightsPostProcess;
  41198. }(BABYLON.PostProcess));
  41199. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  41200. })(BABYLON || (BABYLON = {}));
  41201. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  41202. var BABYLON;
  41203. (function (BABYLON) {
  41204. var ImageProcessingPostProcess = (function (_super) {
  41205. __extends(ImageProcessingPostProcess, _super);
  41206. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41207. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41208. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  41209. _this._fromLinearSpace = true;
  41210. /**
  41211. * Defines cache preventing GC.
  41212. */
  41213. _this._defines = {
  41214. IMAGEPROCESSING: false,
  41215. VIGNETTE: false,
  41216. VIGNETTEBLENDMODEMULTIPLY: false,
  41217. VIGNETTEBLENDMODEOPAQUE: false,
  41218. TONEMAPPING: false,
  41219. CONTRAST: false,
  41220. COLORCURVES: false,
  41221. COLORGRADING: false,
  41222. FROMLINEARSPACE: false,
  41223. SAMPLER3DGREENDEPTH: false,
  41224. SAMPLER3DBGRMAP: false,
  41225. IMAGEPROCESSINGPOSTPROCESS: false,
  41226. EXPOSURE: false,
  41227. };
  41228. // Setup the default processing configuration to the scene.
  41229. _this._attachImageProcessingConfiguration(null, true);
  41230. _this.imageProcessingConfiguration.applyByPostProcess = true;
  41231. _this.onApply = function (effect) {
  41232. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  41233. };
  41234. return _this;
  41235. }
  41236. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  41237. /**
  41238. * Gets the image processing configuration used either in this material.
  41239. */
  41240. get: function () {
  41241. return this._imageProcessingConfiguration;
  41242. },
  41243. /**
  41244. * Sets the Default image processing configuration used either in the this material.
  41245. *
  41246. * If sets to null, the scene one is in use.
  41247. */
  41248. set: function (value) {
  41249. this._attachImageProcessingConfiguration(value);
  41250. },
  41251. enumerable: true,
  41252. configurable: true
  41253. });
  41254. /**
  41255. * Attaches a new image processing configuration to the PBR Material.
  41256. * @param configuration
  41257. */
  41258. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  41259. var _this = this;
  41260. if (doNotBuild === void 0) { doNotBuild = false; }
  41261. if (configuration === this._imageProcessingConfiguration) {
  41262. return;
  41263. }
  41264. // Detaches observer.
  41265. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41266. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41267. }
  41268. // Pick the scene configuration if needed.
  41269. if (!configuration) {
  41270. var camera = this.getCamera();
  41271. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  41272. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  41273. }
  41274. else {
  41275. this._imageProcessingConfiguration = configuration;
  41276. }
  41277. // Attaches observer.
  41278. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41279. _this._updateParameters();
  41280. });
  41281. // Ensure the effect will be rebuilt.
  41282. if (!doNotBuild) {
  41283. this._updateParameters();
  41284. }
  41285. };
  41286. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  41287. /**
  41288. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  41289. */
  41290. get: function () {
  41291. return this.imageProcessingConfiguration.colorCurves;
  41292. },
  41293. /**
  41294. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  41295. */
  41296. set: function (value) {
  41297. this.imageProcessingConfiguration.colorCurves = value;
  41298. },
  41299. enumerable: true,
  41300. configurable: true
  41301. });
  41302. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  41303. /**
  41304. * Gets wether the color curves effect is enabled.
  41305. */
  41306. get: function () {
  41307. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41308. },
  41309. /**
  41310. * Sets wether the color curves effect is enabled.
  41311. */
  41312. set: function (value) {
  41313. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41314. },
  41315. enumerable: true,
  41316. configurable: true
  41317. });
  41318. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  41319. /**
  41320. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  41321. */
  41322. get: function () {
  41323. return this.imageProcessingConfiguration.colorGradingTexture;
  41324. },
  41325. /**
  41326. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  41327. */
  41328. set: function (value) {
  41329. this.imageProcessingConfiguration.colorGradingTexture = value;
  41330. },
  41331. enumerable: true,
  41332. configurable: true
  41333. });
  41334. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  41335. /**
  41336. * Gets wether the color grading effect is enabled.
  41337. */
  41338. get: function () {
  41339. return this.imageProcessingConfiguration.colorGradingEnabled;
  41340. },
  41341. /**
  41342. * Gets wether the color grading effect is enabled.
  41343. */
  41344. set: function (value) {
  41345. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41346. },
  41347. enumerable: true,
  41348. configurable: true
  41349. });
  41350. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  41351. /**
  41352. * Gets exposure used in the effect.
  41353. */
  41354. get: function () {
  41355. return this.imageProcessingConfiguration.exposure;
  41356. },
  41357. /**
  41358. * Sets exposure used in the effect.
  41359. */
  41360. set: function (value) {
  41361. this.imageProcessingConfiguration.exposure = value;
  41362. },
  41363. enumerable: true,
  41364. configurable: true
  41365. });
  41366. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  41367. /**
  41368. * Gets wether tonemapping is enabled or not.
  41369. */
  41370. get: function () {
  41371. return this._imageProcessingConfiguration.toneMappingEnabled;
  41372. },
  41373. /**
  41374. * Sets wether tonemapping is enabled or not
  41375. */
  41376. set: function (value) {
  41377. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41378. },
  41379. enumerable: true,
  41380. configurable: true
  41381. });
  41382. ;
  41383. ;
  41384. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  41385. /**
  41386. * Gets contrast used in the effect.
  41387. */
  41388. get: function () {
  41389. return this.imageProcessingConfiguration.contrast;
  41390. },
  41391. /**
  41392. * Sets contrast used in the effect.
  41393. */
  41394. set: function (value) {
  41395. this.imageProcessingConfiguration.contrast = value;
  41396. },
  41397. enumerable: true,
  41398. configurable: true
  41399. });
  41400. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  41401. /**
  41402. * Gets Vignette stretch size.
  41403. */
  41404. get: function () {
  41405. return this.imageProcessingConfiguration.vignetteStretch;
  41406. },
  41407. /**
  41408. * Sets Vignette stretch size.
  41409. */
  41410. set: function (value) {
  41411. this.imageProcessingConfiguration.vignetteStretch = value;
  41412. },
  41413. enumerable: true,
  41414. configurable: true
  41415. });
  41416. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  41417. /**
  41418. * Gets Vignette centre X Offset.
  41419. */
  41420. get: function () {
  41421. return this.imageProcessingConfiguration.vignetteCentreX;
  41422. },
  41423. /**
  41424. * Sets Vignette centre X Offset.
  41425. */
  41426. set: function (value) {
  41427. this.imageProcessingConfiguration.vignetteCentreX = value;
  41428. },
  41429. enumerable: true,
  41430. configurable: true
  41431. });
  41432. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  41433. /**
  41434. * Gets Vignette centre Y Offset.
  41435. */
  41436. get: function () {
  41437. return this.imageProcessingConfiguration.vignetteCentreY;
  41438. },
  41439. /**
  41440. * Sets Vignette centre Y Offset.
  41441. */
  41442. set: function (value) {
  41443. this.imageProcessingConfiguration.vignetteCentreY = value;
  41444. },
  41445. enumerable: true,
  41446. configurable: true
  41447. });
  41448. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  41449. /**
  41450. * Gets Vignette weight or intensity of the vignette effect.
  41451. */
  41452. get: function () {
  41453. return this.imageProcessingConfiguration.vignetteWeight;
  41454. },
  41455. /**
  41456. * Sets Vignette weight or intensity of the vignette effect.
  41457. */
  41458. set: function (value) {
  41459. this.imageProcessingConfiguration.vignetteWeight = value;
  41460. },
  41461. enumerable: true,
  41462. configurable: true
  41463. });
  41464. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  41465. /**
  41466. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41467. * if vignetteEnabled is set to true.
  41468. */
  41469. get: function () {
  41470. return this.imageProcessingConfiguration.vignetteColor;
  41471. },
  41472. /**
  41473. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41474. * if vignetteEnabled is set to true.
  41475. */
  41476. set: function (value) {
  41477. this.imageProcessingConfiguration.vignetteColor = value;
  41478. },
  41479. enumerable: true,
  41480. configurable: true
  41481. });
  41482. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  41483. /**
  41484. * Gets Camera field of view used by the Vignette effect.
  41485. */
  41486. get: function () {
  41487. return this.imageProcessingConfiguration.vignetteCameraFov;
  41488. },
  41489. /**
  41490. * Sets Camera field of view used by the Vignette effect.
  41491. */
  41492. set: function (value) {
  41493. this.imageProcessingConfiguration.vignetteCameraFov = value;
  41494. },
  41495. enumerable: true,
  41496. configurable: true
  41497. });
  41498. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  41499. /**
  41500. * Gets the vignette blend mode allowing different kind of effect.
  41501. */
  41502. get: function () {
  41503. return this.imageProcessingConfiguration.vignetteBlendMode;
  41504. },
  41505. /**
  41506. * Sets the vignette blend mode allowing different kind of effect.
  41507. */
  41508. set: function (value) {
  41509. this.imageProcessingConfiguration.vignetteBlendMode = value;
  41510. },
  41511. enumerable: true,
  41512. configurable: true
  41513. });
  41514. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  41515. /**
  41516. * Gets wether the vignette effect is enabled.
  41517. */
  41518. get: function () {
  41519. return this.imageProcessingConfiguration.vignetteEnabled;
  41520. },
  41521. /**
  41522. * Sets wether the vignette effect is enabled.
  41523. */
  41524. set: function (value) {
  41525. this.imageProcessingConfiguration.vignetteEnabled = value;
  41526. },
  41527. enumerable: true,
  41528. configurable: true
  41529. });
  41530. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  41531. /**
  41532. * Gets wether the input of the processing is in Gamma or Linear Space.
  41533. */
  41534. get: function () {
  41535. return this._fromLinearSpace;
  41536. },
  41537. /**
  41538. * Sets wether the input of the processing is in Gamma or Linear Space.
  41539. */
  41540. set: function (value) {
  41541. if (this._fromLinearSpace === value) {
  41542. return;
  41543. }
  41544. this._fromLinearSpace = value;
  41545. this._updateParameters();
  41546. },
  41547. enumerable: true,
  41548. configurable: true
  41549. });
  41550. ImageProcessingPostProcess.prototype.getClassName = function () {
  41551. return "ImageProcessingPostProcess";
  41552. };
  41553. ImageProcessingPostProcess.prototype._updateParameters = function () {
  41554. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  41555. this.imageProcessingConfiguration.prepareDefines(this._defines);
  41556. var defines = "";
  41557. for (var define in this._defines) {
  41558. if (this._defines[define]) {
  41559. defines += "#define " + define + ";\r\n";
  41560. }
  41561. }
  41562. var samplers = ["textureSampler"];
  41563. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  41564. var uniforms = ["scale"];
  41565. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  41566. this.updateEffect(defines, uniforms, samplers);
  41567. };
  41568. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  41569. _super.prototype.dispose.call(this, camera);
  41570. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41571. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41572. }
  41573. this.imageProcessingConfiguration.applyByPostProcess = false;
  41574. };
  41575. __decorate([
  41576. BABYLON.serialize()
  41577. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  41578. return ImageProcessingPostProcess;
  41579. }(BABYLON.PostProcess));
  41580. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  41581. })(BABYLON || (BABYLON = {}));
  41582. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  41583. var BABYLON;
  41584. (function (BABYLON) {
  41585. /**
  41586. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41587. * It can help converting any input color in a desired output one. This can then be used to create effects
  41588. * from sepia, black and white to sixties or futuristic rendering...
  41589. *
  41590. * The only supported format is currently 3dl.
  41591. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41592. */
  41593. var ColorGradingTexture = (function (_super) {
  41594. __extends(ColorGradingTexture, _super);
  41595. /**
  41596. * Instantiates a ColorGradingTexture from the following parameters.
  41597. *
  41598. * @param url The location of the color gradind data (currently only supporting 3dl)
  41599. * @param scene The scene the texture will be used in
  41600. */
  41601. function ColorGradingTexture(url, scene) {
  41602. var _this = _super.call(this, scene) || this;
  41603. if (!url) {
  41604. return _this;
  41605. }
  41606. _this._textureMatrix = BABYLON.Matrix.Identity();
  41607. _this.name = url;
  41608. _this.url = url;
  41609. _this.hasAlpha = false;
  41610. _this.isCube = false;
  41611. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41612. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41613. _this.anisotropicFilteringLevel = 1;
  41614. _this._texture = _this._getFromCache(url, true);
  41615. if (!_this._texture) {
  41616. if (!scene.useDelayedTextureLoading) {
  41617. _this.loadTexture();
  41618. }
  41619. else {
  41620. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41621. }
  41622. }
  41623. return _this;
  41624. }
  41625. /**
  41626. * Returns the texture matrix used in most of the material.
  41627. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41628. */
  41629. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41630. return this._textureMatrix;
  41631. };
  41632. /**
  41633. * Occurs when the file being loaded is a .3dl LUT file.
  41634. */
  41635. ColorGradingTexture.prototype.load3dlTexture = function () {
  41636. var _this = this;
  41637. var mipLevels = 0;
  41638. var floatArrayView = null;
  41639. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41640. this._texture = texture;
  41641. var callback = function (text) {
  41642. var data;
  41643. var tempData;
  41644. var line;
  41645. var lines = text.split('\n');
  41646. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41647. var maxColor = 0;
  41648. for (var i = 0; i < lines.length; i++) {
  41649. line = lines[i];
  41650. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41651. continue;
  41652. if (line.indexOf('#') === 0)
  41653. continue;
  41654. var words = line.split(" ");
  41655. if (size === 0) {
  41656. // Number of space + one
  41657. size = words.length;
  41658. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41659. tempData = new Float32Array(size * size * size * 4);
  41660. continue;
  41661. }
  41662. if (size != 0) {
  41663. var r = Math.max(parseInt(words[0]), 0);
  41664. var g = Math.max(parseInt(words[1]), 0);
  41665. var b = Math.max(parseInt(words[2]), 0);
  41666. maxColor = Math.max(r, maxColor);
  41667. maxColor = Math.max(g, maxColor);
  41668. maxColor = Math.max(b, maxColor);
  41669. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41670. tempData[pixelStorageIndex + 0] = r;
  41671. tempData[pixelStorageIndex + 1] = g;
  41672. tempData[pixelStorageIndex + 2] = b;
  41673. pixelIndexSlice++;
  41674. if (pixelIndexSlice % size == 0) {
  41675. pixelIndexH++;
  41676. pixelIndexSlice = 0;
  41677. if (pixelIndexH % size == 0) {
  41678. pixelIndexW++;
  41679. pixelIndexH = 0;
  41680. }
  41681. }
  41682. }
  41683. }
  41684. for (var i = 0; i < tempData.length; i++) {
  41685. if (i > 0 && (i + 1) % 4 === 0) {
  41686. data[i] = 255;
  41687. }
  41688. else {
  41689. var value = tempData[i];
  41690. data[i] = (value / maxColor * 255);
  41691. }
  41692. }
  41693. texture.updateSize(size * size, size);
  41694. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41695. };
  41696. BABYLON.Tools.LoadFile(this.url, callback);
  41697. return this._texture;
  41698. };
  41699. /**
  41700. * Starts the loading process of the texture.
  41701. */
  41702. ColorGradingTexture.prototype.loadTexture = function () {
  41703. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41704. this.load3dlTexture();
  41705. }
  41706. };
  41707. /**
  41708. * Clones the color gradind texture.
  41709. */
  41710. ColorGradingTexture.prototype.clone = function () {
  41711. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41712. // Base texture
  41713. newTexture.level = this.level;
  41714. return newTexture;
  41715. };
  41716. /**
  41717. * Called during delayed load for textures.
  41718. */
  41719. ColorGradingTexture.prototype.delayLoad = function () {
  41720. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41721. return;
  41722. }
  41723. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41724. this._texture = this._getFromCache(this.url, true);
  41725. if (!this._texture) {
  41726. this.loadTexture();
  41727. }
  41728. };
  41729. /**
  41730. * Parses a color grading texture serialized by Babylon.
  41731. * @param parsedTexture The texture information being parsedTexture
  41732. * @param scene The scene to load the texture in
  41733. * @param rootUrl The root url of the data assets to load
  41734. * @return A color gradind texture
  41735. */
  41736. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41737. var texture = null;
  41738. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41739. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  41740. texture.name = parsedTexture.name;
  41741. texture.level = parsedTexture.level;
  41742. }
  41743. return texture;
  41744. };
  41745. /**
  41746. * Serializes the LUT texture to json format.
  41747. */
  41748. ColorGradingTexture.prototype.serialize = function () {
  41749. if (!this.name) {
  41750. return null;
  41751. }
  41752. var serializationObject = {};
  41753. serializationObject.name = this.name;
  41754. serializationObject.level = this.level;
  41755. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41756. return serializationObject;
  41757. };
  41758. /**
  41759. * Empty line regex stored for GC.
  41760. */
  41761. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41762. return ColorGradingTexture;
  41763. }(BABYLON.BaseTexture));
  41764. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41765. })(BABYLON || (BABYLON = {}));
  41766. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41767. var BABYLON;
  41768. (function (BABYLON) {
  41769. /**
  41770. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41771. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41772. * 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;
  41773. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41774. */
  41775. var ColorCurves = (function () {
  41776. function ColorCurves() {
  41777. this._dirty = true;
  41778. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41779. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41780. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41781. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41782. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41783. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41784. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41785. this._globalHue = 30;
  41786. this._globalDensity = 0;
  41787. this._globalSaturation = 0;
  41788. this._globalExposure = 0;
  41789. this._highlightsHue = 30;
  41790. this._highlightsDensity = 0;
  41791. this._highlightsSaturation = 0;
  41792. this._highlightsExposure = 0;
  41793. this._midtonesHue = 30;
  41794. this._midtonesDensity = 0;
  41795. this._midtonesSaturation = 0;
  41796. this._midtonesExposure = 0;
  41797. this._shadowsHue = 30;
  41798. this._shadowsDensity = 0;
  41799. this._shadowsSaturation = 0;
  41800. this._shadowsExposure = 0;
  41801. }
  41802. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41803. /**
  41804. * Gets the global Hue value.
  41805. * 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).
  41806. */
  41807. get: function () {
  41808. return this._globalHue;
  41809. },
  41810. /**
  41811. * Sets the global Hue value.
  41812. * 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).
  41813. */
  41814. set: function (value) {
  41815. this._globalHue = value;
  41816. this._dirty = true;
  41817. },
  41818. enumerable: true,
  41819. configurable: true
  41820. });
  41821. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41822. /**
  41823. * Gets the global Density value.
  41824. * 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.
  41825. * Values less than zero provide a filter of opposite hue.
  41826. */
  41827. get: function () {
  41828. return this._globalDensity;
  41829. },
  41830. /**
  41831. * Sets the global Density value.
  41832. * 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.
  41833. * Values less than zero provide a filter of opposite hue.
  41834. */
  41835. set: function (value) {
  41836. this._globalDensity = value;
  41837. this._dirty = true;
  41838. },
  41839. enumerable: true,
  41840. configurable: true
  41841. });
  41842. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41843. /**
  41844. * Gets the global Saturation value.
  41845. * 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.
  41846. */
  41847. get: function () {
  41848. return this._globalSaturation;
  41849. },
  41850. /**
  41851. * Sets the global Saturation value.
  41852. * 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.
  41853. */
  41854. set: function (value) {
  41855. this._globalSaturation = value;
  41856. this._dirty = true;
  41857. },
  41858. enumerable: true,
  41859. configurable: true
  41860. });
  41861. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41862. /**
  41863. * Gets the highlights Hue value.
  41864. * 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).
  41865. */
  41866. get: function () {
  41867. return this._highlightsHue;
  41868. },
  41869. /**
  41870. * Sets the highlights Hue value.
  41871. * 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).
  41872. */
  41873. set: function (value) {
  41874. this._highlightsHue = value;
  41875. this._dirty = true;
  41876. },
  41877. enumerable: true,
  41878. configurable: true
  41879. });
  41880. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41881. /**
  41882. * Gets the highlights Density value.
  41883. * 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.
  41884. * Values less than zero provide a filter of opposite hue.
  41885. */
  41886. get: function () {
  41887. return this._highlightsDensity;
  41888. },
  41889. /**
  41890. * Sets the highlights Density value.
  41891. * 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.
  41892. * Values less than zero provide a filter of opposite hue.
  41893. */
  41894. set: function (value) {
  41895. this._highlightsDensity = value;
  41896. this._dirty = true;
  41897. },
  41898. enumerable: true,
  41899. configurable: true
  41900. });
  41901. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41902. /**
  41903. * Gets the highlights Saturation value.
  41904. * 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.
  41905. */
  41906. get: function () {
  41907. return this._highlightsSaturation;
  41908. },
  41909. /**
  41910. * Sets the highlights Saturation value.
  41911. * 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.
  41912. */
  41913. set: function (value) {
  41914. this._highlightsSaturation = value;
  41915. this._dirty = true;
  41916. },
  41917. enumerable: true,
  41918. configurable: true
  41919. });
  41920. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41921. /**
  41922. * Gets the highlights Exposure value.
  41923. * 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.
  41924. */
  41925. get: function () {
  41926. return this._highlightsExposure;
  41927. },
  41928. /**
  41929. * Sets the highlights Exposure value.
  41930. * 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.
  41931. */
  41932. set: function (value) {
  41933. this._highlightsExposure = value;
  41934. this._dirty = true;
  41935. },
  41936. enumerable: true,
  41937. configurable: true
  41938. });
  41939. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41940. /**
  41941. * Gets the midtones Hue value.
  41942. * 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).
  41943. */
  41944. get: function () {
  41945. return this._midtonesHue;
  41946. },
  41947. /**
  41948. * Sets the midtones Hue value.
  41949. * 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).
  41950. */
  41951. set: function (value) {
  41952. this._midtonesHue = value;
  41953. this._dirty = true;
  41954. },
  41955. enumerable: true,
  41956. configurable: true
  41957. });
  41958. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41959. /**
  41960. * Gets the midtones Density value.
  41961. * 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.
  41962. * Values less than zero provide a filter of opposite hue.
  41963. */
  41964. get: function () {
  41965. return this._midtonesDensity;
  41966. },
  41967. /**
  41968. * Sets the midtones Density value.
  41969. * 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.
  41970. * Values less than zero provide a filter of opposite hue.
  41971. */
  41972. set: function (value) {
  41973. this._midtonesDensity = value;
  41974. this._dirty = true;
  41975. },
  41976. enumerable: true,
  41977. configurable: true
  41978. });
  41979. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41980. /**
  41981. * Gets the midtones Saturation value.
  41982. * 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.
  41983. */
  41984. get: function () {
  41985. return this._midtonesSaturation;
  41986. },
  41987. /**
  41988. * Sets the midtones Saturation value.
  41989. * 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.
  41990. */
  41991. set: function (value) {
  41992. this._midtonesSaturation = value;
  41993. this._dirty = true;
  41994. },
  41995. enumerable: true,
  41996. configurable: true
  41997. });
  41998. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41999. /**
  42000. * Gets the midtones Exposure value.
  42001. * 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.
  42002. */
  42003. get: function () {
  42004. return this._midtonesExposure;
  42005. },
  42006. /**
  42007. * Sets the midtones Exposure value.
  42008. * 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.
  42009. */
  42010. set: function (value) {
  42011. this._midtonesExposure = value;
  42012. this._dirty = true;
  42013. },
  42014. enumerable: true,
  42015. configurable: true
  42016. });
  42017. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42018. /**
  42019. * Gets the shadows Hue value.
  42020. * 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).
  42021. */
  42022. get: function () {
  42023. return this._shadowsHue;
  42024. },
  42025. /**
  42026. * Sets the shadows Hue value.
  42027. * 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).
  42028. */
  42029. set: function (value) {
  42030. this._shadowsHue = value;
  42031. this._dirty = true;
  42032. },
  42033. enumerable: true,
  42034. configurable: true
  42035. });
  42036. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42037. /**
  42038. * Gets the shadows Density value.
  42039. * 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.
  42040. * Values less than zero provide a filter of opposite hue.
  42041. */
  42042. get: function () {
  42043. return this._shadowsDensity;
  42044. },
  42045. /**
  42046. * Sets the shadows Density value.
  42047. * 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.
  42048. * Values less than zero provide a filter of opposite hue.
  42049. */
  42050. set: function (value) {
  42051. this._shadowsDensity = value;
  42052. this._dirty = true;
  42053. },
  42054. enumerable: true,
  42055. configurable: true
  42056. });
  42057. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42058. /**
  42059. * Gets the shadows Saturation value.
  42060. * 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.
  42061. */
  42062. get: function () {
  42063. return this._shadowsSaturation;
  42064. },
  42065. /**
  42066. * Sets the shadows Saturation value.
  42067. * 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.
  42068. */
  42069. set: function (value) {
  42070. this._shadowsSaturation = value;
  42071. this._dirty = true;
  42072. },
  42073. enumerable: true,
  42074. configurable: true
  42075. });
  42076. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42077. /**
  42078. * Gets the shadows Exposure value.
  42079. * 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.
  42080. */
  42081. get: function () {
  42082. return this._shadowsExposure;
  42083. },
  42084. /**
  42085. * Sets the shadows Exposure value.
  42086. * 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.
  42087. */
  42088. set: function (value) {
  42089. this._shadowsExposure = value;
  42090. this._dirty = true;
  42091. },
  42092. enumerable: true,
  42093. configurable: true
  42094. });
  42095. ColorCurves.prototype.getClassName = function () {
  42096. return "ColorCurves";
  42097. };
  42098. /**
  42099. * Binds the color curves to the shader.
  42100. * @param colorCurves The color curve to bind
  42101. * @param effect The effect to bind to
  42102. */
  42103. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42104. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42105. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42106. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42107. if (colorCurves._dirty) {
  42108. colorCurves._dirty = false;
  42109. // Fill in global info.
  42110. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42111. // Compute highlights info.
  42112. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42113. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42114. // Compute midtones info.
  42115. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42116. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42117. // Compute shadows info.
  42118. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42119. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42120. // Compute deltas (neutral is midtones).
  42121. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42122. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42123. }
  42124. if (effect) {
  42125. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42126. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42127. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42128. }
  42129. };
  42130. /**
  42131. * Prepare the list of uniforms associated with the ColorCurves effects.
  42132. * @param uniformsList The list of uniforms used in the effect
  42133. */
  42134. ColorCurves.PrepareUniforms = function (uniformsList) {
  42135. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42136. };
  42137. /**
  42138. * Returns color grading data based on a hue, density, saturation and exposure value.
  42139. * @param filterHue The hue of the color filter.
  42140. * @param filterDensity The density of the color filter.
  42141. * @param saturation The saturation.
  42142. * @param exposure The exposure.
  42143. * @param result The result data container.
  42144. */
  42145. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42146. if (hue == null) {
  42147. return;
  42148. }
  42149. hue = ColorCurves.clamp(hue, 0, 360);
  42150. density = ColorCurves.clamp(density, -100, 100);
  42151. saturation = ColorCurves.clamp(saturation, -100, 100);
  42152. exposure = ColorCurves.clamp(exposure, -100, 100);
  42153. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42154. // so that the maximum filter density is only 50% control. This provides fine control
  42155. // for small values and reasonable range.
  42156. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42157. density *= 0.5;
  42158. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42159. if (density < 0) {
  42160. density *= -1;
  42161. hue = (hue + 180) % 360;
  42162. }
  42163. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42164. result.scaleToRef(2, result);
  42165. result.a = 1 + 0.01 * saturation;
  42166. };
  42167. /**
  42168. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42169. * @param value The input slider value in range [-100,100].
  42170. * @returns Adjusted value.
  42171. */
  42172. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42173. value /= 100;
  42174. var x = Math.abs(value);
  42175. x = Math.pow(x, 2);
  42176. if (value < 0) {
  42177. x *= -1;
  42178. }
  42179. x *= 100;
  42180. return x;
  42181. };
  42182. /**
  42183. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42184. * @param hue The hue (H) input.
  42185. * @param saturation The saturation (S) input.
  42186. * @param brightness The brightness (B) input.
  42187. * @result An RGBA color represented as Vector4.
  42188. */
  42189. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42190. var h = ColorCurves.clamp(hue, 0, 360);
  42191. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42192. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42193. if (s === 0) {
  42194. result.r = v;
  42195. result.g = v;
  42196. result.b = v;
  42197. }
  42198. else {
  42199. // sector 0 to 5
  42200. h /= 60;
  42201. var i = Math.floor(h);
  42202. // fractional part of h
  42203. var f = h - i;
  42204. var p = v * (1 - s);
  42205. var q = v * (1 - s * f);
  42206. var t = v * (1 - s * (1 - f));
  42207. switch (i) {
  42208. case 0:
  42209. result.r = v;
  42210. result.g = t;
  42211. result.b = p;
  42212. break;
  42213. case 1:
  42214. result.r = q;
  42215. result.g = v;
  42216. result.b = p;
  42217. break;
  42218. case 2:
  42219. result.r = p;
  42220. result.g = v;
  42221. result.b = t;
  42222. break;
  42223. case 3:
  42224. result.r = p;
  42225. result.g = q;
  42226. result.b = v;
  42227. break;
  42228. case 4:
  42229. result.r = t;
  42230. result.g = p;
  42231. result.b = v;
  42232. break;
  42233. default:// case 5:
  42234. result.r = v;
  42235. result.g = p;
  42236. result.b = q;
  42237. break;
  42238. }
  42239. }
  42240. result.a = 1;
  42241. };
  42242. /**
  42243. * Returns a value clamped between min and max
  42244. * @param value The value to clamp
  42245. * @param min The minimum of value
  42246. * @param max The maximum of value
  42247. * @returns The clamped value.
  42248. */
  42249. ColorCurves.clamp = function (value, min, max) {
  42250. return Math.min(Math.max(value, min), max);
  42251. };
  42252. /**
  42253. * Clones the current color curve instance.
  42254. * @return The cloned curves
  42255. */
  42256. ColorCurves.prototype.clone = function () {
  42257. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42258. };
  42259. /**
  42260. * Serializes the current color curve instance to a json representation.
  42261. * @return a JSON representation
  42262. */
  42263. ColorCurves.prototype.serialize = function () {
  42264. return BABYLON.SerializationHelper.Serialize(this);
  42265. };
  42266. /**
  42267. * Parses the color curve from a json representation.
  42268. * @param source the JSON source to parse
  42269. * @return The parsed curves
  42270. */
  42271. ColorCurves.Parse = function (source) {
  42272. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42273. };
  42274. __decorate([
  42275. BABYLON.serialize()
  42276. ], ColorCurves.prototype, "_globalHue", void 0);
  42277. __decorate([
  42278. BABYLON.serialize()
  42279. ], ColorCurves.prototype, "_globalDensity", void 0);
  42280. __decorate([
  42281. BABYLON.serialize()
  42282. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42283. __decorate([
  42284. BABYLON.serialize()
  42285. ], ColorCurves.prototype, "_globalExposure", void 0);
  42286. __decorate([
  42287. BABYLON.serialize()
  42288. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42289. __decorate([
  42290. BABYLON.serialize()
  42291. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42292. __decorate([
  42293. BABYLON.serialize()
  42294. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42295. __decorate([
  42296. BABYLON.serialize()
  42297. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42298. __decorate([
  42299. BABYLON.serialize()
  42300. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42301. __decorate([
  42302. BABYLON.serialize()
  42303. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42304. __decorate([
  42305. BABYLON.serialize()
  42306. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42307. __decorate([
  42308. BABYLON.serialize()
  42309. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42310. return ColorCurves;
  42311. }());
  42312. BABYLON.ColorCurves = ColorCurves;
  42313. })(BABYLON || (BABYLON = {}));
  42314. //# sourceMappingURL=babylon.colorCurves.js.map
  42315. var BABYLON;
  42316. (function (BABYLON) {
  42317. var PostProcessRenderPipelineManager = (function () {
  42318. function PostProcessRenderPipelineManager() {
  42319. this._renderPipelines = {};
  42320. }
  42321. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  42322. this._renderPipelines[renderPipeline._name] = renderPipeline;
  42323. };
  42324. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  42325. var renderPipeline = this._renderPipelines[renderPipelineName];
  42326. if (!renderPipeline) {
  42327. return;
  42328. }
  42329. renderPipeline._attachCameras(cameras, unique);
  42330. };
  42331. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  42332. var renderPipeline = this._renderPipelines[renderPipelineName];
  42333. if (!renderPipeline) {
  42334. return;
  42335. }
  42336. renderPipeline._detachCameras(cameras);
  42337. };
  42338. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42339. var renderPipeline = this._renderPipelines[renderPipelineName];
  42340. if (!renderPipeline) {
  42341. return;
  42342. }
  42343. renderPipeline._enableEffect(renderEffectName, cameras);
  42344. };
  42345. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42346. var renderPipeline = this._renderPipelines[renderPipelineName];
  42347. if (!renderPipeline) {
  42348. return;
  42349. }
  42350. renderPipeline._disableEffect(renderEffectName, cameras);
  42351. };
  42352. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  42353. var renderPipeline = this._renderPipelines[renderPipelineName];
  42354. if (!renderPipeline) {
  42355. return;
  42356. }
  42357. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  42358. };
  42359. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  42360. var renderPipeline = this._renderPipelines[renderPipelineName];
  42361. if (!renderPipeline) {
  42362. return;
  42363. }
  42364. renderPipeline._disableDisplayOnlyPass(cameras);
  42365. };
  42366. PostProcessRenderPipelineManager.prototype.update = function () {
  42367. for (var renderPipelineName in this._renderPipelines) {
  42368. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42369. var pipeline = this._renderPipelines[renderPipelineName];
  42370. if (!pipeline.isSupported) {
  42371. pipeline.dispose();
  42372. delete this._renderPipelines[renderPipelineName];
  42373. }
  42374. else {
  42375. pipeline._update();
  42376. }
  42377. }
  42378. }
  42379. };
  42380. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  42381. for (var renderPipelineName in this._renderPipelines) {
  42382. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42383. var pipeline = this._renderPipelines[renderPipelineName];
  42384. pipeline._rebuild();
  42385. }
  42386. }
  42387. };
  42388. PostProcessRenderPipelineManager.prototype.dispose = function () {
  42389. for (var renderPipelineName in this._renderPipelines) {
  42390. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42391. var pipeline = this._renderPipelines[renderPipelineName];
  42392. pipeline.dispose();
  42393. }
  42394. }
  42395. };
  42396. return PostProcessRenderPipelineManager;
  42397. }());
  42398. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  42399. })(BABYLON || (BABYLON = {}));
  42400. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  42401. var BABYLON;
  42402. (function (BABYLON) {
  42403. var PostProcessRenderPass = (function () {
  42404. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  42405. this._enabled = true;
  42406. this._refCount = 0;
  42407. this._name = name;
  42408. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  42409. this.setRenderList(renderList);
  42410. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  42411. this._renderTexture.onAfterRenderObservable.add(afterRender);
  42412. this._scene = scene;
  42413. this._renderList = renderList;
  42414. }
  42415. // private
  42416. PostProcessRenderPass.prototype._incRefCount = function () {
  42417. if (this._refCount === 0) {
  42418. this._scene.customRenderTargets.push(this._renderTexture);
  42419. }
  42420. return ++this._refCount;
  42421. };
  42422. PostProcessRenderPass.prototype._decRefCount = function () {
  42423. this._refCount--;
  42424. if (this._refCount <= 0) {
  42425. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  42426. }
  42427. return this._refCount;
  42428. };
  42429. PostProcessRenderPass.prototype._update = function () {
  42430. this.setRenderList(this._renderList);
  42431. };
  42432. // public
  42433. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  42434. this._renderTexture.renderList = renderList;
  42435. };
  42436. PostProcessRenderPass.prototype.getRenderTexture = function () {
  42437. return this._renderTexture;
  42438. };
  42439. return PostProcessRenderPass;
  42440. }());
  42441. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  42442. })(BABYLON || (BABYLON = {}));
  42443. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  42444. var BABYLON;
  42445. (function (BABYLON) {
  42446. var PostProcessRenderEffect = (function () {
  42447. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  42448. this._engine = engine;
  42449. this._name = name;
  42450. this._singleInstance = singleInstance || true;
  42451. this._getPostProcess = getPostProcess;
  42452. this._cameras = [];
  42453. this._indicesForCamera = [];
  42454. this._postProcesses = {};
  42455. this._renderPasses = {};
  42456. this._renderEffectAsPasses = {};
  42457. }
  42458. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  42459. get: function () {
  42460. for (var index in this._postProcesses) {
  42461. if (!this._postProcesses[index].isSupported) {
  42462. return false;
  42463. }
  42464. }
  42465. return true;
  42466. },
  42467. enumerable: true,
  42468. configurable: true
  42469. });
  42470. PostProcessRenderEffect.prototype._update = function () {
  42471. for (var renderPassName in this._renderPasses) {
  42472. this._renderPasses[renderPassName]._update();
  42473. }
  42474. };
  42475. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  42476. this._renderPasses[renderPass._name] = renderPass;
  42477. this._linkParameters();
  42478. };
  42479. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  42480. delete this._renderPasses[renderPass._name];
  42481. this._linkParameters();
  42482. };
  42483. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  42484. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  42485. this._linkParameters();
  42486. };
  42487. PostProcessRenderEffect.prototype.getPass = function (passName) {
  42488. for (var renderPassName in this._renderPasses) {
  42489. if (renderPassName === passName) {
  42490. return this._renderPasses[passName];
  42491. }
  42492. }
  42493. };
  42494. PostProcessRenderEffect.prototype.emptyPasses = function () {
  42495. this._renderPasses = {};
  42496. this._linkParameters();
  42497. };
  42498. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  42499. var cameraKey;
  42500. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42501. for (var i = 0; i < _cam.length; i++) {
  42502. var camera = _cam[i];
  42503. var cameraName = camera.name;
  42504. if (this._singleInstance) {
  42505. cameraKey = 0;
  42506. }
  42507. else {
  42508. cameraKey = cameraName;
  42509. }
  42510. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  42511. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  42512. if (!this._indicesForCamera[cameraName]) {
  42513. this._indicesForCamera[cameraName] = [];
  42514. }
  42515. this._indicesForCamera[cameraName].push(index);
  42516. if (this._cameras.indexOf(camera) === -1) {
  42517. this._cameras[cameraName] = camera;
  42518. }
  42519. for (var passName in this._renderPasses) {
  42520. this._renderPasses[passName]._incRefCount();
  42521. }
  42522. }
  42523. this._linkParameters();
  42524. };
  42525. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  42526. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42527. for (var i = 0; i < _cam.length; i++) {
  42528. var camera = _cam[i];
  42529. var cameraName = camera.name;
  42530. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42531. var index = this._cameras.indexOf(cameraName);
  42532. this._indicesForCamera.splice(index, 1);
  42533. this._cameras.splice(index, 1);
  42534. for (var passName in this._renderPasses) {
  42535. this._renderPasses[passName]._decRefCount();
  42536. }
  42537. }
  42538. };
  42539. PostProcessRenderEffect.prototype._enable = function (cameras) {
  42540. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42541. for (var i = 0; i < _cam.length; i++) {
  42542. var camera = _cam[i];
  42543. var cameraName = camera.name;
  42544. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  42545. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  42546. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  42547. }
  42548. }
  42549. for (var passName in this._renderPasses) {
  42550. this._renderPasses[passName]._incRefCount();
  42551. }
  42552. }
  42553. };
  42554. PostProcessRenderEffect.prototype._disable = function (cameras) {
  42555. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42556. for (var i = 0; i < _cam.length; i++) {
  42557. var camera = _cam[i];
  42558. var cameraName = camera.Name;
  42559. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42560. for (var passName in this._renderPasses) {
  42561. this._renderPasses[passName]._decRefCount();
  42562. }
  42563. }
  42564. };
  42565. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  42566. if (this._singleInstance) {
  42567. return this._postProcesses[0];
  42568. }
  42569. else {
  42570. return this._postProcesses[camera.name];
  42571. }
  42572. };
  42573. PostProcessRenderEffect.prototype._linkParameters = function () {
  42574. var _this = this;
  42575. for (var index in this._postProcesses) {
  42576. if (this.applyParameters) {
  42577. this.applyParameters(this._postProcesses[index]);
  42578. }
  42579. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  42580. _this._linkTextures(effect);
  42581. });
  42582. }
  42583. };
  42584. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  42585. for (var renderPassName in this._renderPasses) {
  42586. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  42587. }
  42588. for (var renderEffectName in this._renderEffectAsPasses) {
  42589. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  42590. }
  42591. };
  42592. return PostProcessRenderEffect;
  42593. }());
  42594. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  42595. })(BABYLON || (BABYLON = {}));
  42596. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  42597. var BABYLON;
  42598. (function (BABYLON) {
  42599. var PostProcessRenderPipeline = (function () {
  42600. function PostProcessRenderPipeline(engine, name) {
  42601. this._engine = engine;
  42602. this._name = name;
  42603. this._renderEffects = new Array();
  42604. this._renderEffectsForIsolatedPass = new Array();
  42605. this._cameras = [];
  42606. }
  42607. PostProcessRenderPipeline.prototype.getClassName = function () {
  42608. return "PostProcessRenderPipeline";
  42609. };
  42610. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  42611. get: function () {
  42612. for (var renderEffectName in this._renderEffects) {
  42613. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42614. if (!this._renderEffects[renderEffectName].isSupported) {
  42615. return false;
  42616. }
  42617. }
  42618. }
  42619. return true;
  42620. },
  42621. enumerable: true,
  42622. configurable: true
  42623. });
  42624. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  42625. this._renderEffects[renderEffect._name] = renderEffect;
  42626. };
  42627. // private
  42628. PostProcessRenderPipeline.prototype._rebuild = function () {
  42629. };
  42630. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  42631. var renderEffects = this._renderEffects[renderEffectName];
  42632. if (!renderEffects) {
  42633. return;
  42634. }
  42635. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42636. };
  42637. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  42638. var renderEffects = this._renderEffects[renderEffectName];
  42639. if (!renderEffects) {
  42640. return;
  42641. }
  42642. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42643. };
  42644. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  42645. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42646. var indicesToDelete = [];
  42647. var i;
  42648. for (i = 0; i < _cam.length; i++) {
  42649. var camera = _cam[i];
  42650. var cameraName = camera.name;
  42651. if (this._cameras.indexOf(camera) === -1) {
  42652. this._cameras[cameraName] = camera;
  42653. }
  42654. else if (unique) {
  42655. indicesToDelete.push(i);
  42656. }
  42657. }
  42658. for (i = 0; i < indicesToDelete.length; i++) {
  42659. cameras.splice(indicesToDelete[i], 1);
  42660. }
  42661. for (var renderEffectName in this._renderEffects) {
  42662. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42663. this._renderEffects[renderEffectName]._attachCameras(_cam);
  42664. }
  42665. }
  42666. };
  42667. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  42668. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42669. for (var renderEffectName in this._renderEffects) {
  42670. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42671. this._renderEffects[renderEffectName]._detachCameras(_cam);
  42672. }
  42673. }
  42674. for (var i = 0; i < _cam.length; i++) {
  42675. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  42676. }
  42677. };
  42678. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  42679. var _this = this;
  42680. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42681. var pass = null;
  42682. var renderEffectName;
  42683. for (renderEffectName in this._renderEffects) {
  42684. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42685. pass = this._renderEffects[renderEffectName].getPass(passName);
  42686. if (pass != null) {
  42687. break;
  42688. }
  42689. }
  42690. }
  42691. if (pass === null) {
  42692. return;
  42693. }
  42694. for (renderEffectName in this._renderEffects) {
  42695. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42696. this._renderEffects[renderEffectName]._disable(_cam);
  42697. }
  42698. }
  42699. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  42700. for (var i = 0; i < _cam.length; i++) {
  42701. var camera = _cam[i];
  42702. var cameraName = camera.name;
  42703. 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); });
  42704. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  42705. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  42706. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  42707. }
  42708. };
  42709. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  42710. var _this = this;
  42711. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42712. for (var i = 0; i < _cam.length; i++) {
  42713. var camera = _cam[i];
  42714. var cameraName = camera.name;
  42715. 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); });
  42716. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  42717. }
  42718. for (var renderEffectName in this._renderEffects) {
  42719. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42720. this._renderEffects[renderEffectName]._enable(_cam);
  42721. }
  42722. }
  42723. };
  42724. PostProcessRenderPipeline.prototype._update = function () {
  42725. for (var renderEffectName in this._renderEffects) {
  42726. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42727. this._renderEffects[renderEffectName]._update();
  42728. }
  42729. }
  42730. for (var i = 0; i < this._cameras.length; i++) {
  42731. var cameraName = this._cameras[i].name;
  42732. if (this._renderEffectsForIsolatedPass[cameraName]) {
  42733. this._renderEffectsForIsolatedPass[cameraName]._update();
  42734. }
  42735. }
  42736. };
  42737. PostProcessRenderPipeline.prototype._reset = function () {
  42738. this._renderEffects = new Array();
  42739. this._renderEffectsForIsolatedPass = new Array();
  42740. };
  42741. PostProcessRenderPipeline.prototype.dispose = function () {
  42742. // Must be implemented by children
  42743. };
  42744. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  42745. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  42746. __decorate([
  42747. BABYLON.serialize()
  42748. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  42749. return PostProcessRenderPipeline;
  42750. }());
  42751. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  42752. })(BABYLON || (BABYLON = {}));
  42753. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  42754. var BABYLON;
  42755. (function (BABYLON) {
  42756. var DefaultRenderingPipeline = (function (_super) {
  42757. __extends(DefaultRenderingPipeline, _super);
  42758. /**
  42759. * @constructor
  42760. * @param {string} name - The rendering pipeline name
  42761. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  42762. * @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)
  42763. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  42764. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  42765. */
  42766. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  42767. if (automaticBuild === void 0) { automaticBuild = true; }
  42768. var _this = _super.call(this, scene.getEngine(), name) || this;
  42769. _this.PassPostProcessId = "PassPostProcessEffect";
  42770. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  42771. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  42772. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  42773. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  42774. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  42775. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  42776. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  42777. // IAnimatable
  42778. _this.animations = [];
  42779. // Values
  42780. _this._bloomEnabled = false;
  42781. _this._fxaaEnabled = false;
  42782. _this._imageProcessingEnabled = true;
  42783. _this._bloomScale = 0.6;
  42784. _this._buildAllowed = true;
  42785. /**
  42786. * Specifies the size of the bloom blur kernel, relative to the final output size
  42787. */
  42788. _this.bloomKernel = 64;
  42789. /**
  42790. * Specifies the weight of the bloom in the final rendering
  42791. */
  42792. _this._bloomWeight = 0.15;
  42793. _this._cameras = cameras || [];
  42794. _this._buildAllowed = automaticBuild;
  42795. // Initialize
  42796. _this._scene = scene;
  42797. var caps = _this._scene.getEngine().getCaps();
  42798. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  42799. // Misc
  42800. if (_this._hdr) {
  42801. if (caps.textureHalfFloatRender) {
  42802. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  42803. }
  42804. else if (caps.textureFloatRender) {
  42805. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42806. }
  42807. }
  42808. else {
  42809. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42810. }
  42811. // Attach
  42812. scene.postProcessRenderPipelineManager.addPipeline(_this);
  42813. _this._buildPipeline();
  42814. return _this;
  42815. }
  42816. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  42817. get: function () {
  42818. return this._bloomWeight;
  42819. },
  42820. set: function (value) {
  42821. if (this._bloomWeight === value) {
  42822. return;
  42823. }
  42824. this._bloomWeight = value;
  42825. if (this._hdr && this.copyBack) {
  42826. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  42827. }
  42828. },
  42829. enumerable: true,
  42830. configurable: true
  42831. });
  42832. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  42833. get: function () {
  42834. return this._bloomScale;
  42835. },
  42836. set: function (value) {
  42837. if (this._bloomScale === value) {
  42838. return;
  42839. }
  42840. this._bloomScale = value;
  42841. this._buildPipeline();
  42842. },
  42843. enumerable: true,
  42844. configurable: true
  42845. });
  42846. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  42847. get: function () {
  42848. return this._bloomEnabled;
  42849. },
  42850. set: function (enabled) {
  42851. if (this._bloomEnabled === enabled) {
  42852. return;
  42853. }
  42854. this._bloomEnabled = enabled;
  42855. this._buildPipeline();
  42856. },
  42857. enumerable: true,
  42858. configurable: true
  42859. });
  42860. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  42861. get: function () {
  42862. return this._fxaaEnabled;
  42863. },
  42864. set: function (enabled) {
  42865. if (this._fxaaEnabled === enabled) {
  42866. return;
  42867. }
  42868. this._fxaaEnabled = enabled;
  42869. this._buildPipeline();
  42870. },
  42871. enumerable: true,
  42872. configurable: true
  42873. });
  42874. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  42875. get: function () {
  42876. return this._imageProcessingEnabled;
  42877. },
  42878. set: function (enabled) {
  42879. if (this._imageProcessingEnabled === enabled) {
  42880. return;
  42881. }
  42882. this._imageProcessingEnabled = enabled;
  42883. this._buildPipeline();
  42884. },
  42885. enumerable: true,
  42886. configurable: true
  42887. });
  42888. /**
  42889. * Force the compilation of the entire pipeline.
  42890. */
  42891. DefaultRenderingPipeline.prototype.prepare = function () {
  42892. var previousState = this._buildAllowed;
  42893. this._buildAllowed = true;
  42894. this._buildPipeline();
  42895. this._buildAllowed = previousState;
  42896. };
  42897. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  42898. var _this = this;
  42899. if (!this._buildAllowed) {
  42900. return;
  42901. }
  42902. var engine = this._scene.getEngine();
  42903. this._disposePostProcesses();
  42904. this._reset();
  42905. if (this.bloomEnabled) {
  42906. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42907. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  42908. if (!this._hdr) {
  42909. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42910. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  42911. this.highlights.autoClear = false;
  42912. this.highlights.alwaysForcePOT = true;
  42913. }
  42914. 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);
  42915. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  42916. this.blurX.alwaysForcePOT = true;
  42917. this.blurX.autoClear = false;
  42918. this.blurX.onActivateObservable.add(function () {
  42919. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  42920. _this.blurX.kernel = _this.bloomKernel * dw;
  42921. });
  42922. 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);
  42923. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  42924. this.blurY.alwaysForcePOT = true;
  42925. this.blurY.autoClear = false;
  42926. this.blurY.onActivateObservable.add(function () {
  42927. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  42928. _this.blurY.kernel = _this.bloomKernel * dh;
  42929. });
  42930. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42931. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  42932. this.copyBack.alwaysForcePOT = true;
  42933. if (this._hdr) {
  42934. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  42935. var w = this.bloomWeight;
  42936. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  42937. }
  42938. else {
  42939. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  42940. }
  42941. this.copyBack.autoClear = false;
  42942. }
  42943. if (this._imageProcessingEnabled) {
  42944. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42945. if (this._hdr) {
  42946. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  42947. }
  42948. }
  42949. if (this.fxaaEnabled) {
  42950. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42951. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  42952. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42953. }
  42954. else {
  42955. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42956. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  42957. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42958. }
  42959. if (this.bloomEnabled) {
  42960. if (this._hdr) {
  42961. this.copyBack.shareOutputWith(this.blurX);
  42962. if (this.imageProcessing) {
  42963. this.imageProcessing.shareOutputWith(this.pass);
  42964. this.imageProcessing.autoClear = false;
  42965. }
  42966. else if (this.fxaa) {
  42967. this.fxaa.shareOutputWith(this.pass);
  42968. }
  42969. else {
  42970. this.finalMerge.shareOutputWith(this.pass);
  42971. }
  42972. }
  42973. else {
  42974. if (this.fxaa) {
  42975. this.fxaa.shareOutputWith(this.pass);
  42976. }
  42977. else {
  42978. this.finalMerge.shareOutputWith(this.pass);
  42979. }
  42980. }
  42981. }
  42982. if (this._cameras !== null) {
  42983. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  42984. }
  42985. };
  42986. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  42987. for (var i = 0; i < this._cameras.length; i++) {
  42988. var camera = this._cameras[i];
  42989. if (this.pass) {
  42990. this.pass.dispose(camera);
  42991. }
  42992. if (this.highlights) {
  42993. this.highlights.dispose(camera);
  42994. }
  42995. if (this.blurX) {
  42996. this.blurX.dispose(camera);
  42997. }
  42998. if (this.blurY) {
  42999. this.blurY.dispose(camera);
  43000. }
  43001. if (this.copyBack) {
  43002. this.copyBack.dispose(camera);
  43003. }
  43004. if (this.imageProcessing) {
  43005. this.imageProcessing.dispose(camera);
  43006. }
  43007. if (this.fxaa) {
  43008. this.fxaa.dispose(camera);
  43009. }
  43010. if (this.finalMerge) {
  43011. this.finalMerge.dispose(camera);
  43012. }
  43013. }
  43014. this.pass = null;
  43015. this.highlights = null;
  43016. this.blurX = null;
  43017. this.blurY = null;
  43018. this.copyBack = null;
  43019. this.imageProcessing = null;
  43020. this.fxaa = null;
  43021. this.finalMerge = null;
  43022. };
  43023. // Dispose
  43024. DefaultRenderingPipeline.prototype.dispose = function () {
  43025. this._disposePostProcesses();
  43026. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  43027. _super.prototype.dispose.call(this);
  43028. };
  43029. // Serialize rendering pipeline
  43030. DefaultRenderingPipeline.prototype.serialize = function () {
  43031. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43032. serializationObject.customType = "DefaultRenderingPipeline";
  43033. return serializationObject;
  43034. };
  43035. // Parse serialized pipeline
  43036. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  43037. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  43038. };
  43039. __decorate([
  43040. BABYLON.serialize()
  43041. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  43042. __decorate([
  43043. BABYLON.serialize()
  43044. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  43045. __decorate([
  43046. BABYLON.serialize()
  43047. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  43048. __decorate([
  43049. BABYLON.serialize()
  43050. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  43051. __decorate([
  43052. BABYLON.serialize()
  43053. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  43054. __decorate([
  43055. BABYLON.serialize()
  43056. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  43057. __decorate([
  43058. BABYLON.serialize()
  43059. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  43060. __decorate([
  43061. BABYLON.serialize()
  43062. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  43063. return DefaultRenderingPipeline;
  43064. }(BABYLON.PostProcessRenderPipeline));
  43065. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  43066. })(BABYLON || (BABYLON = {}));
  43067. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  43068. var BABYLON;
  43069. (function (BABYLON) {
  43070. /**
  43071. * This groups together the common properties used for image processing either in direct forward pass
  43072. * or through post processing effect depending on the use of the image processing pipeline in your scene
  43073. * or not.
  43074. */
  43075. var ImageProcessingConfiguration = (function () {
  43076. function ImageProcessingConfiguration() {
  43077. /**
  43078. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  43079. */
  43080. this.colorCurves = new BABYLON.ColorCurves();
  43081. this._colorCurvesEnabled = false;
  43082. this._colorGradingEnabled = false;
  43083. this._colorGradingWithGreenDepth = false;
  43084. this._colorGradingBGR = false;
  43085. this._exposure = 1.0;
  43086. this._toneMappingEnabled = false;
  43087. this._contrast = 1.0;
  43088. /**
  43089. * Vignette stretch size.
  43090. */
  43091. this.vignetteStretch = 0;
  43092. /**
  43093. * Vignette centre X Offset.
  43094. */
  43095. this.vignetteCentreX = 0;
  43096. /**
  43097. * Vignette centre Y Offset.
  43098. */
  43099. this.vignetteCentreY = 0;
  43100. /**
  43101. * Vignette weight or intensity of the vignette effect.
  43102. */
  43103. this.vignetteWeight = 1.5;
  43104. /**
  43105. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  43106. * if vignetteEnabled is set to true.
  43107. */
  43108. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  43109. /**
  43110. * Camera field of view used by the Vignette effect.
  43111. */
  43112. this.vignetteCameraFov = 0.5;
  43113. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  43114. this._vignetteEnabled = false;
  43115. this._applyByPostProcess = false;
  43116. /**
  43117. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  43118. * @type {BABYLON.Observable}
  43119. */
  43120. this.onUpdateParameters = new BABYLON.Observable();
  43121. }
  43122. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  43123. /**
  43124. * Gets wether the color curves effect is enabled.
  43125. */
  43126. get: function () {
  43127. return this._colorCurvesEnabled;
  43128. },
  43129. /**
  43130. * Sets wether the color curves effect is enabled.
  43131. */
  43132. set: function (value) {
  43133. if (this._colorCurvesEnabled === value) {
  43134. return;
  43135. }
  43136. this._colorCurvesEnabled = value;
  43137. this._updateParameters();
  43138. },
  43139. enumerable: true,
  43140. configurable: true
  43141. });
  43142. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  43143. /**
  43144. * Gets wether the color grading effect is enabled.
  43145. */
  43146. get: function () {
  43147. return this._colorGradingEnabled;
  43148. },
  43149. /**
  43150. * Sets wether the color grading effect is enabled.
  43151. */
  43152. set: function (value) {
  43153. if (this._colorGradingEnabled === value) {
  43154. return;
  43155. }
  43156. this._colorGradingEnabled = value;
  43157. this._updateParameters();
  43158. },
  43159. enumerable: true,
  43160. configurable: true
  43161. });
  43162. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  43163. /**
  43164. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  43165. */
  43166. get: function () {
  43167. return this._colorGradingWithGreenDepth;
  43168. },
  43169. /**
  43170. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  43171. */
  43172. set: function (value) {
  43173. if (this._colorGradingWithGreenDepth === value) {
  43174. return;
  43175. }
  43176. this._colorGradingWithGreenDepth = value;
  43177. this._updateParameters();
  43178. },
  43179. enumerable: true,
  43180. configurable: true
  43181. });
  43182. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  43183. /**
  43184. * Gets wether the color grading texture contains BGR values.
  43185. */
  43186. get: function () {
  43187. return this._colorGradingBGR;
  43188. },
  43189. /**
  43190. * Sets wether the color grading texture contains BGR values.
  43191. */
  43192. set: function (value) {
  43193. if (this._colorGradingBGR === value) {
  43194. return;
  43195. }
  43196. this._colorGradingBGR = value;
  43197. this._updateParameters();
  43198. },
  43199. enumerable: true,
  43200. configurable: true
  43201. });
  43202. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  43203. /**
  43204. * Gets the Exposure used in the effect.
  43205. */
  43206. get: function () {
  43207. return this._exposure;
  43208. },
  43209. /**
  43210. * Sets the Exposure used in the effect.
  43211. */
  43212. set: function (value) {
  43213. if (this._exposure === value) {
  43214. return;
  43215. }
  43216. this._exposure = value;
  43217. this._updateParameters();
  43218. },
  43219. enumerable: true,
  43220. configurable: true
  43221. });
  43222. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  43223. /**
  43224. * Gets wether the tone mapping effect is enabled.
  43225. */
  43226. get: function () {
  43227. return this._toneMappingEnabled;
  43228. },
  43229. /**
  43230. * Sets wether the tone mapping effect is enabled.
  43231. */
  43232. set: function (value) {
  43233. if (this._toneMappingEnabled === value) {
  43234. return;
  43235. }
  43236. this._toneMappingEnabled = value;
  43237. this._updateParameters();
  43238. },
  43239. enumerable: true,
  43240. configurable: true
  43241. });
  43242. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  43243. /**
  43244. * Gets the contrast used in the effect.
  43245. */
  43246. get: function () {
  43247. return this._contrast;
  43248. },
  43249. /**
  43250. * Sets the contrast used in the effect.
  43251. */
  43252. set: function (value) {
  43253. if (this._contrast === value) {
  43254. return;
  43255. }
  43256. this._contrast = value;
  43257. this._updateParameters();
  43258. },
  43259. enumerable: true,
  43260. configurable: true
  43261. });
  43262. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  43263. /**
  43264. * Gets the vignette blend mode allowing different kind of effect.
  43265. */
  43266. get: function () {
  43267. return this._vignetteBlendMode;
  43268. },
  43269. /**
  43270. * Sets the vignette blend mode allowing different kind of effect.
  43271. */
  43272. set: function (value) {
  43273. if (this._vignetteBlendMode === value) {
  43274. return;
  43275. }
  43276. this._vignetteBlendMode = value;
  43277. this._updateParameters();
  43278. },
  43279. enumerable: true,
  43280. configurable: true
  43281. });
  43282. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  43283. /**
  43284. * Gets wether the vignette effect is enabled.
  43285. */
  43286. get: function () {
  43287. return this._vignetteEnabled;
  43288. },
  43289. /**
  43290. * Sets wether the vignette effect is enabled.
  43291. */
  43292. set: function (value) {
  43293. if (this._vignetteEnabled === value) {
  43294. return;
  43295. }
  43296. this._vignetteEnabled = value;
  43297. this._updateParameters();
  43298. },
  43299. enumerable: true,
  43300. configurable: true
  43301. });
  43302. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  43303. /**
  43304. * Gets wether the image processing is applied through a post process or not.
  43305. */
  43306. get: function () {
  43307. return this._applyByPostProcess;
  43308. },
  43309. /**
  43310. * Sets wether the image processing is applied through a post process or not.
  43311. */
  43312. set: function (value) {
  43313. if (this._applyByPostProcess === value) {
  43314. return;
  43315. }
  43316. this._applyByPostProcess = value;
  43317. this._updateParameters();
  43318. },
  43319. enumerable: true,
  43320. configurable: true
  43321. });
  43322. /**
  43323. * Method called each time the image processing information changes requires to recompile the effect.
  43324. */
  43325. ImageProcessingConfiguration.prototype._updateParameters = function () {
  43326. this.onUpdateParameters.notifyObservers(this);
  43327. };
  43328. ImageProcessingConfiguration.prototype.getClassName = function () {
  43329. return "ImageProcessingConfiguration";
  43330. };
  43331. /**
  43332. * Prepare the list of uniforms associated with the Image Processing effects.
  43333. * @param uniformsList The list of uniforms used in the effect
  43334. * @param defines the list of defines currently in use
  43335. */
  43336. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  43337. if (defines.EXPOSURE) {
  43338. uniforms.push("exposureLinear");
  43339. }
  43340. if (defines.CONTRAST) {
  43341. uniforms.push("contrast");
  43342. }
  43343. if (defines.COLORGRADING) {
  43344. uniforms.push("colorTransformSettings");
  43345. }
  43346. if (defines.VIGNETTE) {
  43347. uniforms.push("vInverseScreenSize");
  43348. uniforms.push("vignetteSettings1");
  43349. uniforms.push("vignetteSettings2");
  43350. }
  43351. if (defines.COLORCURVES) {
  43352. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  43353. }
  43354. };
  43355. /**
  43356. * Prepare the list of samplers associated with the Image Processing effects.
  43357. * @param uniformsList The list of uniforms used in the effect
  43358. * @param defines the list of defines currently in use
  43359. */
  43360. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  43361. if (defines.COLORGRADING) {
  43362. samplersList.push("txColorTransform");
  43363. }
  43364. };
  43365. /**
  43366. * Prepare the list of defines associated to the shader.
  43367. * @param defines the list of defines to complete
  43368. */
  43369. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  43370. defines.VIGNETTE = this.vignetteEnabled;
  43371. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  43372. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  43373. defines.TONEMAPPING = this.toneMappingEnabled;
  43374. defines.CONTRAST = (this.contrast !== 1.0);
  43375. defines.EXPOSURE = (this.exposure !== 1.0);
  43376. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  43377. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  43378. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  43379. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  43380. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  43381. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  43382. };
  43383. /**
  43384. * Returns true if all the image processing information are ready.
  43385. */
  43386. ImageProcessingConfiguration.prototype.isReady = function () {
  43387. // Color Grading texure can not be none blocking.
  43388. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  43389. };
  43390. /**
  43391. * Binds the image processing to the shader.
  43392. * @param effect The effect to bind to
  43393. */
  43394. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  43395. if (aspectRatio === void 0) { aspectRatio = 1; }
  43396. // Color Curves
  43397. if (this._colorCurvesEnabled) {
  43398. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  43399. }
  43400. // Vignette
  43401. if (this._vignetteEnabled) {
  43402. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  43403. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  43404. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  43405. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  43406. var vignetteScaleX = vignetteScaleY * aspectRatio;
  43407. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  43408. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  43409. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  43410. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  43411. var vignettePower = -2.0 * this.vignetteWeight;
  43412. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  43413. }
  43414. // Exposure
  43415. effect.setFloat("exposureLinear", this.exposure);
  43416. // Contrast
  43417. effect.setFloat("contrast", this.contrast);
  43418. // Color transform settings
  43419. if (this.colorGradingTexture) {
  43420. effect.setTexture("txColorTransform", this.colorGradingTexture);
  43421. var textureSize = this.colorGradingTexture.getSize().height;
  43422. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  43423. 0.5 / textureSize, // textureOffset
  43424. textureSize, // textureSize
  43425. this.colorGradingTexture.level // weight
  43426. );
  43427. }
  43428. };
  43429. /**
  43430. * Clones the current image processing instance.
  43431. * @return The cloned image processing
  43432. */
  43433. ImageProcessingConfiguration.prototype.clone = function () {
  43434. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  43435. };
  43436. /**
  43437. * Serializes the current image processing instance to a json representation.
  43438. * @return a JSON representation
  43439. */
  43440. ImageProcessingConfiguration.prototype.serialize = function () {
  43441. return BABYLON.SerializationHelper.Serialize(this);
  43442. };
  43443. /**
  43444. * Parses the image processing from a json representation.
  43445. * @param source the JSON source to parse
  43446. * @return The parsed image processing
  43447. */
  43448. ImageProcessingConfiguration.Parse = function (source) {
  43449. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  43450. };
  43451. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  43452. /**
  43453. * Used to apply the vignette as a mix with the pixel color.
  43454. */
  43455. get: function () {
  43456. return this._VIGNETTEMODE_MULTIPLY;
  43457. },
  43458. enumerable: true,
  43459. configurable: true
  43460. });
  43461. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  43462. /**
  43463. * Used to apply the vignette as a replacement of the pixel color.
  43464. */
  43465. get: function () {
  43466. return this._VIGNETTEMODE_OPAQUE;
  43467. },
  43468. enumerable: true,
  43469. configurable: true
  43470. });
  43471. // Static constants associated to the image processing.
  43472. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  43473. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  43474. __decorate([
  43475. BABYLON.serializeAsColorCurves()
  43476. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  43477. __decorate([
  43478. BABYLON.serialize()
  43479. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  43480. __decorate([
  43481. BABYLON.serializeAsTexture()
  43482. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  43483. __decorate([
  43484. BABYLON.serialize()
  43485. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  43486. __decorate([
  43487. BABYLON.serialize()
  43488. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  43489. __decorate([
  43490. BABYLON.serialize()
  43491. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  43492. __decorate([
  43493. BABYLON.serialize()
  43494. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  43495. __decorate([
  43496. BABYLON.serialize()
  43497. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  43498. __decorate([
  43499. BABYLON.serialize()
  43500. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  43501. __decorate([
  43502. BABYLON.serialize()
  43503. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  43504. __decorate([
  43505. BABYLON.serialize()
  43506. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  43507. __decorate([
  43508. BABYLON.serialize()
  43509. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  43510. __decorate([
  43511. BABYLON.serialize()
  43512. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  43513. __decorate([
  43514. BABYLON.serializeAsColor4()
  43515. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  43516. __decorate([
  43517. BABYLON.serialize()
  43518. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  43519. __decorate([
  43520. BABYLON.serialize()
  43521. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  43522. __decorate([
  43523. BABYLON.serialize()
  43524. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  43525. __decorate([
  43526. BABYLON.serialize()
  43527. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  43528. return ImageProcessingConfiguration;
  43529. }());
  43530. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  43531. })(BABYLON || (BABYLON = {}));
  43532. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  43533. /// <reference path="babylon.mesh.ts" />
  43534. var BABYLON;
  43535. (function (BABYLON) {
  43536. var GroundMesh = (function (_super) {
  43537. __extends(GroundMesh, _super);
  43538. function GroundMesh(name, scene) {
  43539. var _this = _super.call(this, name, scene) || this;
  43540. _this.generateOctree = false;
  43541. _this._worldInverse = new BABYLON.Matrix();
  43542. return _this;
  43543. }
  43544. GroundMesh.prototype.getClassName = function () {
  43545. return "GroundMesh";
  43546. };
  43547. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  43548. get: function () {
  43549. return Math.min(this._subdivisionsX, this._subdivisionsY);
  43550. },
  43551. enumerable: true,
  43552. configurable: true
  43553. });
  43554. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  43555. get: function () {
  43556. return this._subdivisionsX;
  43557. },
  43558. enumerable: true,
  43559. configurable: true
  43560. });
  43561. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  43562. get: function () {
  43563. return this._subdivisionsY;
  43564. },
  43565. enumerable: true,
  43566. configurable: true
  43567. });
  43568. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  43569. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  43570. this._subdivisionsX = chunksCount;
  43571. this._subdivisionsY = chunksCount;
  43572. this.subdivide(chunksCount);
  43573. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  43574. };
  43575. /**
  43576. * Returns a height (y) value in the Worl system :
  43577. * the ground altitude at the coordinates (x, z) expressed in the World system.
  43578. * Returns the ground y position if (x, z) are outside the ground surface.
  43579. */
  43580. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  43581. var world = this.getWorldMatrix();
  43582. var invMat = BABYLON.Tmp.Matrix[5];
  43583. world.invertToRef(invMat);
  43584. var tmpVect = BABYLON.Tmp.Vector3[8];
  43585. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  43586. x = tmpVect.x;
  43587. z = tmpVect.z;
  43588. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43589. return this.position.y;
  43590. }
  43591. if (!this._heightQuads || this._heightQuads.length == 0) {
  43592. this._initHeightQuads();
  43593. this._computeHeightQuads();
  43594. }
  43595. var facet = this._getFacetAt(x, z);
  43596. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  43597. // return y in the World system
  43598. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  43599. return tmpVect.y;
  43600. };
  43601. /**
  43602. * Returns a normalized vector (Vector3) orthogonal to the ground
  43603. * at the ground coordinates (x, z) expressed in the World system.
  43604. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  43605. */
  43606. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  43607. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  43608. this.getNormalAtCoordinatesToRef(x, z, normal);
  43609. return normal;
  43610. };
  43611. /**
  43612. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  43613. * at the ground coordinates (x, z) expressed in the World system.
  43614. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  43615. * Returns the GroundMesh.
  43616. */
  43617. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  43618. var world = this.getWorldMatrix();
  43619. var tmpMat = BABYLON.Tmp.Matrix[5];
  43620. world.invertToRef(tmpMat);
  43621. var tmpVect = BABYLON.Tmp.Vector3[8];
  43622. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  43623. x = tmpVect.x;
  43624. z = tmpVect.z;
  43625. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43626. return this;
  43627. }
  43628. if (!this._heightQuads || this._heightQuads.length == 0) {
  43629. this._initHeightQuads();
  43630. this._computeHeightQuads();
  43631. }
  43632. var facet = this._getFacetAt(x, z);
  43633. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  43634. return this;
  43635. };
  43636. /**
  43637. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  43638. * if the ground has been updated.
  43639. * This can be used in the render loop.
  43640. * Returns the GroundMesh.
  43641. */
  43642. GroundMesh.prototype.updateCoordinateHeights = function () {
  43643. if (!this._heightQuads || this._heightQuads.length == 0) {
  43644. this._initHeightQuads();
  43645. }
  43646. this._computeHeightQuads();
  43647. return this;
  43648. };
  43649. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  43650. GroundMesh.prototype._getFacetAt = function (x, z) {
  43651. // retrieve col and row from x, z coordinates in the ground local system
  43652. var subdivisionsX = this._subdivisionsX;
  43653. var subdivisionsY = this._subdivisionsY;
  43654. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  43655. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  43656. var quad = this._heightQuads[row * this._subdivisionsX + col];
  43657. var facet;
  43658. if (z < quad.slope.x * x + quad.slope.y) {
  43659. facet = quad.facet1;
  43660. }
  43661. else {
  43662. facet = quad.facet2;
  43663. }
  43664. return facet;
  43665. };
  43666. // Creates and populates the heightMap array with "facet" elements :
  43667. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  43668. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43669. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43670. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43671. // Returns the GroundMesh.
  43672. GroundMesh.prototype._initHeightQuads = function () {
  43673. var subdivisionsX = this._subdivisionsX;
  43674. var subdivisionsY = this._subdivisionsY;
  43675. this._heightQuads = new Array();
  43676. for (var row = 0; row < subdivisionsY; row++) {
  43677. for (var col = 0; col < subdivisionsX; col++) {
  43678. 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) };
  43679. this._heightQuads[row * subdivisionsX + col] = quad;
  43680. }
  43681. }
  43682. return this;
  43683. };
  43684. // Compute each quad element values and update the the heightMap array :
  43685. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43686. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43687. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43688. // Returns the GroundMesh.
  43689. GroundMesh.prototype._computeHeightQuads = function () {
  43690. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43691. var v1 = BABYLON.Tmp.Vector3[3];
  43692. var v2 = BABYLON.Tmp.Vector3[2];
  43693. var v3 = BABYLON.Tmp.Vector3[1];
  43694. var v4 = BABYLON.Tmp.Vector3[0];
  43695. var v1v2 = BABYLON.Tmp.Vector3[4];
  43696. var v1v3 = BABYLON.Tmp.Vector3[5];
  43697. var v1v4 = BABYLON.Tmp.Vector3[6];
  43698. var norm1 = BABYLON.Tmp.Vector3[7];
  43699. var norm2 = BABYLON.Tmp.Vector3[8];
  43700. var i = 0;
  43701. var j = 0;
  43702. var k = 0;
  43703. var cd = 0; // 2D slope coefficient : z = cd * x + h
  43704. var h = 0;
  43705. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  43706. var d2 = 0;
  43707. var subdivisionsX = this._subdivisionsX;
  43708. var subdivisionsY = this._subdivisionsY;
  43709. for (var row = 0; row < subdivisionsY; row++) {
  43710. for (var col = 0; col < subdivisionsX; col++) {
  43711. i = col * 3;
  43712. j = row * (subdivisionsX + 1) * 3;
  43713. k = (row + 1) * (subdivisionsX + 1) * 3;
  43714. v1.x = positions[j + i];
  43715. v1.y = positions[j + i + 1];
  43716. v1.z = positions[j + i + 2];
  43717. v2.x = positions[j + i + 3];
  43718. v2.y = positions[j + i + 4];
  43719. v2.z = positions[j + i + 5];
  43720. v3.x = positions[k + i];
  43721. v3.y = positions[k + i + 1];
  43722. v3.z = positions[k + i + 2];
  43723. v4.x = positions[k + i + 3];
  43724. v4.y = positions[k + i + 4];
  43725. v4.z = positions[k + i + 5];
  43726. // 2D slope V1V4
  43727. cd = (v4.z - v1.z) / (v4.x - v1.x);
  43728. h = v1.z - cd * v1.x; // v1 belongs to the slope
  43729. // facet equations :
  43730. // we compute each facet normal vector
  43731. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  43732. // we compute the value d by applying the equation to v1 which belongs to the plane
  43733. // then we store the facet equation in a Vector4
  43734. v2.subtractToRef(v1, v1v2);
  43735. v3.subtractToRef(v1, v1v3);
  43736. v4.subtractToRef(v1, v1v4);
  43737. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  43738. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  43739. norm1.normalize();
  43740. norm2.normalize();
  43741. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  43742. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  43743. var quad = this._heightQuads[row * subdivisionsX + col];
  43744. quad.slope.copyFromFloats(cd, h);
  43745. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  43746. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  43747. }
  43748. }
  43749. return this;
  43750. };
  43751. GroundMesh.prototype.serialize = function (serializationObject) {
  43752. _super.prototype.serialize.call(this, serializationObject);
  43753. serializationObject.subdivisionsX = this._subdivisionsX;
  43754. serializationObject.subdivisionsY = this._subdivisionsY;
  43755. serializationObject.minX = this._minX;
  43756. serializationObject.maxX = this._maxX;
  43757. serializationObject.minZ = this._minZ;
  43758. serializationObject.maxZ = this._maxZ;
  43759. serializationObject.width = this._width;
  43760. serializationObject.height = this._height;
  43761. };
  43762. GroundMesh.Parse = function (parsedMesh, scene) {
  43763. var result = new GroundMesh(parsedMesh.name, scene);
  43764. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  43765. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  43766. result._minX = parsedMesh.minX;
  43767. result._maxX = parsedMesh.maxX;
  43768. result._minZ = parsedMesh.minZ;
  43769. result._maxZ = parsedMesh.maxZ;
  43770. result._width = parsedMesh.width;
  43771. result._height = parsedMesh.height;
  43772. return result;
  43773. };
  43774. return GroundMesh;
  43775. }(BABYLON.Mesh));
  43776. BABYLON.GroundMesh = GroundMesh;
  43777. })(BABYLON || (BABYLON = {}));
  43778. //# sourceMappingURL=babylon.groundMesh.js.map
  43779. var BABYLON;
  43780. (function (BABYLON) {
  43781. /**
  43782. * Creates an instance based on a source mesh.
  43783. */
  43784. var InstancedMesh = (function (_super) {
  43785. __extends(InstancedMesh, _super);
  43786. function InstancedMesh(name, source) {
  43787. var _this = _super.call(this, name, source.getScene()) || this;
  43788. source.instances.push(_this);
  43789. _this._sourceMesh = source;
  43790. _this.position.copyFrom(source.position);
  43791. _this.rotation.copyFrom(source.rotation);
  43792. _this.scaling.copyFrom(source.scaling);
  43793. if (source.rotationQuaternion) {
  43794. _this.rotationQuaternion = source.rotationQuaternion.clone();
  43795. }
  43796. _this.infiniteDistance = source.infiniteDistance;
  43797. _this.setPivotMatrix(source.getPivotMatrix());
  43798. _this.refreshBoundingInfo();
  43799. _this._syncSubMeshes();
  43800. return _this;
  43801. }
  43802. /**
  43803. * Returns the string "InstancedMesh".
  43804. */
  43805. InstancedMesh.prototype.getClassName = function () {
  43806. return "InstancedMesh";
  43807. };
  43808. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  43809. // Methods
  43810. get: function () {
  43811. return this._sourceMesh.receiveShadows;
  43812. },
  43813. enumerable: true,
  43814. configurable: true
  43815. });
  43816. Object.defineProperty(InstancedMesh.prototype, "material", {
  43817. get: function () {
  43818. return this._sourceMesh.material;
  43819. },
  43820. enumerable: true,
  43821. configurable: true
  43822. });
  43823. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  43824. get: function () {
  43825. return this._sourceMesh.visibility;
  43826. },
  43827. enumerable: true,
  43828. configurable: true
  43829. });
  43830. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  43831. get: function () {
  43832. return this._sourceMesh.skeleton;
  43833. },
  43834. enumerable: true,
  43835. configurable: true
  43836. });
  43837. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  43838. get: function () {
  43839. return this._sourceMesh.renderingGroupId;
  43840. },
  43841. enumerable: true,
  43842. configurable: true
  43843. });
  43844. /**
  43845. * Returns the total number of vertices (integer).
  43846. */
  43847. InstancedMesh.prototype.getTotalVertices = function () {
  43848. return this._sourceMesh.getTotalVertices();
  43849. };
  43850. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  43851. get: function () {
  43852. return this._sourceMesh;
  43853. },
  43854. enumerable: true,
  43855. configurable: true
  43856. });
  43857. /**
  43858. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  43859. */
  43860. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  43861. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  43862. };
  43863. /**
  43864. * Sets the vertex data of the mesh geometry for the requested `kind`.
  43865. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  43866. * The `data` are either a numeric array either a Float32Array.
  43867. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  43868. * 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).
  43869. * Note that a new underlying VertexBuffer object is created each call.
  43870. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  43871. *
  43872. * Possible `kind` values :
  43873. * - BABYLON.VertexBuffer.PositionKind
  43874. * - BABYLON.VertexBuffer.UVKind
  43875. * - BABYLON.VertexBuffer.UV2Kind
  43876. * - BABYLON.VertexBuffer.UV3Kind
  43877. * - BABYLON.VertexBuffer.UV4Kind
  43878. * - BABYLON.VertexBuffer.UV5Kind
  43879. * - BABYLON.VertexBuffer.UV6Kind
  43880. * - BABYLON.VertexBuffer.ColorKind
  43881. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43882. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43883. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43884. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43885. *
  43886. * Returns the Mesh.
  43887. */
  43888. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  43889. if (this.sourceMesh) {
  43890. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  43891. }
  43892. return this.sourceMesh;
  43893. };
  43894. /**
  43895. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  43896. * If the mesh has no geometry, it is simply returned as it is.
  43897. * The `data` are either a numeric array either a Float32Array.
  43898. * No new underlying VertexBuffer object is created.
  43899. * 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.
  43900. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  43901. *
  43902. * Possible `kind` values :
  43903. * - BABYLON.VertexBuffer.PositionKind
  43904. * - BABYLON.VertexBuffer.UVKind
  43905. * - BABYLON.VertexBuffer.UV2Kind
  43906. * - BABYLON.VertexBuffer.UV3Kind
  43907. * - BABYLON.VertexBuffer.UV4Kind
  43908. * - BABYLON.VertexBuffer.UV5Kind
  43909. * - BABYLON.VertexBuffer.UV6Kind
  43910. * - BABYLON.VertexBuffer.ColorKind
  43911. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43912. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43913. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43914. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43915. *
  43916. * Returns the Mesh.
  43917. */
  43918. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  43919. if (this.sourceMesh) {
  43920. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  43921. }
  43922. return this.sourceMesh;
  43923. };
  43924. /**
  43925. * Sets the mesh indices.
  43926. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  43927. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  43928. * This method creates a new index buffer each call.
  43929. * Returns the Mesh.
  43930. */
  43931. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  43932. if (this.sourceMesh) {
  43933. this.sourceMesh.setIndices(indices, totalVertices);
  43934. }
  43935. return this.sourceMesh;
  43936. };
  43937. /**
  43938. * Boolean : True if the mesh owns the requested kind of data.
  43939. */
  43940. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  43941. return this._sourceMesh.isVerticesDataPresent(kind);
  43942. };
  43943. /**
  43944. * Returns an array of indices (IndicesArray).
  43945. */
  43946. InstancedMesh.prototype.getIndices = function () {
  43947. return this._sourceMesh.getIndices();
  43948. };
  43949. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  43950. get: function () {
  43951. return this._sourceMesh._positions;
  43952. },
  43953. enumerable: true,
  43954. configurable: true
  43955. });
  43956. /**
  43957. * Sets a new updated BoundingInfo to the mesh.
  43958. * Returns the mesh.
  43959. */
  43960. InstancedMesh.prototype.refreshBoundingInfo = function () {
  43961. var meshBB = this._sourceMesh.getBoundingInfo();
  43962. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  43963. this._updateBoundingInfo();
  43964. return this;
  43965. };
  43966. InstancedMesh.prototype._preActivate = function () {
  43967. if (this._currentLOD) {
  43968. this._currentLOD._preActivate();
  43969. }
  43970. return this;
  43971. };
  43972. InstancedMesh.prototype._activate = function (renderId) {
  43973. if (this._currentLOD) {
  43974. this._currentLOD._registerInstanceForRenderId(this, renderId);
  43975. }
  43976. return this;
  43977. };
  43978. /**
  43979. * Returns the current associated LOD AbstractMesh.
  43980. */
  43981. InstancedMesh.prototype.getLOD = function (camera) {
  43982. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  43983. if (this._currentLOD === this.sourceMesh) {
  43984. return this;
  43985. }
  43986. return this._currentLOD;
  43987. };
  43988. InstancedMesh.prototype._syncSubMeshes = function () {
  43989. this.releaseSubMeshes();
  43990. if (this._sourceMesh.subMeshes) {
  43991. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  43992. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  43993. }
  43994. }
  43995. return this;
  43996. };
  43997. InstancedMesh.prototype._generatePointsArray = function () {
  43998. return this._sourceMesh._generatePointsArray();
  43999. };
  44000. /**
  44001. * Creates a new InstancedMesh from the current mesh.
  44002. * - name (string) : the cloned mesh name
  44003. * - newParent (optional Node) : the optional Node to parent the clone to.
  44004. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  44005. *
  44006. * Returns the clone.
  44007. */
  44008. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44009. var result = this._sourceMesh.createInstance(name);
  44010. // Deep copy
  44011. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  44012. // Bounding info
  44013. this.refreshBoundingInfo();
  44014. // Parent
  44015. if (newParent) {
  44016. result.parent = newParent;
  44017. }
  44018. if (!doNotCloneChildren) {
  44019. // Children
  44020. for (var index = 0; index < this.getScene().meshes.length; index++) {
  44021. var mesh = this.getScene().meshes[index];
  44022. if (mesh.parent === this) {
  44023. mesh.clone(mesh.name, result);
  44024. }
  44025. }
  44026. }
  44027. result.computeWorldMatrix(true);
  44028. return result;
  44029. };
  44030. /**
  44031. * Disposes the InstancedMesh.
  44032. * Returns nothing.
  44033. */
  44034. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  44035. // Remove from mesh
  44036. var index = this._sourceMesh.instances.indexOf(this);
  44037. this._sourceMesh.instances.splice(index, 1);
  44038. _super.prototype.dispose.call(this, doNotRecurse);
  44039. };
  44040. return InstancedMesh;
  44041. }(BABYLON.AbstractMesh));
  44042. BABYLON.InstancedMesh = InstancedMesh;
  44043. })(BABYLON || (BABYLON = {}));
  44044. //# sourceMappingURL=babylon.instancedMesh.js.map
  44045. /// <reference path="babylon.mesh.ts" />
  44046. var BABYLON;
  44047. (function (BABYLON) {
  44048. var LinesMesh = (function (_super) {
  44049. __extends(LinesMesh, _super);
  44050. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  44051. if (parent === void 0) { parent = null; }
  44052. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  44053. _this.useVertexColor = useVertexColor;
  44054. _this.color = new BABYLON.Color3(1, 1, 1);
  44055. _this.alpha = 1;
  44056. if (source) {
  44057. _this.color = source.color.clone();
  44058. _this.alpha = source.alpha;
  44059. _this.useVertexColor = source.useVertexColor;
  44060. }
  44061. _this._intersectionThreshold = 0.1;
  44062. var options = {
  44063. attributes: [BABYLON.VertexBuffer.PositionKind],
  44064. uniforms: ["world", "viewProjection"],
  44065. needAlphaBlending: false,
  44066. };
  44067. if (!useVertexColor) {
  44068. options.uniforms.push("color");
  44069. options.needAlphaBlending = true;
  44070. }
  44071. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  44072. return _this;
  44073. }
  44074. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  44075. /**
  44076. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  44077. * This margin is expressed in world space coordinates, so its value may vary.
  44078. * Default value is 0.1
  44079. * @returns the intersection Threshold value.
  44080. */
  44081. get: function () {
  44082. return this._intersectionThreshold;
  44083. },
  44084. /**
  44085. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  44086. * This margin is expressed in world space coordinates, so its value may vary.
  44087. * @param value the new threshold to apply
  44088. */
  44089. set: function (value) {
  44090. if (this._intersectionThreshold === value) {
  44091. return;
  44092. }
  44093. this._intersectionThreshold = value;
  44094. if (this.geometry) {
  44095. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  44096. }
  44097. },
  44098. enumerable: true,
  44099. configurable: true
  44100. });
  44101. /**
  44102. * Returns the string "LineMesh"
  44103. */
  44104. LinesMesh.prototype.getClassName = function () {
  44105. return "LinesMesh";
  44106. };
  44107. Object.defineProperty(LinesMesh.prototype, "material", {
  44108. get: function () {
  44109. return this._colorShader;
  44110. },
  44111. enumerable: true,
  44112. configurable: true
  44113. });
  44114. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  44115. get: function () {
  44116. return false;
  44117. },
  44118. enumerable: true,
  44119. configurable: true
  44120. });
  44121. LinesMesh.prototype.createInstance = function (name) {
  44122. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  44123. return null;
  44124. };
  44125. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  44126. // VBOs
  44127. this._geometry._bind(this._colorShader.getEffect());
  44128. // Color
  44129. if (!this.useVertexColor) {
  44130. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  44131. }
  44132. return this;
  44133. };
  44134. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  44135. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  44136. return this;
  44137. }
  44138. var engine = this.getScene().getEngine();
  44139. // Draw order
  44140. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  44141. return this;
  44142. };
  44143. LinesMesh.prototype.dispose = function (doNotRecurse) {
  44144. this._colorShader.dispose();
  44145. _super.prototype.dispose.call(this, doNotRecurse);
  44146. };
  44147. /**
  44148. * Returns a new LineMesh object cloned from the current one.
  44149. */
  44150. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44151. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  44152. };
  44153. return LinesMesh;
  44154. }(BABYLON.Mesh));
  44155. BABYLON.LinesMesh = LinesMesh;
  44156. })(BABYLON || (BABYLON = {}));
  44157. //# sourceMappingURL=babylon.linesMesh.js.map
  44158. var BABYLON;
  44159. (function (BABYLON) {
  44160. var StandardMaterialDefines = (function (_super) {
  44161. __extends(StandardMaterialDefines, _super);
  44162. function StandardMaterialDefines() {
  44163. var _this = _super.call(this) || this;
  44164. _this.MAINUV1 = false;
  44165. _this.MAINUV2 = false;
  44166. _this.DIFFUSE = false;
  44167. _this.DIFFUSEDIRECTUV = 0;
  44168. _this.AMBIENT = false;
  44169. _this.AMBIENTDIRECTUV = 0;
  44170. _this.OPACITY = false;
  44171. _this.OPACITYDIRECTUV = 0;
  44172. _this.OPACITYRGB = false;
  44173. _this.REFLECTION = false;
  44174. _this.EMISSIVE = false;
  44175. _this.EMISSIVEDIRECTUV = 0;
  44176. _this.SPECULAR = false;
  44177. _this.SPECULARDIRECTUV = 0;
  44178. _this.BUMP = false;
  44179. _this.BUMPDIRECTUV = 0;
  44180. _this.PARALLAX = false;
  44181. _this.PARALLAXOCCLUSION = false;
  44182. _this.SPECULAROVERALPHA = false;
  44183. _this.CLIPPLANE = false;
  44184. _this.ALPHATEST = false;
  44185. _this.ALPHAFROMDIFFUSE = false;
  44186. _this.POINTSIZE = false;
  44187. _this.FOG = false;
  44188. _this.SPECULARTERM = false;
  44189. _this.DIFFUSEFRESNEL = false;
  44190. _this.OPACITYFRESNEL = false;
  44191. _this.REFLECTIONFRESNEL = false;
  44192. _this.REFRACTIONFRESNEL = false;
  44193. _this.EMISSIVEFRESNEL = false;
  44194. _this.FRESNEL = false;
  44195. _this.NORMAL = false;
  44196. _this.UV1 = false;
  44197. _this.UV2 = false;
  44198. _this.VERTEXCOLOR = false;
  44199. _this.VERTEXALPHA = false;
  44200. _this.NUM_BONE_INFLUENCERS = 0;
  44201. _this.BonesPerMesh = 0;
  44202. _this.INSTANCES = false;
  44203. _this.GLOSSINESS = false;
  44204. _this.ROUGHNESS = false;
  44205. _this.EMISSIVEASILLUMINATION = false;
  44206. _this.LINKEMISSIVEWITHDIFFUSE = false;
  44207. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  44208. _this.LIGHTMAP = false;
  44209. _this.LIGHTMAPDIRECTUV = 0;
  44210. _this.USELIGHTMAPASSHADOWMAP = false;
  44211. _this.REFLECTIONMAP_3D = false;
  44212. _this.REFLECTIONMAP_SPHERICAL = false;
  44213. _this.REFLECTIONMAP_PLANAR = false;
  44214. _this.REFLECTIONMAP_CUBIC = false;
  44215. _this.REFLECTIONMAP_PROJECTION = false;
  44216. _this.REFLECTIONMAP_SKYBOX = false;
  44217. _this.REFLECTIONMAP_EXPLICIT = false;
  44218. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44219. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44220. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44221. _this.INVERTCUBICMAP = false;
  44222. _this.LOGARITHMICDEPTH = false;
  44223. _this.REFRACTION = false;
  44224. _this.REFRACTIONMAP_3D = false;
  44225. _this.REFLECTIONOVERALPHA = false;
  44226. _this.TWOSIDEDLIGHTING = false;
  44227. _this.SHADOWFLOAT = false;
  44228. _this.MORPHTARGETS = false;
  44229. _this.MORPHTARGETS_NORMAL = false;
  44230. _this.MORPHTARGETS_TANGENT = false;
  44231. _this.NUM_MORPH_INFLUENCERS = 0;
  44232. _this.USERIGHTHANDEDSYSTEM = false;
  44233. _this.IMAGEPROCESSING = false;
  44234. _this.VIGNETTE = false;
  44235. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44236. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44237. _this.TONEMAPPING = false;
  44238. _this.CONTRAST = false;
  44239. _this.COLORCURVES = false;
  44240. _this.COLORGRADING = false;
  44241. _this.SAMPLER3DGREENDEPTH = false;
  44242. _this.SAMPLER3DBGRMAP = false;
  44243. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44244. _this.EXPOSURE = false;
  44245. _this.rebuild();
  44246. return _this;
  44247. }
  44248. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  44249. var modes = [
  44250. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  44251. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  44252. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  44253. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  44254. ];
  44255. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  44256. var mode = modes_1[_i];
  44257. this[mode] = (mode === modeToEnable);
  44258. }
  44259. };
  44260. return StandardMaterialDefines;
  44261. }(BABYLON.MaterialDefines));
  44262. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  44263. var StandardMaterial = (function (_super) {
  44264. __extends(StandardMaterial, _super);
  44265. function StandardMaterial(name, scene) {
  44266. var _this = _super.call(this, name, scene) || this;
  44267. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44268. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  44269. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  44270. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44271. _this.specularPower = 64;
  44272. _this._useAlphaFromDiffuseTexture = false;
  44273. _this._useEmissiveAsIllumination = false;
  44274. _this._linkEmissiveWithDiffuse = false;
  44275. _this._useSpecularOverAlpha = false;
  44276. _this._useReflectionOverAlpha = false;
  44277. _this._disableLighting = false;
  44278. _this._useParallax = false;
  44279. _this._useParallaxOcclusion = false;
  44280. _this.parallaxScaleBias = 0.05;
  44281. _this._roughness = 0;
  44282. _this.indexOfRefraction = 0.98;
  44283. _this.invertRefractionY = true;
  44284. _this._useLightmapAsShadowmap = false;
  44285. _this._useReflectionFresnelFromSpecular = false;
  44286. _this._useGlossinessFromSpecularMapAlpha = false;
  44287. _this._maxSimultaneousLights = 4;
  44288. /**
  44289. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44290. */
  44291. _this._invertNormalMapX = false;
  44292. /**
  44293. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44294. */
  44295. _this._invertNormalMapY = false;
  44296. /**
  44297. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44298. */
  44299. _this._twoSidedLighting = false;
  44300. _this._renderTargets = new BABYLON.SmartArray(16);
  44301. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44302. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44303. // Setup the default processing configuration to the scene.
  44304. _this._attachImageProcessingConfiguration(null);
  44305. _this.getRenderTargetTextures = function () {
  44306. _this._renderTargets.reset();
  44307. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44308. _this._renderTargets.push(_this._reflectionTexture);
  44309. }
  44310. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44311. _this._renderTargets.push(_this._refractionTexture);
  44312. }
  44313. return _this._renderTargets;
  44314. };
  44315. return _this;
  44316. }
  44317. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  44318. /**
  44319. * Gets the image processing configuration used either in this material.
  44320. */
  44321. get: function () {
  44322. return this._imageProcessingConfiguration;
  44323. },
  44324. /**
  44325. * Sets the Default image processing configuration used either in the this material.
  44326. *
  44327. * If sets to null, the scene one is in use.
  44328. */
  44329. set: function (value) {
  44330. this._attachImageProcessingConfiguration(value);
  44331. // Ensure the effect will be rebuilt.
  44332. this._markAllSubMeshesAsTexturesDirty();
  44333. },
  44334. enumerable: true,
  44335. configurable: true
  44336. });
  44337. /**
  44338. * Attaches a new image processing configuration to the Standard Material.
  44339. * @param configuration
  44340. */
  44341. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44342. var _this = this;
  44343. if (configuration === this._imageProcessingConfiguration) {
  44344. return;
  44345. }
  44346. // Detaches observer.
  44347. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44348. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44349. }
  44350. // Pick the scene configuration if needed.
  44351. if (!configuration) {
  44352. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44353. }
  44354. else {
  44355. this._imageProcessingConfiguration = configuration;
  44356. }
  44357. // Attaches observer.
  44358. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44359. _this._markAllSubMeshesAsImageProcessingDirty();
  44360. });
  44361. };
  44362. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  44363. /**
  44364. * Gets wether the color curves effect is enabled.
  44365. */
  44366. get: function () {
  44367. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44368. },
  44369. /**
  44370. * Sets wether the color curves effect is enabled.
  44371. */
  44372. set: function (value) {
  44373. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44374. },
  44375. enumerable: true,
  44376. configurable: true
  44377. });
  44378. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  44379. /**
  44380. * Gets wether the color grading effect is enabled.
  44381. */
  44382. get: function () {
  44383. return this.imageProcessingConfiguration.colorGradingEnabled;
  44384. },
  44385. /**
  44386. * Gets wether the color grading effect is enabled.
  44387. */
  44388. set: function (value) {
  44389. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44390. },
  44391. enumerable: true,
  44392. configurable: true
  44393. });
  44394. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  44395. /**
  44396. * Gets wether tonemapping is enabled or not.
  44397. */
  44398. get: function () {
  44399. return this._imageProcessingConfiguration.toneMappingEnabled;
  44400. },
  44401. /**
  44402. * Sets wether tonemapping is enabled or not
  44403. */
  44404. set: function (value) {
  44405. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44406. },
  44407. enumerable: true,
  44408. configurable: true
  44409. });
  44410. ;
  44411. ;
  44412. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  44413. /**
  44414. * The camera exposure used on this material.
  44415. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44416. * This corresponds to a photographic exposure.
  44417. */
  44418. get: function () {
  44419. return this._imageProcessingConfiguration.exposure;
  44420. },
  44421. /**
  44422. * The camera exposure used on this material.
  44423. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44424. * This corresponds to a photographic exposure.
  44425. */
  44426. set: function (value) {
  44427. this._imageProcessingConfiguration.exposure = value;
  44428. },
  44429. enumerable: true,
  44430. configurable: true
  44431. });
  44432. ;
  44433. ;
  44434. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  44435. /**
  44436. * Gets The camera contrast used on this material.
  44437. */
  44438. get: function () {
  44439. return this._imageProcessingConfiguration.contrast;
  44440. },
  44441. /**
  44442. * Sets The camera contrast used on this material.
  44443. */
  44444. set: function (value) {
  44445. this._imageProcessingConfiguration.contrast = value;
  44446. },
  44447. enumerable: true,
  44448. configurable: true
  44449. });
  44450. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  44451. /**
  44452. * Gets the Color Grading 2D Lookup Texture.
  44453. */
  44454. get: function () {
  44455. return this._imageProcessingConfiguration.colorGradingTexture;
  44456. },
  44457. /**
  44458. * Sets the Color Grading 2D Lookup Texture.
  44459. */
  44460. set: function (value) {
  44461. this._imageProcessingConfiguration.colorGradingTexture = value;
  44462. },
  44463. enumerable: true,
  44464. configurable: true
  44465. });
  44466. StandardMaterial.prototype.getClassName = function () {
  44467. return "StandardMaterial";
  44468. };
  44469. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  44470. get: function () {
  44471. return this._useLogarithmicDepth;
  44472. },
  44473. set: function (value) {
  44474. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44475. this._markAllSubMeshesAsMiscDirty();
  44476. },
  44477. enumerable: true,
  44478. configurable: true
  44479. });
  44480. StandardMaterial.prototype.needAlphaBlending = function () {
  44481. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  44482. };
  44483. StandardMaterial.prototype.needAlphaTesting = function () {
  44484. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  44485. };
  44486. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  44487. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  44488. };
  44489. StandardMaterial.prototype.getAlphaTestTexture = function () {
  44490. return this._diffuseTexture;
  44491. };
  44492. /**
  44493. * Child classes can use it to update shaders
  44494. */
  44495. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44496. if (this.isFrozen) {
  44497. if (this._wasPreviouslyReady && subMesh.effect) {
  44498. return true;
  44499. }
  44500. }
  44501. if (!subMesh._materialDefines) {
  44502. subMesh._materialDefines = new StandardMaterialDefines();
  44503. }
  44504. var scene = this.getScene();
  44505. var defines = subMesh._materialDefines;
  44506. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44507. if (defines._renderId === scene.getRenderId()) {
  44508. return true;
  44509. }
  44510. }
  44511. var engine = scene.getEngine();
  44512. // Lights
  44513. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44514. // Textures
  44515. if (defines._areTexturesDirty) {
  44516. defines._needUVs = false;
  44517. defines.MAINUV1 = false;
  44518. defines.MAINUV2 = false;
  44519. if (scene.texturesEnabled) {
  44520. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44521. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  44522. return false;
  44523. }
  44524. else {
  44525. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  44526. }
  44527. }
  44528. else {
  44529. defines.DIFFUSE = false;
  44530. }
  44531. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44532. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44533. return false;
  44534. }
  44535. else {
  44536. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44537. }
  44538. }
  44539. else {
  44540. defines.AMBIENT = false;
  44541. }
  44542. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44543. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44544. return false;
  44545. }
  44546. else {
  44547. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44548. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44549. }
  44550. }
  44551. else {
  44552. defines.OPACITY = false;
  44553. }
  44554. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44555. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  44556. return false;
  44557. }
  44558. else {
  44559. defines._needNormals = true;
  44560. defines.REFLECTION = true;
  44561. defines.ROUGHNESS = (this._roughness > 0);
  44562. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  44563. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  44564. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  44565. switch (this._reflectionTexture.coordinatesMode) {
  44566. case BABYLON.Texture.CUBIC_MODE:
  44567. case BABYLON.Texture.INVCUBIC_MODE:
  44568. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  44569. break;
  44570. case BABYLON.Texture.EXPLICIT_MODE:
  44571. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  44572. break;
  44573. case BABYLON.Texture.PLANAR_MODE:
  44574. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  44575. break;
  44576. case BABYLON.Texture.PROJECTION_MODE:
  44577. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  44578. break;
  44579. case BABYLON.Texture.SKYBOX_MODE:
  44580. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  44581. break;
  44582. case BABYLON.Texture.SPHERICAL_MODE:
  44583. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  44584. break;
  44585. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44586. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  44587. break;
  44588. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44589. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  44590. break;
  44591. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44592. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  44593. break;
  44594. }
  44595. }
  44596. }
  44597. else {
  44598. defines.REFLECTION = false;
  44599. }
  44600. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44601. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44602. return false;
  44603. }
  44604. else {
  44605. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44606. }
  44607. }
  44608. else {
  44609. defines.EMISSIVE = false;
  44610. }
  44611. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44612. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44613. return false;
  44614. }
  44615. else {
  44616. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44617. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44618. }
  44619. }
  44620. else {
  44621. defines.LIGHTMAP = false;
  44622. }
  44623. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44624. if (!this._specularTexture.isReadyOrNotBlocking()) {
  44625. return false;
  44626. }
  44627. else {
  44628. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  44629. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  44630. }
  44631. }
  44632. else {
  44633. defines.SPECULAR = false;
  44634. }
  44635. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  44636. // Bump texure can not be not blocking.
  44637. if (!this._bumpTexture.isReady()) {
  44638. return false;
  44639. }
  44640. else {
  44641. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44642. defines.PARALLAX = this._useParallax;
  44643. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  44644. }
  44645. }
  44646. else {
  44647. defines.BUMP = false;
  44648. }
  44649. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44650. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  44651. return false;
  44652. }
  44653. else {
  44654. defines._needUVs = true;
  44655. defines.REFRACTION = true;
  44656. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  44657. }
  44658. }
  44659. else {
  44660. defines.REFRACTION = false;
  44661. }
  44662. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  44663. }
  44664. else {
  44665. defines.DIFFUSE = false;
  44666. defines.AMBIENT = false;
  44667. defines.OPACITY = false;
  44668. defines.REFLECTION = false;
  44669. defines.EMISSIVE = false;
  44670. defines.LIGHTMAP = false;
  44671. defines.BUMP = false;
  44672. defines.REFRACTION = false;
  44673. }
  44674. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  44675. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  44676. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  44677. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44678. }
  44679. if (defines._areImageProcessingDirty) {
  44680. if (!this._imageProcessingConfiguration.isReady()) {
  44681. return false;
  44682. }
  44683. this._imageProcessingConfiguration.prepareDefines(defines);
  44684. }
  44685. if (defines._areFresnelDirty) {
  44686. if (StandardMaterial.FresnelEnabled) {
  44687. // Fresnel
  44688. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  44689. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  44690. this._reflectionFresnelParameters) {
  44691. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  44692. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  44693. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  44694. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  44695. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  44696. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  44697. defines._needNormals = true;
  44698. defines.FRESNEL = true;
  44699. }
  44700. }
  44701. else {
  44702. defines.FRESNEL = false;
  44703. }
  44704. }
  44705. // Misc.
  44706. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  44707. // Attribs
  44708. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  44709. // Values that need to be evaluated on every frame
  44710. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  44711. // Get correct effect
  44712. if (defines.isDirty) {
  44713. defines.markAsProcessed();
  44714. scene.resetCachedMaterial();
  44715. // Fallbacks
  44716. var fallbacks = new BABYLON.EffectFallbacks();
  44717. if (defines.REFLECTION) {
  44718. fallbacks.addFallback(0, "REFLECTION");
  44719. }
  44720. if (defines.SPECULAR) {
  44721. fallbacks.addFallback(0, "SPECULAR");
  44722. }
  44723. if (defines.BUMP) {
  44724. fallbacks.addFallback(0, "BUMP");
  44725. }
  44726. if (defines.PARALLAX) {
  44727. fallbacks.addFallback(1, "PARALLAX");
  44728. }
  44729. if (defines.PARALLAXOCCLUSION) {
  44730. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44731. }
  44732. if (defines.SPECULAROVERALPHA) {
  44733. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44734. }
  44735. if (defines.FOG) {
  44736. fallbacks.addFallback(1, "FOG");
  44737. }
  44738. if (defines.POINTSIZE) {
  44739. fallbacks.addFallback(0, "POINTSIZE");
  44740. }
  44741. if (defines.LOGARITHMICDEPTH) {
  44742. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44743. }
  44744. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  44745. if (defines.SPECULARTERM) {
  44746. fallbacks.addFallback(0, "SPECULARTERM");
  44747. }
  44748. if (defines.DIFFUSEFRESNEL) {
  44749. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44750. }
  44751. if (defines.OPACITYFRESNEL) {
  44752. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44753. }
  44754. if (defines.REFLECTIONFRESNEL) {
  44755. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44756. }
  44757. if (defines.EMISSIVEFRESNEL) {
  44758. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44759. }
  44760. if (defines.FRESNEL) {
  44761. fallbacks.addFallback(4, "FRESNEL");
  44762. }
  44763. //Attributes
  44764. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44765. if (defines.NORMAL) {
  44766. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44767. }
  44768. if (defines.UV1) {
  44769. attribs.push(BABYLON.VertexBuffer.UVKind);
  44770. }
  44771. if (defines.UV2) {
  44772. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44773. }
  44774. if (defines.VERTEXCOLOR) {
  44775. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44776. }
  44777. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44778. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44779. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44780. var shaderName = "default";
  44781. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44782. "vFogInfos", "vFogColor", "pointSize",
  44783. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44784. "mBones",
  44785. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44786. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44787. "logarithmicDepthConstant", "vNormalReoderParams"
  44788. ];
  44789. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  44790. var uniformBuffers = ["Material", "Scene"];
  44791. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44792. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44793. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44794. uniformsNames: uniforms,
  44795. uniformBuffersNames: uniformBuffers,
  44796. samplers: samplers,
  44797. defines: defines,
  44798. maxSimultaneousLights: this._maxSimultaneousLights
  44799. });
  44800. if (this.customShaderNameResolve) {
  44801. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44802. }
  44803. var join = defines.toString();
  44804. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  44805. attributes: attribs,
  44806. uniformsNames: uniforms,
  44807. uniformBuffersNames: uniformBuffers,
  44808. samplers: samplers,
  44809. defines: join,
  44810. fallbacks: fallbacks,
  44811. onCompiled: this.onCompiled,
  44812. onError: this.onError,
  44813. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44814. }, engine), defines);
  44815. this.buildUniformLayout();
  44816. }
  44817. if (!subMesh.effect.isReady()) {
  44818. return false;
  44819. }
  44820. defines._renderId = scene.getRenderId();
  44821. this._wasPreviouslyReady = true;
  44822. return true;
  44823. };
  44824. StandardMaterial.prototype.buildUniformLayout = function () {
  44825. // Order is important !
  44826. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44827. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44828. this._uniformBuffer.addUniform("opacityParts", 4);
  44829. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44830. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44831. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44832. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44833. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44834. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44835. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44836. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44837. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44838. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44839. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44840. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44841. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44842. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44843. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44844. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44845. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44846. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44847. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44848. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44849. this._uniformBuffer.addUniform("specularMatrix", 16);
  44850. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44851. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  44852. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44853. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44854. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44855. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44856. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44857. this._uniformBuffer.addUniform("pointSize", 1);
  44858. this._uniformBuffer.create();
  44859. };
  44860. StandardMaterial.prototype.unbind = function () {
  44861. if (this._activeEffect) {
  44862. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44863. this._activeEffect.setTexture("reflection2DSampler", null);
  44864. }
  44865. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44866. this._activeEffect.setTexture("refraction2DSampler", null);
  44867. }
  44868. }
  44869. _super.prototype.unbind.call(this);
  44870. };
  44871. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44872. var scene = this.getScene();
  44873. var defines = subMesh._materialDefines;
  44874. if (!defines) {
  44875. return;
  44876. }
  44877. var effect = subMesh.effect;
  44878. this._activeEffect = effect;
  44879. // Matrices
  44880. this.bindOnlyWorldMatrix(world);
  44881. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44882. // Bones
  44883. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44884. if (mustRebind) {
  44885. this._uniformBuffer.bindToEffect(effect, "Material");
  44886. this.bindViewProjection(effect);
  44887. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44888. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44889. // Fresnel
  44890. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44891. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44892. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44893. }
  44894. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44895. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44896. }
  44897. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44898. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44899. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44900. }
  44901. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44902. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44903. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44904. }
  44905. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44906. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44907. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44908. }
  44909. }
  44910. // Textures
  44911. if (scene.texturesEnabled) {
  44912. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44913. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44914. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44915. }
  44916. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44917. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44918. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44919. }
  44920. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44921. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44922. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44923. }
  44924. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44925. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44926. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44927. }
  44928. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44929. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44930. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44931. }
  44932. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44933. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44934. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44935. }
  44936. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44937. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44938. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44939. }
  44940. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44941. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44942. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44943. if (scene._mirroredCameraPosition) {
  44944. 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);
  44945. }
  44946. else {
  44947. 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);
  44948. }
  44949. }
  44950. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44951. var depth = 1.0;
  44952. if (!this._refractionTexture.isCube) {
  44953. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44954. if (this._refractionTexture.depth) {
  44955. depth = this._refractionTexture.depth;
  44956. }
  44957. }
  44958. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44959. }
  44960. }
  44961. // Point size
  44962. if (this.pointsCloud) {
  44963. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44964. }
  44965. if (defines.SPECULARTERM) {
  44966. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44967. }
  44968. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44969. // Diffuse
  44970. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44971. }
  44972. // Textures
  44973. if (scene.texturesEnabled) {
  44974. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44975. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44976. }
  44977. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44978. effect.setTexture("ambientSampler", this._ambientTexture);
  44979. }
  44980. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44981. effect.setTexture("opacitySampler", this._opacityTexture);
  44982. }
  44983. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44984. if (this._reflectionTexture.isCube) {
  44985. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44986. }
  44987. else {
  44988. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44989. }
  44990. }
  44991. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44992. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44993. }
  44994. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44995. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44996. }
  44997. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44998. effect.setTexture("specularSampler", this._specularTexture);
  44999. }
  45000. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  45001. effect.setTexture("bumpSampler", this._bumpTexture);
  45002. }
  45003. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  45004. var depth = 1.0;
  45005. if (this._refractionTexture.isCube) {
  45006. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  45007. }
  45008. else {
  45009. effect.setTexture("refraction2DSampler", this._refractionTexture);
  45010. }
  45011. }
  45012. }
  45013. // Clip plane
  45014. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  45015. // Colors
  45016. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  45017. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45018. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45019. }
  45020. if (mustRebind || !this.isFrozen) {
  45021. // Lights
  45022. if (scene.lightsEnabled && !this._disableLighting) {
  45023. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  45024. }
  45025. // View
  45026. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  45027. this.bindView(effect);
  45028. }
  45029. // Fog
  45030. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  45031. // Morph targets
  45032. if (defines.NUM_MORPH_INFLUENCERS) {
  45033. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  45034. }
  45035. // Log. depth
  45036. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  45037. // image processing
  45038. this._imageProcessingConfiguration.bind(this._activeEffect);
  45039. }
  45040. this._uniformBuffer.update();
  45041. this._afterBind(mesh, this._activeEffect);
  45042. };
  45043. StandardMaterial.prototype.getAnimatables = function () {
  45044. var results = [];
  45045. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  45046. results.push(this._diffuseTexture);
  45047. }
  45048. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45049. results.push(this._ambientTexture);
  45050. }
  45051. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45052. results.push(this._opacityTexture);
  45053. }
  45054. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45055. results.push(this._reflectionTexture);
  45056. }
  45057. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45058. results.push(this._emissiveTexture);
  45059. }
  45060. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  45061. results.push(this._specularTexture);
  45062. }
  45063. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45064. results.push(this._bumpTexture);
  45065. }
  45066. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45067. results.push(this._lightmapTexture);
  45068. }
  45069. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45070. results.push(this._refractionTexture);
  45071. }
  45072. return results;
  45073. };
  45074. StandardMaterial.prototype.getActiveTextures = function () {
  45075. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45076. if (this._diffuseTexture) {
  45077. activeTextures.push(this._diffuseTexture);
  45078. }
  45079. if (this._ambientTexture) {
  45080. activeTextures.push(this._ambientTexture);
  45081. }
  45082. if (this._opacityTexture) {
  45083. activeTextures.push(this._opacityTexture);
  45084. }
  45085. if (this._reflectionTexture) {
  45086. activeTextures.push(this._reflectionTexture);
  45087. }
  45088. if (this._emissiveTexture) {
  45089. activeTextures.push(this._emissiveTexture);
  45090. }
  45091. if (this._specularTexture) {
  45092. activeTextures.push(this._specularTexture);
  45093. }
  45094. if (this._bumpTexture) {
  45095. activeTextures.push(this._bumpTexture);
  45096. }
  45097. if (this._lightmapTexture) {
  45098. activeTextures.push(this._lightmapTexture);
  45099. }
  45100. if (this._refractionTexture) {
  45101. activeTextures.push(this._refractionTexture);
  45102. }
  45103. return activeTextures;
  45104. };
  45105. StandardMaterial.prototype.hasTexture = function (texture) {
  45106. if (_super.prototype.hasTexture.call(this, texture)) {
  45107. return true;
  45108. }
  45109. if (this._diffuseTexture === texture) {
  45110. return true;
  45111. }
  45112. if (this._ambientTexture === texture) {
  45113. return true;
  45114. }
  45115. if (this._opacityTexture === texture) {
  45116. return true;
  45117. }
  45118. if (this._reflectionTexture === texture) {
  45119. return true;
  45120. }
  45121. if (this._emissiveTexture === texture) {
  45122. return true;
  45123. }
  45124. if (this._specularTexture === texture) {
  45125. return true;
  45126. }
  45127. if (this._bumpTexture === texture) {
  45128. return true;
  45129. }
  45130. if (this._lightmapTexture === texture) {
  45131. return true;
  45132. }
  45133. if (this._refractionTexture === texture) {
  45134. return true;
  45135. }
  45136. return false;
  45137. };
  45138. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45139. if (forceDisposeTextures) {
  45140. if (this._diffuseTexture) {
  45141. this._diffuseTexture.dispose();
  45142. }
  45143. if (this._ambientTexture) {
  45144. this._ambientTexture.dispose();
  45145. }
  45146. if (this._opacityTexture) {
  45147. this._opacityTexture.dispose();
  45148. }
  45149. if (this._reflectionTexture) {
  45150. this._reflectionTexture.dispose();
  45151. }
  45152. if (this._emissiveTexture) {
  45153. this._emissiveTexture.dispose();
  45154. }
  45155. if (this._specularTexture) {
  45156. this._specularTexture.dispose();
  45157. }
  45158. if (this._bumpTexture) {
  45159. this._bumpTexture.dispose();
  45160. }
  45161. if (this._lightmapTexture) {
  45162. this._lightmapTexture.dispose();
  45163. }
  45164. if (this._refractionTexture) {
  45165. this._refractionTexture.dispose();
  45166. }
  45167. }
  45168. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45169. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45170. }
  45171. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45172. };
  45173. StandardMaterial.prototype.clone = function (name) {
  45174. var _this = this;
  45175. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  45176. result.name = name;
  45177. result.id = name;
  45178. return result;
  45179. };
  45180. StandardMaterial.prototype.serialize = function () {
  45181. return BABYLON.SerializationHelper.Serialize(this);
  45182. };
  45183. // Statics
  45184. StandardMaterial.Parse = function (source, scene, rootUrl) {
  45185. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  45186. };
  45187. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  45188. get: function () {
  45189. return StandardMaterial._DiffuseTextureEnabled;
  45190. },
  45191. set: function (value) {
  45192. if (StandardMaterial._DiffuseTextureEnabled === value) {
  45193. return;
  45194. }
  45195. StandardMaterial._DiffuseTextureEnabled = value;
  45196. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45197. },
  45198. enumerable: true,
  45199. configurable: true
  45200. });
  45201. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  45202. get: function () {
  45203. return StandardMaterial._AmbientTextureEnabled;
  45204. },
  45205. set: function (value) {
  45206. if (StandardMaterial._AmbientTextureEnabled === value) {
  45207. return;
  45208. }
  45209. StandardMaterial._AmbientTextureEnabled = value;
  45210. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45211. },
  45212. enumerable: true,
  45213. configurable: true
  45214. });
  45215. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  45216. get: function () {
  45217. return StandardMaterial._OpacityTextureEnabled;
  45218. },
  45219. set: function (value) {
  45220. if (StandardMaterial._OpacityTextureEnabled === value) {
  45221. return;
  45222. }
  45223. StandardMaterial._OpacityTextureEnabled = value;
  45224. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45225. },
  45226. enumerable: true,
  45227. configurable: true
  45228. });
  45229. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  45230. get: function () {
  45231. return StandardMaterial._ReflectionTextureEnabled;
  45232. },
  45233. set: function (value) {
  45234. if (StandardMaterial._ReflectionTextureEnabled === value) {
  45235. return;
  45236. }
  45237. StandardMaterial._ReflectionTextureEnabled = value;
  45238. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45239. },
  45240. enumerable: true,
  45241. configurable: true
  45242. });
  45243. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  45244. get: function () {
  45245. return StandardMaterial._EmissiveTextureEnabled;
  45246. },
  45247. set: function (value) {
  45248. if (StandardMaterial._EmissiveTextureEnabled === value) {
  45249. return;
  45250. }
  45251. StandardMaterial._EmissiveTextureEnabled = value;
  45252. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45253. },
  45254. enumerable: true,
  45255. configurable: true
  45256. });
  45257. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  45258. get: function () {
  45259. return StandardMaterial._SpecularTextureEnabled;
  45260. },
  45261. set: function (value) {
  45262. if (StandardMaterial._SpecularTextureEnabled === value) {
  45263. return;
  45264. }
  45265. StandardMaterial._SpecularTextureEnabled = value;
  45266. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45267. },
  45268. enumerable: true,
  45269. configurable: true
  45270. });
  45271. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  45272. get: function () {
  45273. return StandardMaterial._BumpTextureEnabled;
  45274. },
  45275. set: function (value) {
  45276. if (StandardMaterial._BumpTextureEnabled === value) {
  45277. return;
  45278. }
  45279. StandardMaterial._BumpTextureEnabled = value;
  45280. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45281. },
  45282. enumerable: true,
  45283. configurable: true
  45284. });
  45285. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  45286. get: function () {
  45287. return StandardMaterial._LightmapTextureEnabled;
  45288. },
  45289. set: function (value) {
  45290. if (StandardMaterial._LightmapTextureEnabled === value) {
  45291. return;
  45292. }
  45293. StandardMaterial._LightmapTextureEnabled = value;
  45294. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45295. },
  45296. enumerable: true,
  45297. configurable: true
  45298. });
  45299. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  45300. get: function () {
  45301. return StandardMaterial._RefractionTextureEnabled;
  45302. },
  45303. set: function (value) {
  45304. if (StandardMaterial._RefractionTextureEnabled === value) {
  45305. return;
  45306. }
  45307. StandardMaterial._RefractionTextureEnabled = value;
  45308. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45309. },
  45310. enumerable: true,
  45311. configurable: true
  45312. });
  45313. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  45314. get: function () {
  45315. return StandardMaterial._ColorGradingTextureEnabled;
  45316. },
  45317. set: function (value) {
  45318. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  45319. return;
  45320. }
  45321. StandardMaterial._ColorGradingTextureEnabled = value;
  45322. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45323. },
  45324. enumerable: true,
  45325. configurable: true
  45326. });
  45327. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  45328. get: function () {
  45329. return StandardMaterial._FresnelEnabled;
  45330. },
  45331. set: function (value) {
  45332. if (StandardMaterial._FresnelEnabled === value) {
  45333. return;
  45334. }
  45335. StandardMaterial._FresnelEnabled = value;
  45336. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  45337. },
  45338. enumerable: true,
  45339. configurable: true
  45340. });
  45341. // Flags used to enable or disable a type of texture for all Standard Materials
  45342. StandardMaterial._DiffuseTextureEnabled = true;
  45343. StandardMaterial._AmbientTextureEnabled = true;
  45344. StandardMaterial._OpacityTextureEnabled = true;
  45345. StandardMaterial._ReflectionTextureEnabled = true;
  45346. StandardMaterial._EmissiveTextureEnabled = true;
  45347. StandardMaterial._SpecularTextureEnabled = true;
  45348. StandardMaterial._BumpTextureEnabled = true;
  45349. StandardMaterial._LightmapTextureEnabled = true;
  45350. StandardMaterial._RefractionTextureEnabled = true;
  45351. StandardMaterial._ColorGradingTextureEnabled = true;
  45352. StandardMaterial._FresnelEnabled = true;
  45353. __decorate([
  45354. BABYLON.serializeAsTexture("diffuseTexture")
  45355. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  45356. __decorate([
  45357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45358. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  45359. __decorate([
  45360. BABYLON.serializeAsTexture("ambientTexture")
  45361. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  45362. __decorate([
  45363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45364. ], StandardMaterial.prototype, "ambientTexture", void 0);
  45365. __decorate([
  45366. BABYLON.serializeAsTexture("opacityTexture")
  45367. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  45368. __decorate([
  45369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45370. ], StandardMaterial.prototype, "opacityTexture", void 0);
  45371. __decorate([
  45372. BABYLON.serializeAsTexture("reflectionTexture")
  45373. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  45374. __decorate([
  45375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45376. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  45377. __decorate([
  45378. BABYLON.serializeAsTexture("emissiveTexture")
  45379. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  45380. __decorate([
  45381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45382. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  45383. __decorate([
  45384. BABYLON.serializeAsTexture("specularTexture")
  45385. ], StandardMaterial.prototype, "_specularTexture", void 0);
  45386. __decorate([
  45387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45388. ], StandardMaterial.prototype, "specularTexture", void 0);
  45389. __decorate([
  45390. BABYLON.serializeAsTexture("bumpTexture")
  45391. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  45392. __decorate([
  45393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45394. ], StandardMaterial.prototype, "bumpTexture", void 0);
  45395. __decorate([
  45396. BABYLON.serializeAsTexture("lightmapTexture")
  45397. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  45398. __decorate([
  45399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45400. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  45401. __decorate([
  45402. BABYLON.serializeAsTexture("refractionTexture")
  45403. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  45404. __decorate([
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45406. ], StandardMaterial.prototype, "refractionTexture", void 0);
  45407. __decorate([
  45408. BABYLON.serializeAsColor3("ambient")
  45409. ], StandardMaterial.prototype, "ambientColor", void 0);
  45410. __decorate([
  45411. BABYLON.serializeAsColor3("diffuse")
  45412. ], StandardMaterial.prototype, "diffuseColor", void 0);
  45413. __decorate([
  45414. BABYLON.serializeAsColor3("specular")
  45415. ], StandardMaterial.prototype, "specularColor", void 0);
  45416. __decorate([
  45417. BABYLON.serializeAsColor3("emissive")
  45418. ], StandardMaterial.prototype, "emissiveColor", void 0);
  45419. __decorate([
  45420. BABYLON.serialize()
  45421. ], StandardMaterial.prototype, "specularPower", void 0);
  45422. __decorate([
  45423. BABYLON.serialize("useAlphaFromDiffuseTexture")
  45424. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  45425. __decorate([
  45426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45427. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  45428. __decorate([
  45429. BABYLON.serialize("useEmissiveAsIllumination")
  45430. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  45431. __decorate([
  45432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45433. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45434. __decorate([
  45435. BABYLON.serialize("linkEmissiveWithDiffuse")
  45436. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  45437. __decorate([
  45438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45439. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  45440. __decorate([
  45441. BABYLON.serialize("useSpecularOverAlpha")
  45442. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  45443. __decorate([
  45444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45445. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  45446. __decorate([
  45447. BABYLON.serialize("useReflectionOverAlpha")
  45448. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  45449. __decorate([
  45450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45451. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  45452. __decorate([
  45453. BABYLON.serialize("disableLighting")
  45454. ], StandardMaterial.prototype, "_disableLighting", void 0);
  45455. __decorate([
  45456. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45457. ], StandardMaterial.prototype, "disableLighting", void 0);
  45458. __decorate([
  45459. BABYLON.serialize("useParallax")
  45460. ], StandardMaterial.prototype, "_useParallax", void 0);
  45461. __decorate([
  45462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45463. ], StandardMaterial.prototype, "useParallax", void 0);
  45464. __decorate([
  45465. BABYLON.serialize("useParallaxOcclusion")
  45466. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  45467. __decorate([
  45468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45469. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  45470. __decorate([
  45471. BABYLON.serialize()
  45472. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  45473. __decorate([
  45474. BABYLON.serialize("roughness")
  45475. ], StandardMaterial.prototype, "_roughness", void 0);
  45476. __decorate([
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], StandardMaterial.prototype, "roughness", void 0);
  45479. __decorate([
  45480. BABYLON.serialize()
  45481. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  45482. __decorate([
  45483. BABYLON.serialize()
  45484. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  45485. __decorate([
  45486. BABYLON.serialize("useLightmapAsShadowmap")
  45487. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  45488. __decorate([
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45490. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45491. __decorate([
  45492. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  45493. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  45494. __decorate([
  45495. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45496. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  45497. __decorate([
  45498. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  45499. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  45500. __decorate([
  45501. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45502. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  45503. __decorate([
  45504. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  45505. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  45506. __decorate([
  45507. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45508. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  45509. __decorate([
  45510. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  45511. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  45512. __decorate([
  45513. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45514. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  45515. __decorate([
  45516. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  45517. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  45518. __decorate([
  45519. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45520. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  45521. __decorate([
  45522. BABYLON.serialize("useReflectionFresnelFromSpecular")
  45523. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  45524. __decorate([
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45526. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  45527. __decorate([
  45528. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  45529. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  45530. __decorate([
  45531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45532. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  45533. __decorate([
  45534. BABYLON.serialize("maxSimultaneousLights")
  45535. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  45536. __decorate([
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45538. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  45539. __decorate([
  45540. BABYLON.serialize("invertNormalMapX")
  45541. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  45542. __decorate([
  45543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45544. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  45545. __decorate([
  45546. BABYLON.serialize("invertNormalMapY")
  45547. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  45548. __decorate([
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45550. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  45551. __decorate([
  45552. BABYLON.serialize("twoSidedLighting")
  45553. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  45554. __decorate([
  45555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45556. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  45557. __decorate([
  45558. BABYLON.serialize()
  45559. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  45560. return StandardMaterial;
  45561. }(BABYLON.PushMaterial));
  45562. BABYLON.StandardMaterial = StandardMaterial;
  45563. })(BABYLON || (BABYLON = {}));
  45564. //# sourceMappingURL=babylon.standardMaterial.js.map
  45565. var BABYLON;
  45566. (function (BABYLON) {
  45567. /**
  45568. * This class implement a typical dictionary using a string as key and the generic type T as value.
  45569. * The underlying implementation relies on an associative array to ensure the best performances.
  45570. * The value can be anything including 'null' but except 'undefined'
  45571. */
  45572. var StringDictionary = (function () {
  45573. function StringDictionary() {
  45574. this._count = 0;
  45575. this._data = {};
  45576. }
  45577. /**
  45578. * This will clear this dictionary and copy the content from the 'source' one.
  45579. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  45580. * @param source the dictionary to take the content from and copy to this dictionary
  45581. */
  45582. StringDictionary.prototype.copyFrom = function (source) {
  45583. var _this = this;
  45584. this.clear();
  45585. source.forEach(function (t, v) { return _this.add(t, v); });
  45586. };
  45587. /**
  45588. * Get a value based from its key
  45589. * @param key the given key to get the matching value from
  45590. * @return the value if found, otherwise undefined is returned
  45591. */
  45592. StringDictionary.prototype.get = function (key) {
  45593. var val = this._data[key];
  45594. if (val !== undefined) {
  45595. return val;
  45596. }
  45597. return undefined;
  45598. };
  45599. /**
  45600. * Get a value from its key or add it if it doesn't exist.
  45601. * This method will ensure you that a given key/data will be present in the dictionary.
  45602. * @param key the given key to get the matching value from
  45603. * @param factory the factory that will create the value if the key is not present in the dictionary.
  45604. * The factory will only be invoked if there's no data for the given key.
  45605. * @return the value corresponding to the key.
  45606. */
  45607. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  45608. var val = this.get(key);
  45609. if (val !== undefined) {
  45610. return val;
  45611. }
  45612. val = factory(key);
  45613. if (val) {
  45614. this.add(key, val);
  45615. }
  45616. return val;
  45617. };
  45618. /**
  45619. * Get a value from its key if present in the dictionary otherwise add it
  45620. * @param key the key to get the value from
  45621. * @param val if there's no such key/value pair in the dictionary add it with this value
  45622. * @return the value corresponding to the key
  45623. */
  45624. StringDictionary.prototype.getOrAdd = function (key, val) {
  45625. var curVal = this.get(key);
  45626. if (curVal !== undefined) {
  45627. return curVal;
  45628. }
  45629. this.add(key, val);
  45630. return val;
  45631. };
  45632. /**
  45633. * Check if there's a given key in the dictionary
  45634. * @param key the key to check for
  45635. * @return true if the key is present, false otherwise
  45636. */
  45637. StringDictionary.prototype.contains = function (key) {
  45638. return this._data[key] !== undefined;
  45639. };
  45640. /**
  45641. * Add a new key and its corresponding value
  45642. * @param key the key to add
  45643. * @param value the value corresponding to the key
  45644. * @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
  45645. */
  45646. StringDictionary.prototype.add = function (key, value) {
  45647. if (this._data[key] !== undefined) {
  45648. return false;
  45649. }
  45650. this._data[key] = value;
  45651. ++this._count;
  45652. return true;
  45653. };
  45654. StringDictionary.prototype.set = function (key, value) {
  45655. if (this._data[key] === undefined) {
  45656. return false;
  45657. }
  45658. this._data[key] = value;
  45659. return true;
  45660. };
  45661. /**
  45662. * Get the element of the given key and remove it from the dictionary
  45663. * @param key
  45664. */
  45665. StringDictionary.prototype.getAndRemove = function (key) {
  45666. var val = this.get(key);
  45667. if (val !== undefined) {
  45668. delete this._data[key];
  45669. --this._count;
  45670. return val;
  45671. }
  45672. return null;
  45673. };
  45674. /**
  45675. * Remove a key/value from the dictionary.
  45676. * @param key the key to remove
  45677. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  45678. */
  45679. StringDictionary.prototype.remove = function (key) {
  45680. if (this.contains(key)) {
  45681. delete this._data[key];
  45682. --this._count;
  45683. return true;
  45684. }
  45685. return false;
  45686. };
  45687. /**
  45688. * Clear the whole content of the dictionary
  45689. */
  45690. StringDictionary.prototype.clear = function () {
  45691. this._data = {};
  45692. this._count = 0;
  45693. };
  45694. Object.defineProperty(StringDictionary.prototype, "count", {
  45695. get: function () {
  45696. return this._count;
  45697. },
  45698. enumerable: true,
  45699. configurable: true
  45700. });
  45701. /**
  45702. * Execute a callback on each key/val of the dictionary.
  45703. * Note that you can remove any element in this dictionary in the callback implementation
  45704. * @param callback the callback to execute on a given key/value pair
  45705. */
  45706. StringDictionary.prototype.forEach = function (callback) {
  45707. for (var cur in this._data) {
  45708. var val = this._data[cur];
  45709. callback(cur, val);
  45710. }
  45711. };
  45712. /**
  45713. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  45714. * If the callback returns null or undefined the method will iterate to the next key/value pair
  45715. * Note that you can remove any element in this dictionary in the callback implementation
  45716. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  45717. */
  45718. StringDictionary.prototype.first = function (callback) {
  45719. for (var cur in this._data) {
  45720. var val = this._data[cur];
  45721. var res = callback(cur, val);
  45722. if (res) {
  45723. return res;
  45724. }
  45725. }
  45726. return null;
  45727. };
  45728. return StringDictionary;
  45729. }());
  45730. BABYLON.StringDictionary = StringDictionary;
  45731. })(BABYLON || (BABYLON = {}));
  45732. //# sourceMappingURL=babylon.stringDictionary.js.map
  45733. var BABYLON;
  45734. (function (BABYLON) {
  45735. var DynamicFloatArrayElementInfo = (function () {
  45736. function DynamicFloatArrayElementInfo() {
  45737. }
  45738. return DynamicFloatArrayElementInfo;
  45739. }());
  45740. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  45741. /**
  45742. * 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.
  45743. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  45744. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  45745. * 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.
  45746. * 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.
  45747. * 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".
  45748. */
  45749. var DynamicFloatArray = (function () {
  45750. /**
  45751. * Construct an instance of the dynamic float array
  45752. * @param stride size of one element in float (i.e. not bytes!)
  45753. * @param initialElementCount the number of available entries at construction
  45754. */
  45755. function DynamicFloatArray(stride, initialElementCount) {
  45756. this.compareValueOffset = null;
  45757. this.sortingAscending = true;
  45758. this._stride = stride;
  45759. this.buffer = new Float32Array(stride * initialElementCount);
  45760. this._lastUsed = 0;
  45761. this._firstFree = 0;
  45762. this._allEntries = new Array(initialElementCount);
  45763. this._freeEntries = new Array(initialElementCount);
  45764. for (var i = 0; i < initialElementCount; i++) {
  45765. var element = new DynamicFloatArrayElementInfo();
  45766. element.offset = i * stride;
  45767. this._allEntries[i] = element;
  45768. this._freeEntries[initialElementCount - i - 1] = element;
  45769. }
  45770. }
  45771. /**
  45772. * Allocate an element in the array.
  45773. * @return the element info instance that contains the offset into the main buffer of the element's location.
  45774. * Beware, this offset may change when you call pack()
  45775. */
  45776. DynamicFloatArray.prototype.allocElement = function () {
  45777. if (this._freeEntries.length === 0) {
  45778. this._growBuffer();
  45779. }
  45780. var el = this._freeEntries.pop();
  45781. this._lastUsed = Math.max(el.offset, this._lastUsed);
  45782. if (el.offset === this._firstFree) {
  45783. if (this._freeEntries.length > 0) {
  45784. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  45785. }
  45786. else {
  45787. this._firstFree += this._stride;
  45788. }
  45789. }
  45790. return el;
  45791. };
  45792. /**
  45793. * Free the element corresponding to the given element info
  45794. * @param elInfo the element that describe the allocated element
  45795. */
  45796. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  45797. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  45798. this._freeEntries.push(elInfo);
  45799. };
  45800. /**
  45801. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  45802. * 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().
  45803. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  45804. */
  45805. DynamicFloatArray.prototype.pack = function () {
  45806. // no free slot? no need to pack
  45807. if (this._freeEntries.length === 0) {
  45808. return this.buffer;
  45809. }
  45810. // If the buffer is already packed the last used will always be lower than the first free
  45811. // 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.
  45812. if (this._lastUsed < this._firstFree) {
  45813. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  45814. return elementsBuffer_1;
  45815. }
  45816. var s = this._stride;
  45817. // 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
  45818. var lastFree = new DynamicFloatArrayElementInfo();
  45819. lastFree.offset = this.totalElementCount * s;
  45820. this._freeEntries.push(lastFree);
  45821. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  45822. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45823. var firstFreeSlotOffset = sortedFree[0].offset;
  45824. var freeZoneSize = 1;
  45825. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  45826. var prevOffset = sortedFree[0].offset;
  45827. for (var i = 1; i < sortedFree.length; i++) {
  45828. // 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
  45829. if (firstFreeSlotOffset >= occupiedZoneSize) {
  45830. break;
  45831. }
  45832. var curFree = sortedFree[i];
  45833. var curOffset = curFree.offset;
  45834. // Compute the distance between this offset and the previous
  45835. var distance = curOffset - prevOffset;
  45836. // If the distance is the stride size, they are adjacent, it good, move to the next
  45837. if (distance === s) {
  45838. // Free zone is one element bigger
  45839. ++freeZoneSize;
  45840. // as we're about to iterate to the next, the cur becomes the previous...
  45841. prevOffset = curOffset;
  45842. continue;
  45843. }
  45844. // Distance is bigger, which means there's x element between the previous free and this one
  45845. var usedRange = (distance / s) - 1;
  45846. // Two cases the free zone is smaller than the data to move or bigger
  45847. // Copy what can fit in the free zone
  45848. var curMoveOffset = curOffset - s;
  45849. var copyCount = Math.min(freeZoneSize, usedRange);
  45850. for (var j = 0; j < copyCount; j++) {
  45851. var freeI = firstFreeSlotOffset / s;
  45852. var curI = curMoveOffset / s;
  45853. var moveEl = sortedAll[curI];
  45854. this._moveElement(moveEl, firstFreeSlotOffset);
  45855. var replacedEl = sortedAll[freeI];
  45856. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  45857. replacedEl.offset = curMoveOffset;
  45858. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  45859. sortedAll[freeI] = moveEl;
  45860. sortedAll[curI] = replacedEl;
  45861. curMoveOffset -= s;
  45862. firstFreeSlotOffset += s;
  45863. }
  45864. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  45865. if (freeZoneSize <= usedRange) {
  45866. firstFreeSlotOffset = curMoveOffset + s;
  45867. freeZoneSize = 1 + copyCount;
  45868. }
  45869. else {
  45870. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  45871. }
  45872. // as we're about to iterate to the next, the cur becomes the previous...
  45873. prevOffset = curOffset;
  45874. }
  45875. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  45876. this._lastUsed = firstFreeSlotOffset - s;
  45877. this._firstFree = firstFreeSlotOffset;
  45878. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  45879. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  45880. this._allEntries = sortedAll;
  45881. return elementsBuffer;
  45882. };
  45883. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  45884. for (var i = 0; i < this._stride; i++) {
  45885. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  45886. }
  45887. element.offset = destOffset;
  45888. };
  45889. DynamicFloatArray.prototype._growBuffer = function () {
  45890. // Allocate the new buffer with 50% more entries, copy the content of the current one
  45891. var newElCount = Math.floor(this.totalElementCount * 1.5);
  45892. var newBuffer = new Float32Array(newElCount * this._stride);
  45893. newBuffer.set(this.buffer);
  45894. var curCount = this.totalElementCount;
  45895. var addedCount = newElCount - this.totalElementCount;
  45896. for (var i = 0; i < addedCount; i++) {
  45897. var element = new DynamicFloatArrayElementInfo();
  45898. element.offset = (curCount + i) * this.stride;
  45899. this._allEntries.push(element);
  45900. this._freeEntries[addedCount - i - 1] = element;
  45901. }
  45902. this._firstFree = curCount * this.stride;
  45903. this.buffer = newBuffer;
  45904. };
  45905. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  45906. /**
  45907. * Get the total count of entries that can fit in the current buffer
  45908. * @returns the elements count
  45909. */
  45910. get: function () {
  45911. return this._allEntries.length;
  45912. },
  45913. enumerable: true,
  45914. configurable: true
  45915. });
  45916. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  45917. /**
  45918. * Get the count of free entries that can still be allocated without resizing the buffer
  45919. * @returns the free elements count
  45920. */
  45921. get: function () {
  45922. return this._freeEntries.length;
  45923. },
  45924. enumerable: true,
  45925. configurable: true
  45926. });
  45927. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  45928. /**
  45929. * Get the count of allocated elements
  45930. * @returns the allocated elements count
  45931. */
  45932. get: function () {
  45933. return this._allEntries.length - this._freeEntries.length;
  45934. },
  45935. enumerable: true,
  45936. configurable: true
  45937. });
  45938. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  45939. /**
  45940. * Return the size of one element in float
  45941. * @returns the size in float
  45942. */
  45943. get: function () {
  45944. return this._stride;
  45945. },
  45946. enumerable: true,
  45947. configurable: true
  45948. });
  45949. DynamicFloatArray.prototype.sort = function () {
  45950. var _this = this;
  45951. if (!this.compareValueOffset) {
  45952. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  45953. }
  45954. var count = this.usedElementCount;
  45955. // Do we have to (re)create the sort table?
  45956. if (!this._sortTable || this._sortTable.length < count) {
  45957. // 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...
  45958. var newCount = Math.min(this.totalElementCount, count * 2);
  45959. this._sortTable = new Array(newCount);
  45960. }
  45961. if (!this._sortedTable || this._sortedTable.length !== count) {
  45962. this._sortedTable = new Array(count);
  45963. }
  45964. // Because, you know...
  45965. this.pack();
  45966. //let stride = this.stride;
  45967. //for (let i = 0; i < count; i++) {
  45968. // let si = this._sortTable[i];
  45969. // if (!si) {
  45970. // si = new SortInfo();
  45971. // this._sortTable[i] = si;
  45972. // }
  45973. // si.entry = this._allEntries[i];
  45974. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  45975. // si.swapedOffset = null;
  45976. // this._sortedTable[i] = si;
  45977. //}
  45978. var curOffset = 0;
  45979. var stride = this.stride;
  45980. for (var i = 0; i < count; i++, curOffset += stride) {
  45981. var si = this._sortTable[i];
  45982. if (!si) {
  45983. si = new SortInfo();
  45984. this._sortTable[i] = si;
  45985. }
  45986. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  45987. si.offset = curOffset;
  45988. si.swapedOffset = null;
  45989. this._sortedTable[i] = si;
  45990. }
  45991. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  45992. if (this.sortingAscending) {
  45993. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  45994. }
  45995. else {
  45996. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  45997. }
  45998. var swapElements = function (src, dst) {
  45999. for (var i = 0; i < stride; i++) {
  46000. var tps = _this.buffer[dst + i];
  46001. _this.buffer[dst + i] = _this.buffer[src + i];
  46002. _this.buffer[src + i] = tps;
  46003. }
  46004. };
  46005. // 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:
  46006. // 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),
  46007. // and I still want something with a good algorithm complexity.
  46008. // 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,
  46009. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  46010. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  46011. // 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
  46012. // until we find a SortInfo object without a swapedOffset which means we got the right location
  46013. // 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
  46014. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  46015. for (var i = 0; i < count; i++) {
  46016. // Get the element to move
  46017. var sourceSI = this._sortedTable[i];
  46018. var destSI = this._sortTable[i];
  46019. var sourceOff = sourceSI.offset;
  46020. // If the source changed location, find the new one
  46021. if (sourceSI.swapedOffset) {
  46022. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  46023. var curSI = sourceSI;
  46024. while (curSI.swapedOffset) {
  46025. curSI = this._sortTable[curSI.swapedOffset / stride];
  46026. }
  46027. // Finally get the right location
  46028. sourceOff = curSI.offset;
  46029. }
  46030. // Tag the element being replaced with its new location
  46031. destSI.swapedOffset = sourceOff;
  46032. // Swap elements (only if needed)
  46033. if (sourceOff !== destSI.offset) {
  46034. swapElements(sourceOff, destSI.offset);
  46035. }
  46036. // Update the offset in the corresponding DFAE
  46037. //sourceSI.entry.offset = destSI.entry.offset;
  46038. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  46039. }
  46040. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  46041. return true;
  46042. };
  46043. return DynamicFloatArray;
  46044. }());
  46045. BABYLON.DynamicFloatArray = DynamicFloatArray;
  46046. var SortInfo = (function () {
  46047. function SortInfo() {
  46048. this.compareData = this.offset = this.swapedOffset = null;
  46049. }
  46050. return SortInfo;
  46051. }());
  46052. })(BABYLON || (BABYLON = {}));
  46053. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  46054. var BABYLON;
  46055. (function (BABYLON) {
  46056. var Condition = (function () {
  46057. function Condition(actionManager) {
  46058. this._actionManager = actionManager;
  46059. }
  46060. Condition.prototype.isValid = function () {
  46061. return true;
  46062. };
  46063. Condition.prototype._getProperty = function (propertyPath) {
  46064. return this._actionManager._getProperty(propertyPath);
  46065. };
  46066. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  46067. return this._actionManager._getEffectiveTarget(target, propertyPath);
  46068. };
  46069. Condition.prototype.serialize = function () {
  46070. };
  46071. Condition.prototype._serialize = function (serializedCondition) {
  46072. return {
  46073. type: 2,
  46074. children: [],
  46075. name: serializedCondition.name,
  46076. properties: serializedCondition.properties
  46077. };
  46078. };
  46079. return Condition;
  46080. }());
  46081. BABYLON.Condition = Condition;
  46082. var ValueCondition = (function (_super) {
  46083. __extends(ValueCondition, _super);
  46084. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  46085. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  46086. var _this = _super.call(this, actionManager) || this;
  46087. _this.propertyPath = propertyPath;
  46088. _this.value = value;
  46089. _this.operator = operator;
  46090. _this._target = target;
  46091. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  46092. _this._property = _this._getProperty(_this.propertyPath);
  46093. return _this;
  46094. }
  46095. Object.defineProperty(ValueCondition, "IsEqual", {
  46096. get: function () {
  46097. return ValueCondition._IsEqual;
  46098. },
  46099. enumerable: true,
  46100. configurable: true
  46101. });
  46102. Object.defineProperty(ValueCondition, "IsDifferent", {
  46103. get: function () {
  46104. return ValueCondition._IsDifferent;
  46105. },
  46106. enumerable: true,
  46107. configurable: true
  46108. });
  46109. Object.defineProperty(ValueCondition, "IsGreater", {
  46110. get: function () {
  46111. return ValueCondition._IsGreater;
  46112. },
  46113. enumerable: true,
  46114. configurable: true
  46115. });
  46116. Object.defineProperty(ValueCondition, "IsLesser", {
  46117. get: function () {
  46118. return ValueCondition._IsLesser;
  46119. },
  46120. enumerable: true,
  46121. configurable: true
  46122. });
  46123. // Methods
  46124. ValueCondition.prototype.isValid = function () {
  46125. switch (this.operator) {
  46126. case ValueCondition.IsGreater:
  46127. return this._effectiveTarget[this._property] > this.value;
  46128. case ValueCondition.IsLesser:
  46129. return this._effectiveTarget[this._property] < this.value;
  46130. case ValueCondition.IsEqual:
  46131. case ValueCondition.IsDifferent:
  46132. var check;
  46133. if (this.value.equals) {
  46134. check = this.value.equals(this._effectiveTarget[this._property]);
  46135. }
  46136. else {
  46137. check = this.value === this._effectiveTarget[this._property];
  46138. }
  46139. return this.operator === ValueCondition.IsEqual ? check : !check;
  46140. }
  46141. return false;
  46142. };
  46143. ValueCondition.prototype.serialize = function () {
  46144. return this._serialize({
  46145. name: "ValueCondition",
  46146. properties: [
  46147. BABYLON.Action._GetTargetProperty(this._target),
  46148. { name: "propertyPath", value: this.propertyPath },
  46149. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46150. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  46151. ]
  46152. });
  46153. };
  46154. ValueCondition.GetOperatorName = function (operator) {
  46155. switch (operator) {
  46156. case ValueCondition._IsEqual: return "IsEqual";
  46157. case ValueCondition._IsDifferent: return "IsDifferent";
  46158. case ValueCondition._IsGreater: return "IsGreater";
  46159. case ValueCondition._IsLesser: return "IsLesser";
  46160. default: return "";
  46161. }
  46162. };
  46163. // Statics
  46164. ValueCondition._IsEqual = 0;
  46165. ValueCondition._IsDifferent = 1;
  46166. ValueCondition._IsGreater = 2;
  46167. ValueCondition._IsLesser = 3;
  46168. return ValueCondition;
  46169. }(Condition));
  46170. BABYLON.ValueCondition = ValueCondition;
  46171. var PredicateCondition = (function (_super) {
  46172. __extends(PredicateCondition, _super);
  46173. function PredicateCondition(actionManager, predicate) {
  46174. var _this = _super.call(this, actionManager) || this;
  46175. _this.predicate = predicate;
  46176. return _this;
  46177. }
  46178. PredicateCondition.prototype.isValid = function () {
  46179. return this.predicate();
  46180. };
  46181. return PredicateCondition;
  46182. }(Condition));
  46183. BABYLON.PredicateCondition = PredicateCondition;
  46184. var StateCondition = (function (_super) {
  46185. __extends(StateCondition, _super);
  46186. function StateCondition(actionManager, target, value) {
  46187. var _this = _super.call(this, actionManager) || this;
  46188. _this.value = value;
  46189. _this._target = target;
  46190. return _this;
  46191. }
  46192. // Methods
  46193. StateCondition.prototype.isValid = function () {
  46194. return this._target.state === this.value;
  46195. };
  46196. StateCondition.prototype.serialize = function () {
  46197. return this._serialize({
  46198. name: "StateCondition",
  46199. properties: [
  46200. BABYLON.Action._GetTargetProperty(this._target),
  46201. { name: "value", value: this.value }
  46202. ]
  46203. });
  46204. };
  46205. return StateCondition;
  46206. }(Condition));
  46207. BABYLON.StateCondition = StateCondition;
  46208. })(BABYLON || (BABYLON = {}));
  46209. //# sourceMappingURL=babylon.condition.js.map
  46210. var BABYLON;
  46211. (function (BABYLON) {
  46212. var Action = (function () {
  46213. function Action(triggerOptions, condition) {
  46214. this.triggerOptions = triggerOptions;
  46215. if (triggerOptions.parameter) {
  46216. this.trigger = triggerOptions.trigger;
  46217. this._triggerParameter = triggerOptions.parameter;
  46218. }
  46219. else {
  46220. this.trigger = triggerOptions;
  46221. }
  46222. this._nextActiveAction = this;
  46223. this._condition = condition;
  46224. }
  46225. // Methods
  46226. Action.prototype._prepare = function () {
  46227. };
  46228. Action.prototype.getTriggerParameter = function () {
  46229. return this._triggerParameter;
  46230. };
  46231. Action.prototype._executeCurrent = function (evt) {
  46232. if (this._nextActiveAction._condition) {
  46233. var condition = this._nextActiveAction._condition;
  46234. var currentRenderId = this._actionManager.getScene().getRenderId();
  46235. // We cache the current evaluation for the current frame
  46236. if (condition._evaluationId === currentRenderId) {
  46237. if (!condition._currentResult) {
  46238. return;
  46239. }
  46240. }
  46241. else {
  46242. condition._evaluationId = currentRenderId;
  46243. if (!condition.isValid()) {
  46244. condition._currentResult = false;
  46245. return;
  46246. }
  46247. condition._currentResult = true;
  46248. }
  46249. }
  46250. this._nextActiveAction.execute(evt);
  46251. this.skipToNextActiveAction();
  46252. };
  46253. Action.prototype.execute = function (evt) {
  46254. };
  46255. Action.prototype.skipToNextActiveAction = function () {
  46256. if (this._nextActiveAction._child) {
  46257. if (!this._nextActiveAction._child._actionManager) {
  46258. this._nextActiveAction._child._actionManager = this._actionManager;
  46259. }
  46260. this._nextActiveAction = this._nextActiveAction._child;
  46261. }
  46262. else {
  46263. this._nextActiveAction = this;
  46264. }
  46265. };
  46266. Action.prototype.then = function (action) {
  46267. this._child = action;
  46268. action._actionManager = this._actionManager;
  46269. action._prepare();
  46270. return action;
  46271. };
  46272. Action.prototype._getProperty = function (propertyPath) {
  46273. return this._actionManager._getProperty(propertyPath);
  46274. };
  46275. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  46276. return this._actionManager._getEffectiveTarget(target, propertyPath);
  46277. };
  46278. Action.prototype.serialize = function (parent) {
  46279. };
  46280. // Called by BABYLON.Action objects in serialize(...). Internal use
  46281. Action.prototype._serialize = function (serializedAction, parent) {
  46282. var serializationObject = {
  46283. type: 1,
  46284. children: [],
  46285. name: serializedAction.name,
  46286. properties: serializedAction.properties || []
  46287. };
  46288. // Serialize child
  46289. if (this._child) {
  46290. this._child.serialize(serializationObject);
  46291. }
  46292. // Check if "this" has a condition
  46293. if (this._condition) {
  46294. var serializedCondition = this._condition.serialize();
  46295. serializedCondition.children.push(serializationObject);
  46296. if (parent) {
  46297. parent.children.push(serializedCondition);
  46298. }
  46299. return serializedCondition;
  46300. }
  46301. if (parent) {
  46302. parent.children.push(serializationObject);
  46303. }
  46304. return serializationObject;
  46305. };
  46306. Action._SerializeValueAsString = function (value) {
  46307. if (typeof value === "number") {
  46308. return value.toString();
  46309. }
  46310. if (typeof value === "boolean") {
  46311. return value ? "true" : "false";
  46312. }
  46313. if (value instanceof BABYLON.Vector2) {
  46314. return value.x + ", " + value.y;
  46315. }
  46316. if (value instanceof BABYLON.Vector3) {
  46317. return value.x + ", " + value.y + ", " + value.z;
  46318. }
  46319. if (value instanceof BABYLON.Color3) {
  46320. return value.r + ", " + value.g + ", " + value.b;
  46321. }
  46322. if (value instanceof BABYLON.Color4) {
  46323. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  46324. }
  46325. return value; // string
  46326. };
  46327. Action._GetTargetProperty = function (target) {
  46328. return {
  46329. name: "target",
  46330. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  46331. : target instanceof BABYLON.Light ? "LightProperties"
  46332. : target instanceof BABYLON.Camera ? "CameraProperties"
  46333. : "SceneProperties",
  46334. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  46335. };
  46336. };
  46337. return Action;
  46338. }());
  46339. BABYLON.Action = Action;
  46340. })(BABYLON || (BABYLON = {}));
  46341. //# sourceMappingURL=babylon.action.js.map
  46342. var BABYLON;
  46343. (function (BABYLON) {
  46344. /**
  46345. * ActionEvent is the event beint sent when an action is triggered.
  46346. */
  46347. var ActionEvent = (function () {
  46348. /**
  46349. * @param source The mesh or sprite that triggered the action.
  46350. * @param pointerX The X mouse cursor position at the time of the event
  46351. * @param pointerY The Y mouse cursor position at the time of the event
  46352. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  46353. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  46354. */
  46355. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  46356. this.source = source;
  46357. this.pointerX = pointerX;
  46358. this.pointerY = pointerY;
  46359. this.meshUnderPointer = meshUnderPointer;
  46360. this.sourceEvent = sourceEvent;
  46361. this.additionalData = additionalData;
  46362. }
  46363. /**
  46364. * Helper function to auto-create an ActionEvent from a source mesh.
  46365. * @param source The source mesh that triggered the event
  46366. * @param evt {Event} The original (browser) event
  46367. */
  46368. ActionEvent.CreateNew = function (source, evt, additionalData) {
  46369. var scene = source.getScene();
  46370. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  46371. };
  46372. /**
  46373. * Helper function to auto-create an ActionEvent from a source mesh.
  46374. * @param source The source sprite that triggered the event
  46375. * @param scene Scene associated with the sprite
  46376. * @param evt {Event} The original (browser) event
  46377. */
  46378. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  46379. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  46380. };
  46381. /**
  46382. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  46383. * @param scene the scene where the event occurred
  46384. * @param evt {Event} The original (browser) event
  46385. */
  46386. ActionEvent.CreateNewFromScene = function (scene, evt) {
  46387. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  46388. };
  46389. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  46390. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  46391. };
  46392. return ActionEvent;
  46393. }());
  46394. BABYLON.ActionEvent = ActionEvent;
  46395. /**
  46396. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  46397. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  46398. */
  46399. var ActionManager = (function () {
  46400. function ActionManager(scene) {
  46401. // Members
  46402. this.actions = new Array();
  46403. this.hoverCursor = '';
  46404. this._scene = scene;
  46405. scene._actionManagers.push(this);
  46406. }
  46407. Object.defineProperty(ActionManager, "NothingTrigger", {
  46408. get: function () {
  46409. return ActionManager._NothingTrigger;
  46410. },
  46411. enumerable: true,
  46412. configurable: true
  46413. });
  46414. Object.defineProperty(ActionManager, "OnPickTrigger", {
  46415. get: function () {
  46416. return ActionManager._OnPickTrigger;
  46417. },
  46418. enumerable: true,
  46419. configurable: true
  46420. });
  46421. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  46422. get: function () {
  46423. return ActionManager._OnLeftPickTrigger;
  46424. },
  46425. enumerable: true,
  46426. configurable: true
  46427. });
  46428. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  46429. get: function () {
  46430. return ActionManager._OnRightPickTrigger;
  46431. },
  46432. enumerable: true,
  46433. configurable: true
  46434. });
  46435. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  46436. get: function () {
  46437. return ActionManager._OnCenterPickTrigger;
  46438. },
  46439. enumerable: true,
  46440. configurable: true
  46441. });
  46442. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  46443. get: function () {
  46444. return ActionManager._OnPickDownTrigger;
  46445. },
  46446. enumerable: true,
  46447. configurable: true
  46448. });
  46449. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  46450. get: function () {
  46451. return ActionManager._OnDoublePickTrigger;
  46452. },
  46453. enumerable: true,
  46454. configurable: true
  46455. });
  46456. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  46457. get: function () {
  46458. return ActionManager._OnPickUpTrigger;
  46459. },
  46460. enumerable: true,
  46461. configurable: true
  46462. });
  46463. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  46464. /// This trigger will only be raised if you also declared a OnPickDown
  46465. get: function () {
  46466. return ActionManager._OnPickOutTrigger;
  46467. },
  46468. enumerable: true,
  46469. configurable: true
  46470. });
  46471. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  46472. get: function () {
  46473. return ActionManager._OnLongPressTrigger;
  46474. },
  46475. enumerable: true,
  46476. configurable: true
  46477. });
  46478. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  46479. get: function () {
  46480. return ActionManager._OnPointerOverTrigger;
  46481. },
  46482. enumerable: true,
  46483. configurable: true
  46484. });
  46485. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  46486. get: function () {
  46487. return ActionManager._OnPointerOutTrigger;
  46488. },
  46489. enumerable: true,
  46490. configurable: true
  46491. });
  46492. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  46493. get: function () {
  46494. return ActionManager._OnEveryFrameTrigger;
  46495. },
  46496. enumerable: true,
  46497. configurable: true
  46498. });
  46499. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  46500. get: function () {
  46501. return ActionManager._OnIntersectionEnterTrigger;
  46502. },
  46503. enumerable: true,
  46504. configurable: true
  46505. });
  46506. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  46507. get: function () {
  46508. return ActionManager._OnIntersectionExitTrigger;
  46509. },
  46510. enumerable: true,
  46511. configurable: true
  46512. });
  46513. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  46514. get: function () {
  46515. return ActionManager._OnKeyDownTrigger;
  46516. },
  46517. enumerable: true,
  46518. configurable: true
  46519. });
  46520. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  46521. get: function () {
  46522. return ActionManager._OnKeyUpTrigger;
  46523. },
  46524. enumerable: true,
  46525. configurable: true
  46526. });
  46527. // Methods
  46528. ActionManager.prototype.dispose = function () {
  46529. var index = this._scene._actionManagers.indexOf(this);
  46530. for (var i = 0; i < this.actions.length; i++) {
  46531. var action = this.actions[i];
  46532. ActionManager.Triggers[action.trigger]--;
  46533. if (ActionManager.Triggers[action.trigger] === 0) {
  46534. delete ActionManager.Triggers[action.trigger];
  46535. }
  46536. }
  46537. if (index > -1) {
  46538. this._scene._actionManagers.splice(index, 1);
  46539. }
  46540. };
  46541. ActionManager.prototype.getScene = function () {
  46542. return this._scene;
  46543. };
  46544. /**
  46545. * Does this action manager handles actions of any of the given triggers
  46546. * @param {number[]} triggers - the triggers to be tested
  46547. * @return {boolean} whether one (or more) of the triggers is handeled
  46548. */
  46549. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  46550. for (var index = 0; index < this.actions.length; index++) {
  46551. var action = this.actions[index];
  46552. if (triggers.indexOf(action.trigger) > -1) {
  46553. return true;
  46554. }
  46555. }
  46556. return false;
  46557. };
  46558. /**
  46559. * Does this action manager handles actions of a given trigger
  46560. * @param {number} trigger - the trigger to be tested
  46561. * @return {boolean} whether the trigger is handeled
  46562. */
  46563. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  46564. for (var index = 0; index < this.actions.length; index++) {
  46565. var action = this.actions[index];
  46566. if (action.trigger === trigger) {
  46567. return true;
  46568. }
  46569. }
  46570. return false;
  46571. };
  46572. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  46573. /**
  46574. * Does this action manager has pointer triggers
  46575. * @return {boolean} whether or not it has pointer triggers
  46576. */
  46577. get: function () {
  46578. for (var index = 0; index < this.actions.length; index++) {
  46579. var action = this.actions[index];
  46580. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  46581. return true;
  46582. }
  46583. }
  46584. return false;
  46585. },
  46586. enumerable: true,
  46587. configurable: true
  46588. });
  46589. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  46590. /**
  46591. * Does this action manager has pick triggers
  46592. * @return {boolean} whether or not it has pick triggers
  46593. */
  46594. get: function () {
  46595. for (var index = 0; index < this.actions.length; index++) {
  46596. var action = this.actions[index];
  46597. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  46598. return true;
  46599. }
  46600. }
  46601. return false;
  46602. },
  46603. enumerable: true,
  46604. configurable: true
  46605. });
  46606. Object.defineProperty(ActionManager, "HasTriggers", {
  46607. /**
  46608. * Does exist one action manager with at least one trigger
  46609. * @return {boolean} whether or not it exists one action manager with one trigger
  46610. **/
  46611. get: function () {
  46612. for (var t in ActionManager.Triggers) {
  46613. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46614. return true;
  46615. }
  46616. }
  46617. return false;
  46618. },
  46619. enumerable: true,
  46620. configurable: true
  46621. });
  46622. Object.defineProperty(ActionManager, "HasPickTriggers", {
  46623. /**
  46624. * Does exist one action manager with at least one pick trigger
  46625. * @return {boolean} whether or not it exists one action manager with one pick trigger
  46626. **/
  46627. get: function () {
  46628. for (var t in ActionManager.Triggers) {
  46629. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46630. var t_int = parseInt(t);
  46631. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  46632. return true;
  46633. }
  46634. }
  46635. }
  46636. return false;
  46637. },
  46638. enumerable: true,
  46639. configurable: true
  46640. });
  46641. /**
  46642. * Does exist one action manager that handles actions of a given trigger
  46643. * @param {number} trigger - the trigger to be tested
  46644. * @return {boolean} whether the trigger is handeled by at least one action manager
  46645. **/
  46646. ActionManager.HasSpecificTrigger = function (trigger) {
  46647. for (var t in ActionManager.Triggers) {
  46648. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46649. var t_int = parseInt(t);
  46650. if (t_int === trigger) {
  46651. return true;
  46652. }
  46653. }
  46654. }
  46655. return false;
  46656. };
  46657. /**
  46658. * Registers an action to this action manager
  46659. * @param {BABYLON.Action} action - the action to be registered
  46660. * @return {BABYLON.Action} the action amended (prepared) after registration
  46661. */
  46662. ActionManager.prototype.registerAction = function (action) {
  46663. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46664. if (this.getScene().actionManager !== this) {
  46665. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46666. return null;
  46667. }
  46668. }
  46669. this.actions.push(action);
  46670. if (ActionManager.Triggers[action.trigger]) {
  46671. ActionManager.Triggers[action.trigger]++;
  46672. }
  46673. else {
  46674. ActionManager.Triggers[action.trigger] = 1;
  46675. }
  46676. action._actionManager = this;
  46677. action._prepare();
  46678. return action;
  46679. };
  46680. /**
  46681. * Process a specific trigger
  46682. * @param {number} trigger - the trigger to process
  46683. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46684. */
  46685. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46686. for (var index = 0; index < this.actions.length; index++) {
  46687. var action = this.actions[index];
  46688. if (action.trigger === trigger) {
  46689. if (trigger === ActionManager.OnKeyUpTrigger
  46690. || trigger === ActionManager.OnKeyDownTrigger) {
  46691. var parameter = action.getTriggerParameter();
  46692. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46693. if (!parameter.toLowerCase) {
  46694. continue;
  46695. }
  46696. var lowerCase = parameter.toLowerCase();
  46697. if (lowerCase !== evt.sourceEvent.key) {
  46698. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46699. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46700. if (actualkey !== lowerCase) {
  46701. continue;
  46702. }
  46703. }
  46704. }
  46705. }
  46706. action._executeCurrent(evt);
  46707. }
  46708. }
  46709. };
  46710. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46711. var properties = propertyPath.split(".");
  46712. for (var index = 0; index < properties.length - 1; index++) {
  46713. target = target[properties[index]];
  46714. }
  46715. return target;
  46716. };
  46717. ActionManager.prototype._getProperty = function (propertyPath) {
  46718. var properties = propertyPath.split(".");
  46719. return properties[properties.length - 1];
  46720. };
  46721. ActionManager.prototype.serialize = function (name) {
  46722. var root = {
  46723. children: [],
  46724. name: name,
  46725. type: 3,
  46726. properties: [] // Empty for root but required
  46727. };
  46728. for (var i = 0; i < this.actions.length; i++) {
  46729. var triggerObject = {
  46730. type: 0,
  46731. children: [],
  46732. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46733. properties: []
  46734. };
  46735. var triggerOptions = this.actions[i].triggerOptions;
  46736. if (triggerOptions && typeof triggerOptions !== "number") {
  46737. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46738. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46739. }
  46740. else {
  46741. var parameter = {};
  46742. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46743. if (triggerOptions.parameter.mesh) {
  46744. parameter._meshId = triggerOptions.parameter.mesh.id;
  46745. }
  46746. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46747. }
  46748. }
  46749. // Serialize child action, recursively
  46750. this.actions[i].serialize(triggerObject);
  46751. // Add serialized trigger
  46752. root.children.push(triggerObject);
  46753. }
  46754. return root;
  46755. };
  46756. ActionManager.Parse = function (parsedActions, object, scene) {
  46757. var actionManager = new BABYLON.ActionManager(scene);
  46758. if (object === null)
  46759. scene.actionManager = actionManager;
  46760. else
  46761. object.actionManager = actionManager;
  46762. // instanciate a new object
  46763. var instanciate = function (name, params) {
  46764. var newInstance = Object.create(BABYLON[name].prototype);
  46765. newInstance.constructor.apply(newInstance, params);
  46766. return newInstance;
  46767. };
  46768. var parseParameter = function (name, value, target, propertyPath) {
  46769. if (propertyPath === null) {
  46770. // String, boolean or float
  46771. var floatValue = parseFloat(value);
  46772. if (value === "true" || value === "false")
  46773. return value === "true";
  46774. else
  46775. return isNaN(floatValue) ? value : floatValue;
  46776. }
  46777. var effectiveTarget = propertyPath.split(".");
  46778. var values = value.split(",");
  46779. // Get effective Target
  46780. for (var i = 0; i < effectiveTarget.length; i++) {
  46781. target = target[effectiveTarget[i]];
  46782. }
  46783. // Return appropriate value with its type
  46784. if (typeof (target) === "boolean")
  46785. return values[0] === "true";
  46786. if (typeof (target) === "string")
  46787. return values[0];
  46788. // Parameters with multiple values such as Vector3 etc.
  46789. var split = new Array();
  46790. for (var i = 0; i < values.length; i++)
  46791. split.push(parseFloat(values[i]));
  46792. if (target instanceof BABYLON.Vector3)
  46793. return BABYLON.Vector3.FromArray(split);
  46794. if (target instanceof BABYLON.Vector4)
  46795. return BABYLON.Vector4.FromArray(split);
  46796. if (target instanceof BABYLON.Color3)
  46797. return BABYLON.Color3.FromArray(split);
  46798. if (target instanceof BABYLON.Color4)
  46799. return BABYLON.Color4.FromArray(split);
  46800. return parseFloat(values[0]);
  46801. };
  46802. // traverse graph per trigger
  46803. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46804. if (combineArray === void 0) { combineArray = null; }
  46805. if (parsedAction.detached)
  46806. return;
  46807. var parameters = new Array();
  46808. var target = null;
  46809. var propertyPath = null;
  46810. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46811. // Parameters
  46812. if (parsedAction.type === 2)
  46813. parameters.push(actionManager);
  46814. else
  46815. parameters.push(trigger);
  46816. if (combine) {
  46817. var actions = new Array();
  46818. for (var j = 0; j < parsedAction.combine.length; j++) {
  46819. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46820. }
  46821. parameters.push(actions);
  46822. }
  46823. else {
  46824. for (var i = 0; i < parsedAction.properties.length; i++) {
  46825. var value = parsedAction.properties[i].value;
  46826. var name = parsedAction.properties[i].name;
  46827. var targetType = parsedAction.properties[i].targetType;
  46828. if (name === "target")
  46829. if (targetType !== null && targetType === "SceneProperties")
  46830. value = target = scene;
  46831. else
  46832. value = target = scene.getNodeByName(value);
  46833. else if (name === "parent")
  46834. value = scene.getNodeByName(value);
  46835. else if (name === "sound")
  46836. value = scene.getSoundByName(value);
  46837. else if (name !== "propertyPath") {
  46838. if (parsedAction.type === 2 && name === "operator")
  46839. value = BABYLON.ValueCondition[value];
  46840. else
  46841. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46842. }
  46843. else {
  46844. propertyPath = value;
  46845. }
  46846. parameters.push(value);
  46847. }
  46848. }
  46849. if (combineArray === null) {
  46850. parameters.push(condition);
  46851. }
  46852. else {
  46853. parameters.push(null);
  46854. }
  46855. // If interpolate value action
  46856. if (parsedAction.name === "InterpolateValueAction") {
  46857. var param = parameters[parameters.length - 2];
  46858. parameters[parameters.length - 1] = param;
  46859. parameters[parameters.length - 2] = condition;
  46860. }
  46861. // Action or condition(s) and not CombineAction
  46862. var newAction = instanciate(parsedAction.name, parameters);
  46863. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46864. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46865. if (action)
  46866. action.then(nothing);
  46867. else
  46868. actionManager.registerAction(nothing);
  46869. action = nothing;
  46870. }
  46871. if (combineArray === null) {
  46872. if (newAction instanceof BABYLON.Condition) {
  46873. condition = newAction;
  46874. newAction = action;
  46875. }
  46876. else {
  46877. condition = null;
  46878. if (action)
  46879. action.then(newAction);
  46880. else
  46881. actionManager.registerAction(newAction);
  46882. }
  46883. }
  46884. else {
  46885. combineArray.push(newAction);
  46886. }
  46887. for (var i = 0; i < parsedAction.children.length; i++)
  46888. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46889. };
  46890. // triggers
  46891. for (var i = 0; i < parsedActions.children.length; i++) {
  46892. var triggerParams;
  46893. var trigger = parsedActions.children[i];
  46894. if (trigger.properties.length > 0) {
  46895. var param = trigger.properties[0].value;
  46896. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46897. if (value._meshId) {
  46898. value.mesh = scene.getMeshByID(value._meshId);
  46899. }
  46900. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  46901. }
  46902. else
  46903. triggerParams = BABYLON.ActionManager[trigger.name];
  46904. for (var j = 0; j < trigger.children.length; j++) {
  46905. if (!trigger.detached)
  46906. traverse(trigger.children[j], triggerParams, null, null);
  46907. }
  46908. }
  46909. };
  46910. ActionManager.GetTriggerName = function (trigger) {
  46911. switch (trigger) {
  46912. case 0: return "NothingTrigger";
  46913. case 1: return "OnPickTrigger";
  46914. case 2: return "OnLeftPickTrigger";
  46915. case 3: return "OnRightPickTrigger";
  46916. case 4: return "OnCenterPickTrigger";
  46917. case 5: return "OnPickDownTrigger";
  46918. case 6: return "OnPickUpTrigger";
  46919. case 7: return "OnLongPressTrigger";
  46920. case 8: return "OnPointerOverTrigger";
  46921. case 9: return "OnPointerOutTrigger";
  46922. case 10: return "OnEveryFrameTrigger";
  46923. case 11: return "OnIntersectionEnterTrigger";
  46924. case 12: return "OnIntersectionExitTrigger";
  46925. case 13: return "OnKeyDownTrigger";
  46926. case 14: return "OnKeyUpTrigger";
  46927. case 15: return "OnPickOutTrigger";
  46928. default: return "";
  46929. }
  46930. };
  46931. // Statics
  46932. ActionManager._NothingTrigger = 0;
  46933. ActionManager._OnPickTrigger = 1;
  46934. ActionManager._OnLeftPickTrigger = 2;
  46935. ActionManager._OnRightPickTrigger = 3;
  46936. ActionManager._OnCenterPickTrigger = 4;
  46937. ActionManager._OnPickDownTrigger = 5;
  46938. ActionManager._OnDoublePickTrigger = 6;
  46939. ActionManager._OnPickUpTrigger = 7;
  46940. ActionManager._OnLongPressTrigger = 8;
  46941. ActionManager._OnPointerOverTrigger = 9;
  46942. ActionManager._OnPointerOutTrigger = 10;
  46943. ActionManager._OnEveryFrameTrigger = 11;
  46944. ActionManager._OnIntersectionEnterTrigger = 12;
  46945. ActionManager._OnIntersectionExitTrigger = 13;
  46946. ActionManager._OnKeyDownTrigger = 14;
  46947. ActionManager._OnKeyUpTrigger = 15;
  46948. ActionManager._OnPickOutTrigger = 16;
  46949. ActionManager.Triggers = {};
  46950. return ActionManager;
  46951. }());
  46952. BABYLON.ActionManager = ActionManager;
  46953. })(BABYLON || (BABYLON = {}));
  46954. //# sourceMappingURL=babylon.actionManager.js.map
  46955. var BABYLON;
  46956. (function (BABYLON) {
  46957. var InterpolateValueAction = (function (_super) {
  46958. __extends(InterpolateValueAction, _super);
  46959. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46960. if (duration === void 0) { duration = 1000; }
  46961. var _this = _super.call(this, triggerOptions, condition) || this;
  46962. _this.propertyPath = propertyPath;
  46963. _this.value = value;
  46964. _this.duration = duration;
  46965. _this.stopOtherAnimations = stopOtherAnimations;
  46966. _this.onInterpolationDone = onInterpolationDone;
  46967. _this._target = _this._effectiveTarget = target;
  46968. return _this;
  46969. }
  46970. InterpolateValueAction.prototype._prepare = function () {
  46971. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46972. this._property = this._getProperty(this.propertyPath);
  46973. };
  46974. InterpolateValueAction.prototype.execute = function () {
  46975. var scene = this._actionManager.getScene();
  46976. var keys = [
  46977. {
  46978. frame: 0,
  46979. value: this._effectiveTarget[this._property]
  46980. }, {
  46981. frame: 100,
  46982. value: this.value
  46983. }
  46984. ];
  46985. var dataType;
  46986. if (typeof this.value === "number") {
  46987. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46988. }
  46989. else if (this.value instanceof BABYLON.Color3) {
  46990. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46991. }
  46992. else if (this.value instanceof BABYLON.Vector3) {
  46993. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46994. }
  46995. else if (this.value instanceof BABYLON.Matrix) {
  46996. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46997. }
  46998. else if (this.value instanceof BABYLON.Quaternion) {
  46999. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  47000. }
  47001. else {
  47002. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  47003. return;
  47004. }
  47005. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  47006. animation.setKeys(keys);
  47007. if (this.stopOtherAnimations) {
  47008. scene.stopAnimation(this._effectiveTarget);
  47009. }
  47010. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  47011. };
  47012. InterpolateValueAction.prototype.serialize = function (parent) {
  47013. return _super.prototype._serialize.call(this, {
  47014. name: "InterpolateValueAction",
  47015. properties: [
  47016. BABYLON.Action._GetTargetProperty(this._target),
  47017. { name: "propertyPath", value: this.propertyPath },
  47018. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47019. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  47020. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  47021. ]
  47022. }, parent);
  47023. };
  47024. return InterpolateValueAction;
  47025. }(BABYLON.Action));
  47026. BABYLON.InterpolateValueAction = InterpolateValueAction;
  47027. })(BABYLON || (BABYLON = {}));
  47028. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  47029. var BABYLON;
  47030. (function (BABYLON) {
  47031. var SwitchBooleanAction = (function (_super) {
  47032. __extends(SwitchBooleanAction, _super);
  47033. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  47034. var _this = _super.call(this, triggerOptions, condition) || this;
  47035. _this.propertyPath = propertyPath;
  47036. _this._target = _this._effectiveTarget = target;
  47037. return _this;
  47038. }
  47039. SwitchBooleanAction.prototype._prepare = function () {
  47040. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47041. this._property = this._getProperty(this.propertyPath);
  47042. };
  47043. SwitchBooleanAction.prototype.execute = function () {
  47044. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  47045. };
  47046. SwitchBooleanAction.prototype.serialize = function (parent) {
  47047. return _super.prototype._serialize.call(this, {
  47048. name: "SwitchBooleanAction",
  47049. properties: [
  47050. BABYLON.Action._GetTargetProperty(this._target),
  47051. { name: "propertyPath", value: this.propertyPath }
  47052. ]
  47053. }, parent);
  47054. };
  47055. return SwitchBooleanAction;
  47056. }(BABYLON.Action));
  47057. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  47058. var SetStateAction = (function (_super) {
  47059. __extends(SetStateAction, _super);
  47060. function SetStateAction(triggerOptions, target, value, condition) {
  47061. var _this = _super.call(this, triggerOptions, condition) || this;
  47062. _this.value = value;
  47063. _this._target = target;
  47064. return _this;
  47065. }
  47066. SetStateAction.prototype.execute = function () {
  47067. this._target.state = this.value;
  47068. };
  47069. SetStateAction.prototype.serialize = function (parent) {
  47070. return _super.prototype._serialize.call(this, {
  47071. name: "SetStateAction",
  47072. properties: [
  47073. BABYLON.Action._GetTargetProperty(this._target),
  47074. { name: "value", value: this.value }
  47075. ]
  47076. }, parent);
  47077. };
  47078. return SetStateAction;
  47079. }(BABYLON.Action));
  47080. BABYLON.SetStateAction = SetStateAction;
  47081. var SetValueAction = (function (_super) {
  47082. __extends(SetValueAction, _super);
  47083. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  47084. var _this = _super.call(this, triggerOptions, condition) || this;
  47085. _this.propertyPath = propertyPath;
  47086. _this.value = value;
  47087. _this._target = _this._effectiveTarget = target;
  47088. return _this;
  47089. }
  47090. SetValueAction.prototype._prepare = function () {
  47091. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47092. this._property = this._getProperty(this.propertyPath);
  47093. };
  47094. SetValueAction.prototype.execute = function () {
  47095. this._effectiveTarget[this._property] = this.value;
  47096. if (this._target.markAsDirty) {
  47097. this._target.markAsDirty(this._property);
  47098. }
  47099. };
  47100. SetValueAction.prototype.serialize = function (parent) {
  47101. return _super.prototype._serialize.call(this, {
  47102. name: "SetValueAction",
  47103. properties: [
  47104. BABYLON.Action._GetTargetProperty(this._target),
  47105. { name: "propertyPath", value: this.propertyPath },
  47106. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  47107. ]
  47108. }, parent);
  47109. };
  47110. return SetValueAction;
  47111. }(BABYLON.Action));
  47112. BABYLON.SetValueAction = SetValueAction;
  47113. var IncrementValueAction = (function (_super) {
  47114. __extends(IncrementValueAction, _super);
  47115. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  47116. var _this = _super.call(this, triggerOptions, condition) || this;
  47117. _this.propertyPath = propertyPath;
  47118. _this.value = value;
  47119. _this._target = _this._effectiveTarget = target;
  47120. return _this;
  47121. }
  47122. IncrementValueAction.prototype._prepare = function () {
  47123. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47124. this._property = this._getProperty(this.propertyPath);
  47125. if (typeof this._effectiveTarget[this._property] !== "number") {
  47126. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  47127. }
  47128. };
  47129. IncrementValueAction.prototype.execute = function () {
  47130. this._effectiveTarget[this._property] += this.value;
  47131. if (this._target.markAsDirty) {
  47132. this._target.markAsDirty(this._property);
  47133. }
  47134. };
  47135. IncrementValueAction.prototype.serialize = function (parent) {
  47136. return _super.prototype._serialize.call(this, {
  47137. name: "IncrementValueAction",
  47138. properties: [
  47139. BABYLON.Action._GetTargetProperty(this._target),
  47140. { name: "propertyPath", value: this.propertyPath },
  47141. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  47142. ]
  47143. }, parent);
  47144. };
  47145. return IncrementValueAction;
  47146. }(BABYLON.Action));
  47147. BABYLON.IncrementValueAction = IncrementValueAction;
  47148. var PlayAnimationAction = (function (_super) {
  47149. __extends(PlayAnimationAction, _super);
  47150. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  47151. var _this = _super.call(this, triggerOptions, condition) || this;
  47152. _this.from = from;
  47153. _this.to = to;
  47154. _this.loop = loop;
  47155. _this._target = target;
  47156. return _this;
  47157. }
  47158. PlayAnimationAction.prototype._prepare = function () {
  47159. };
  47160. PlayAnimationAction.prototype.execute = function () {
  47161. var scene = this._actionManager.getScene();
  47162. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  47163. };
  47164. PlayAnimationAction.prototype.serialize = function (parent) {
  47165. return _super.prototype._serialize.call(this, {
  47166. name: "PlayAnimationAction",
  47167. properties: [
  47168. BABYLON.Action._GetTargetProperty(this._target),
  47169. { name: "from", value: String(this.from) },
  47170. { name: "to", value: String(this.to) },
  47171. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  47172. ]
  47173. }, parent);
  47174. };
  47175. return PlayAnimationAction;
  47176. }(BABYLON.Action));
  47177. BABYLON.PlayAnimationAction = PlayAnimationAction;
  47178. var StopAnimationAction = (function (_super) {
  47179. __extends(StopAnimationAction, _super);
  47180. function StopAnimationAction(triggerOptions, target, condition) {
  47181. var _this = _super.call(this, triggerOptions, condition) || this;
  47182. _this._target = target;
  47183. return _this;
  47184. }
  47185. StopAnimationAction.prototype._prepare = function () {
  47186. };
  47187. StopAnimationAction.prototype.execute = function () {
  47188. var scene = this._actionManager.getScene();
  47189. scene.stopAnimation(this._target);
  47190. };
  47191. StopAnimationAction.prototype.serialize = function (parent) {
  47192. return _super.prototype._serialize.call(this, {
  47193. name: "StopAnimationAction",
  47194. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  47195. }, parent);
  47196. };
  47197. return StopAnimationAction;
  47198. }(BABYLON.Action));
  47199. BABYLON.StopAnimationAction = StopAnimationAction;
  47200. var DoNothingAction = (function (_super) {
  47201. __extends(DoNothingAction, _super);
  47202. function DoNothingAction(triggerOptions, condition) {
  47203. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  47204. return _super.call(this, triggerOptions, condition) || this;
  47205. }
  47206. DoNothingAction.prototype.execute = function () {
  47207. };
  47208. DoNothingAction.prototype.serialize = function (parent) {
  47209. return _super.prototype._serialize.call(this, {
  47210. name: "DoNothingAction",
  47211. properties: []
  47212. }, parent);
  47213. };
  47214. return DoNothingAction;
  47215. }(BABYLON.Action));
  47216. BABYLON.DoNothingAction = DoNothingAction;
  47217. var CombineAction = (function (_super) {
  47218. __extends(CombineAction, _super);
  47219. function CombineAction(triggerOptions, children, condition) {
  47220. var _this = _super.call(this, triggerOptions, condition) || this;
  47221. _this.children = children;
  47222. return _this;
  47223. }
  47224. CombineAction.prototype._prepare = function () {
  47225. for (var index = 0; index < this.children.length; index++) {
  47226. this.children[index]._actionManager = this._actionManager;
  47227. this.children[index]._prepare();
  47228. }
  47229. };
  47230. CombineAction.prototype.execute = function (evt) {
  47231. for (var index = 0; index < this.children.length; index++) {
  47232. this.children[index].execute(evt);
  47233. }
  47234. };
  47235. CombineAction.prototype.serialize = function (parent) {
  47236. var serializationObject = _super.prototype._serialize.call(this, {
  47237. name: "CombineAction",
  47238. properties: [],
  47239. combine: []
  47240. }, parent);
  47241. for (var i = 0; i < this.children.length; i++) {
  47242. serializationObject.combine.push(this.children[i].serialize(null));
  47243. }
  47244. return serializationObject;
  47245. };
  47246. return CombineAction;
  47247. }(BABYLON.Action));
  47248. BABYLON.CombineAction = CombineAction;
  47249. var ExecuteCodeAction = (function (_super) {
  47250. __extends(ExecuteCodeAction, _super);
  47251. function ExecuteCodeAction(triggerOptions, func, condition) {
  47252. var _this = _super.call(this, triggerOptions, condition) || this;
  47253. _this.func = func;
  47254. return _this;
  47255. }
  47256. ExecuteCodeAction.prototype.execute = function (evt) {
  47257. this.func(evt);
  47258. };
  47259. return ExecuteCodeAction;
  47260. }(BABYLON.Action));
  47261. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  47262. var SetParentAction = (function (_super) {
  47263. __extends(SetParentAction, _super);
  47264. function SetParentAction(triggerOptions, target, parent, condition) {
  47265. var _this = _super.call(this, triggerOptions, condition) || this;
  47266. _this._target = target;
  47267. _this._parent = parent;
  47268. return _this;
  47269. }
  47270. SetParentAction.prototype._prepare = function () {
  47271. };
  47272. SetParentAction.prototype.execute = function () {
  47273. if (this._target.parent === this._parent) {
  47274. return;
  47275. }
  47276. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  47277. invertParentWorldMatrix.invert();
  47278. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  47279. this._target.parent = this._parent;
  47280. };
  47281. SetParentAction.prototype.serialize = function (parent) {
  47282. return _super.prototype._serialize.call(this, {
  47283. name: "SetParentAction",
  47284. properties: [
  47285. BABYLON.Action._GetTargetProperty(this._target),
  47286. BABYLON.Action._GetTargetProperty(this._parent),
  47287. ]
  47288. }, parent);
  47289. };
  47290. return SetParentAction;
  47291. }(BABYLON.Action));
  47292. BABYLON.SetParentAction = SetParentAction;
  47293. var PlaySoundAction = (function (_super) {
  47294. __extends(PlaySoundAction, _super);
  47295. function PlaySoundAction(triggerOptions, sound, condition) {
  47296. var _this = _super.call(this, triggerOptions, condition) || this;
  47297. _this._sound = sound;
  47298. return _this;
  47299. }
  47300. PlaySoundAction.prototype._prepare = function () {
  47301. };
  47302. PlaySoundAction.prototype.execute = function () {
  47303. if (this._sound !== undefined)
  47304. this._sound.play();
  47305. };
  47306. PlaySoundAction.prototype.serialize = function (parent) {
  47307. return _super.prototype._serialize.call(this, {
  47308. name: "PlaySoundAction",
  47309. properties: [{ name: "sound", value: this._sound.name }]
  47310. }, parent);
  47311. };
  47312. return PlaySoundAction;
  47313. }(BABYLON.Action));
  47314. BABYLON.PlaySoundAction = PlaySoundAction;
  47315. var StopSoundAction = (function (_super) {
  47316. __extends(StopSoundAction, _super);
  47317. function StopSoundAction(triggerOptions, sound, condition) {
  47318. var _this = _super.call(this, triggerOptions, condition) || this;
  47319. _this._sound = sound;
  47320. return _this;
  47321. }
  47322. StopSoundAction.prototype._prepare = function () {
  47323. };
  47324. StopSoundAction.prototype.execute = function () {
  47325. if (this._sound !== undefined)
  47326. this._sound.stop();
  47327. };
  47328. StopSoundAction.prototype.serialize = function (parent) {
  47329. return _super.prototype._serialize.call(this, {
  47330. name: "StopSoundAction",
  47331. properties: [{ name: "sound", value: this._sound.name }]
  47332. }, parent);
  47333. };
  47334. return StopSoundAction;
  47335. }(BABYLON.Action));
  47336. BABYLON.StopSoundAction = StopSoundAction;
  47337. })(BABYLON || (BABYLON = {}));
  47338. //# sourceMappingURL=babylon.directActions.js.map
  47339. var BABYLON;
  47340. (function (BABYLON) {
  47341. var Debug;
  47342. (function (Debug) {
  47343. /**
  47344. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  47345. */
  47346. var SkeletonViewer = (function () {
  47347. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  47348. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  47349. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  47350. this.skeleton = skeleton;
  47351. this.mesh = mesh;
  47352. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  47353. this.renderingGroupId = renderingGroupId;
  47354. this.color = BABYLON.Color3.White();
  47355. this._debugLines = [];
  47356. this._isEnabled = false;
  47357. this._scene = scene;
  47358. this.update();
  47359. this._renderFunction = this.update.bind(this);
  47360. }
  47361. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  47362. get: function () {
  47363. return this._isEnabled;
  47364. },
  47365. set: function (value) {
  47366. if (this._isEnabled === value) {
  47367. return;
  47368. }
  47369. this._isEnabled = value;
  47370. if (value) {
  47371. this._scene.registerBeforeRender(this._renderFunction);
  47372. }
  47373. else {
  47374. this._scene.unregisterBeforeRender(this._renderFunction);
  47375. }
  47376. },
  47377. enumerable: true,
  47378. configurable: true
  47379. });
  47380. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  47381. if (x === void 0) { x = 0; }
  47382. if (y === void 0) { y = 0; }
  47383. if (z === void 0) { z = 0; }
  47384. var tmat = BABYLON.Tmp.Matrix[0];
  47385. var parentBone = bone.getParent();
  47386. tmat.copyFrom(bone.getLocalMatrix());
  47387. if (x !== 0 || y !== 0 || z !== 0) {
  47388. var tmat2 = BABYLON.Tmp.Matrix[1];
  47389. BABYLON.Matrix.IdentityToRef(tmat2);
  47390. tmat2.m[12] = x;
  47391. tmat2.m[13] = y;
  47392. tmat2.m[14] = z;
  47393. tmat2.multiplyToRef(tmat, tmat);
  47394. }
  47395. if (parentBone) {
  47396. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  47397. }
  47398. tmat.multiplyToRef(meshMat, tmat);
  47399. position.x = tmat.m[12];
  47400. position.y = tmat.m[13];
  47401. position.z = tmat.m[14];
  47402. };
  47403. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  47404. var len = bones.length;
  47405. var meshPos = this.mesh.position;
  47406. for (var i = 0; i < len; i++) {
  47407. var bone = bones[i];
  47408. var points = this._debugLines[i];
  47409. if (!points) {
  47410. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47411. this._debugLines[i] = points;
  47412. }
  47413. this._getBonePosition(points[0], bone, meshMat);
  47414. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  47415. points[0].subtractInPlace(meshPos);
  47416. points[1].subtractInPlace(meshPos);
  47417. }
  47418. };
  47419. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  47420. var len = bones.length;
  47421. var boneNum = 0;
  47422. var meshPos = this.mesh.position;
  47423. for (var i = len - 1; i >= 0; i--) {
  47424. var childBone = bones[i];
  47425. var parentBone = childBone.getParent();
  47426. if (!parentBone) {
  47427. continue;
  47428. }
  47429. var points = this._debugLines[boneNum];
  47430. if (!points) {
  47431. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47432. this._debugLines[boneNum] = points;
  47433. }
  47434. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  47435. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  47436. points[0].subtractInPlace(meshPos);
  47437. points[1].subtractInPlace(meshPos);
  47438. boneNum++;
  47439. }
  47440. };
  47441. SkeletonViewer.prototype.update = function () {
  47442. if (this.autoUpdateBonesMatrices) {
  47443. this.skeleton.computeAbsoluteTransforms();
  47444. }
  47445. if (this.skeleton.bones[0].length === undefined) {
  47446. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47447. }
  47448. else {
  47449. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47450. }
  47451. if (!this._debugMesh) {
  47452. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  47453. this._debugMesh.renderingGroupId = this.renderingGroupId;
  47454. }
  47455. else {
  47456. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  47457. }
  47458. this._debugMesh.position.copyFrom(this.mesh.position);
  47459. this._debugMesh.color = this.color;
  47460. };
  47461. SkeletonViewer.prototype.dispose = function () {
  47462. if (this._debugMesh) {
  47463. this.isEnabled = false;
  47464. this._debugMesh.dispose();
  47465. this._debugMesh = null;
  47466. }
  47467. };
  47468. return SkeletonViewer;
  47469. }());
  47470. Debug.SkeletonViewer = SkeletonViewer;
  47471. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47472. })(BABYLON || (BABYLON = {}));
  47473. //# sourceMappingURL=babylon.skeletonViewer.js.map
  47474. var BABYLON;
  47475. (function (BABYLON) {
  47476. var Debug;
  47477. (function (Debug) {
  47478. var AxesViewer = (function () {
  47479. function AxesViewer(scene, scaleLines) {
  47480. if (scaleLines === void 0) { scaleLines = 1; }
  47481. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47482. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47483. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47484. this.scaleLines = 1;
  47485. this.scaleLines = scaleLines;
  47486. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  47487. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  47488. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  47489. this._xmesh.renderingGroupId = 2;
  47490. this._ymesh.renderingGroupId = 2;
  47491. this._zmesh.renderingGroupId = 2;
  47492. this._xmesh.material.checkReadyOnlyOnce = true;
  47493. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  47494. this._ymesh.material.checkReadyOnlyOnce = true;
  47495. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  47496. this._zmesh.material.checkReadyOnlyOnce = true;
  47497. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  47498. this.scene = scene;
  47499. }
  47500. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  47501. var scaleLines = this.scaleLines;
  47502. this._xmesh.position.copyFrom(position);
  47503. this._ymesh.position.copyFrom(position);
  47504. this._zmesh.position.copyFrom(position);
  47505. var point2 = this._xline[1];
  47506. point2.x = xaxis.x * scaleLines;
  47507. point2.y = xaxis.y * scaleLines;
  47508. point2.z = xaxis.z * scaleLines;
  47509. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  47510. point2 = this._yline[1];
  47511. point2.x = yaxis.x * scaleLines;
  47512. point2.y = yaxis.y * scaleLines;
  47513. point2.z = yaxis.z * scaleLines;
  47514. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  47515. point2 = this._zline[1];
  47516. point2.x = zaxis.x * scaleLines;
  47517. point2.y = zaxis.y * scaleLines;
  47518. point2.z = zaxis.z * scaleLines;
  47519. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  47520. };
  47521. AxesViewer.prototype.dispose = function () {
  47522. if (this._xmesh) {
  47523. this._xmesh.dispose();
  47524. this._ymesh.dispose();
  47525. this._zmesh.dispose();
  47526. this._xmesh = null;
  47527. this._ymesh = null;
  47528. this._zmesh = null;
  47529. this._xline = null;
  47530. this._yline = null;
  47531. this._zline = null;
  47532. this.scene = null;
  47533. }
  47534. };
  47535. return AxesViewer;
  47536. }());
  47537. Debug.AxesViewer = AxesViewer;
  47538. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47539. })(BABYLON || (BABYLON = {}));
  47540. //# sourceMappingURL=babylon.axesViewer.js.map
  47541. var BABYLON;
  47542. (function (BABYLON) {
  47543. var Debug;
  47544. (function (Debug) {
  47545. var BoneAxesViewer = (function (_super) {
  47546. __extends(BoneAxesViewer, _super);
  47547. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  47548. if (scaleLines === void 0) { scaleLines = 1; }
  47549. var _this = _super.call(this, scene, scaleLines) || this;
  47550. _this.pos = BABYLON.Vector3.Zero();
  47551. _this.xaxis = BABYLON.Vector3.Zero();
  47552. _this.yaxis = BABYLON.Vector3.Zero();
  47553. _this.zaxis = BABYLON.Vector3.Zero();
  47554. _this.mesh = mesh;
  47555. _this.bone = bone;
  47556. return _this;
  47557. }
  47558. BoneAxesViewer.prototype.update = function () {
  47559. var bone = this.bone;
  47560. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  47561. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  47562. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  47563. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  47564. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  47565. };
  47566. BoneAxesViewer.prototype.dispose = function () {
  47567. if (this.pos) {
  47568. this.pos = null;
  47569. this.xaxis = null;
  47570. this.yaxis = null;
  47571. this.zaxis = null;
  47572. this.mesh = null;
  47573. this.bone = null;
  47574. _super.prototype.dispose.call(this);
  47575. }
  47576. };
  47577. return BoneAxesViewer;
  47578. }(Debug.AxesViewer));
  47579. Debug.BoneAxesViewer = BoneAxesViewer;
  47580. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47581. })(BABYLON || (BABYLON = {}));
  47582. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  47583. var BABYLON;
  47584. (function (BABYLON) {
  47585. var RayHelper = (function () {
  47586. function RayHelper(ray) {
  47587. this.ray = ray;
  47588. }
  47589. RayHelper.CreateAndShow = function (ray, scene, color) {
  47590. var helper = new RayHelper(ray);
  47591. helper.show(scene, color);
  47592. return helper;
  47593. };
  47594. RayHelper.prototype.show = function (scene, color) {
  47595. if (!this._renderFunction) {
  47596. var ray = this.ray;
  47597. this._renderFunction = this._render.bind(this);
  47598. this._scene = scene;
  47599. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  47600. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  47601. this._scene.registerBeforeRender(this._renderFunction);
  47602. }
  47603. if (color) {
  47604. this._renderLine.color.copyFrom(color);
  47605. }
  47606. };
  47607. RayHelper.prototype.hide = function () {
  47608. if (this._renderFunction) {
  47609. this._scene.unregisterBeforeRender(this._renderFunction);
  47610. this._scene = null;
  47611. this._renderFunction = null;
  47612. this._renderLine.dispose();
  47613. this._renderLine = null;
  47614. this._renderPoints = null;
  47615. }
  47616. };
  47617. RayHelper.prototype._render = function () {
  47618. var ray = this.ray;
  47619. var point = this._renderPoints[1];
  47620. var len = Math.min(ray.length, 1000000);
  47621. point.copyFrom(ray.direction);
  47622. point.scaleInPlace(len);
  47623. point.addInPlace(ray.origin);
  47624. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  47625. };
  47626. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  47627. this._attachedToMesh = mesh;
  47628. var ray = this.ray;
  47629. if (!ray.direction) {
  47630. ray.direction = BABYLON.Vector3.Zero();
  47631. }
  47632. if (!ray.origin) {
  47633. ray.origin = BABYLON.Vector3.Zero();
  47634. }
  47635. if (length) {
  47636. ray.length = length;
  47637. }
  47638. if (!meshSpaceOrigin) {
  47639. meshSpaceOrigin = BABYLON.Vector3.Zero();
  47640. }
  47641. if (!meshSpaceDirection) {
  47642. // -1 so that this will work with Mesh.lookAt
  47643. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  47644. }
  47645. if (!this._meshSpaceDirection) {
  47646. this._meshSpaceDirection = meshSpaceDirection.clone();
  47647. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  47648. }
  47649. else {
  47650. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  47651. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  47652. }
  47653. if (!this._updateToMeshFunction) {
  47654. this._updateToMeshFunction = this._updateToMesh.bind(this);
  47655. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  47656. }
  47657. this._updateToMesh();
  47658. };
  47659. RayHelper.prototype.detachFromMesh = function () {
  47660. if (this._attachedToMesh) {
  47661. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  47662. this._attachedToMesh = null;
  47663. this._updateToMeshFunction = null;
  47664. }
  47665. };
  47666. RayHelper.prototype._updateToMesh = function () {
  47667. var ray = this.ray;
  47668. if (this._attachedToMesh._isDisposed) {
  47669. this.detachFromMesh();
  47670. return;
  47671. }
  47672. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  47673. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  47674. };
  47675. RayHelper.prototype.dispose = function () {
  47676. this.hide();
  47677. this.detachFromMesh();
  47678. this.ray = null;
  47679. };
  47680. return RayHelper;
  47681. }());
  47682. BABYLON.RayHelper = RayHelper;
  47683. })(BABYLON || (BABYLON = {}));
  47684. //# sourceMappingURL=babylon.rayHelper.js.map
  47685. var BABYLON;
  47686. (function (BABYLON) {
  47687. var DebugLayer = (function () {
  47688. function DebugLayer(scene) {
  47689. this._scene = scene;
  47690. }
  47691. /** Creates the inspector window. */
  47692. DebugLayer.prototype._createInspector = function (config) {
  47693. if (config === void 0) { config = {}; }
  47694. var popup = config.popup || false;
  47695. var initialTab = config.initialTab || 0;
  47696. var parentElement = config.parentElement || null;
  47697. if (!this._inspector) {
  47698. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  47699. } // else nothing to do,; instance is already existing
  47700. };
  47701. DebugLayer.prototype.isVisible = function () {
  47702. if (!this._inspector) {
  47703. return false;
  47704. }
  47705. return true;
  47706. };
  47707. DebugLayer.prototype.hide = function () {
  47708. if (this._inspector) {
  47709. try {
  47710. this._inspector.dispose();
  47711. }
  47712. catch (e) {
  47713. // If the inspector has been removed directly from the inspector tool
  47714. }
  47715. this._inspector = null;
  47716. }
  47717. };
  47718. DebugLayer.prototype.show = function (config) {
  47719. if (config === void 0) { config = {}; }
  47720. if (typeof INSPECTOR == 'undefined') {
  47721. // Load inspector and add it to the DOM
  47722. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  47723. }
  47724. else {
  47725. // Otherwise creates the inspector
  47726. this._createInspector(config);
  47727. }
  47728. };
  47729. // Get protocol used - http or https
  47730. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  47731. return DebugLayer;
  47732. }());
  47733. BABYLON.DebugLayer = DebugLayer;
  47734. })(BABYLON || (BABYLON = {}));
  47735. //# sourceMappingURL=babylon.debugLayer.js.map
  47736. var BABYLON;
  47737. (function (BABYLON) {
  47738. var Debug;
  47739. (function (Debug) {
  47740. var PhysicsViewer = (function () {
  47741. function PhysicsViewer(scene) {
  47742. this._impostors = [];
  47743. this._meshes = [];
  47744. this._numMeshes = 0;
  47745. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47746. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  47747. }
  47748. PhysicsViewer.prototype._updateDebugMeshes = function () {
  47749. var plugin = this._physicsEnginePlugin;
  47750. for (var i = 0; i < this._numMeshes; i++) {
  47751. if (this._impostors[i].isDisposed) {
  47752. this.hideImpostor(this._impostors[i--]);
  47753. }
  47754. else {
  47755. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  47756. }
  47757. }
  47758. };
  47759. PhysicsViewer.prototype.showImpostor = function (impostor) {
  47760. for (var i = 0; i < this._numMeshes; i++) {
  47761. if (this._impostors[i] == impostor) {
  47762. return;
  47763. }
  47764. }
  47765. var debugMesh = this._getDebugMesh(impostor, this._scene);
  47766. if (debugMesh) {
  47767. this._impostors[this._numMeshes] = impostor;
  47768. this._meshes[this._numMeshes] = debugMesh;
  47769. if (this._numMeshes === 0) {
  47770. this._renderFunction = this._updateDebugMeshes.bind(this);
  47771. this._scene.registerBeforeRender(this._renderFunction);
  47772. }
  47773. this._numMeshes++;
  47774. }
  47775. };
  47776. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  47777. var removed = false;
  47778. for (var i = 0; i < this._numMeshes; i++) {
  47779. if (this._impostors[i] == impostor) {
  47780. this._scene.removeMesh(this._meshes[i]);
  47781. this._meshes[i].dispose();
  47782. this._numMeshes--;
  47783. if (this._numMeshes > 0) {
  47784. this._meshes[i] = this._meshes[this._numMeshes];
  47785. this._impostors[i] = this._impostors[this._numMeshes];
  47786. this._meshes[this._numMeshes] = null;
  47787. this._impostors[this._numMeshes] = null;
  47788. }
  47789. else {
  47790. this._meshes[0] = null;
  47791. this._impostors[0] = null;
  47792. }
  47793. removed = true;
  47794. break;
  47795. }
  47796. }
  47797. if (removed && this._numMeshes === 0) {
  47798. this._scene.unregisterBeforeRender(this._renderFunction);
  47799. }
  47800. };
  47801. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  47802. if (!this._debugMaterial) {
  47803. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  47804. this._debugMaterial.wireframe = true;
  47805. }
  47806. return this._debugMaterial;
  47807. };
  47808. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  47809. if (!this._debugBoxMesh) {
  47810. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  47811. this._debugBoxMesh.renderingGroupId = 1;
  47812. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47813. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  47814. scene.removeMesh(this._debugBoxMesh);
  47815. }
  47816. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  47817. };
  47818. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  47819. if (!this._debugSphereMesh) {
  47820. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  47821. this._debugSphereMesh.renderingGroupId = 1;
  47822. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47823. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  47824. scene.removeMesh(this._debugSphereMesh);
  47825. }
  47826. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  47827. };
  47828. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  47829. var body = impostor.physicsBody;
  47830. var shape = body.shapes[0];
  47831. var mesh;
  47832. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  47833. mesh = this._getDebugBoxMesh(scene);
  47834. impostor.getBoxSizeToRef(mesh.scaling);
  47835. }
  47836. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  47837. mesh = this._getDebugSphereMesh(scene);
  47838. var radius = impostor.getRadius();
  47839. mesh.scaling.x = radius * 2;
  47840. mesh.scaling.y = radius * 2;
  47841. mesh.scaling.z = radius * 2;
  47842. }
  47843. return mesh;
  47844. };
  47845. PhysicsViewer.prototype.dispose = function () {
  47846. for (var i = 0; i < this._numMeshes; i++) {
  47847. this.hideImpostor(this._impostors[i]);
  47848. }
  47849. if (this._debugBoxMesh) {
  47850. this._debugBoxMesh.dispose();
  47851. }
  47852. if (this._debugSphereMesh) {
  47853. this._debugSphereMesh.dispose();
  47854. }
  47855. if (this._debugMaterial) {
  47856. this._debugMaterial.dispose();
  47857. }
  47858. this._impostors.length = 0;
  47859. this._scene = null;
  47860. this._physicsEnginePlugin = null;
  47861. };
  47862. return PhysicsViewer;
  47863. }());
  47864. Debug.PhysicsViewer = PhysicsViewer;
  47865. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47866. })(BABYLON || (BABYLON = {}));
  47867. //# sourceMappingURL=babylon.physicsViewer.js.map
  47868. var BABYLON;
  47869. (function (BABYLON) {
  47870. var BoundingBoxRenderer = (function () {
  47871. function BoundingBoxRenderer(scene) {
  47872. this.frontColor = new BABYLON.Color3(1, 1, 1);
  47873. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  47874. this.showBackLines = true;
  47875. this.renderList = new BABYLON.SmartArray(32);
  47876. this._vertexBuffers = {};
  47877. this._scene = scene;
  47878. }
  47879. BoundingBoxRenderer.prototype._prepareRessources = function () {
  47880. if (this._colorShader) {
  47881. return;
  47882. }
  47883. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  47884. attributes: [BABYLON.VertexBuffer.PositionKind],
  47885. uniforms: ["world", "viewProjection", "color"]
  47886. });
  47887. var engine = this._scene.getEngine();
  47888. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  47889. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  47890. this._createIndexBuffer();
  47891. };
  47892. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  47893. var engine = this._scene.getEngine();
  47894. 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]);
  47895. };
  47896. BoundingBoxRenderer.prototype._rebuild = function () {
  47897. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  47898. this._createIndexBuffer();
  47899. };
  47900. BoundingBoxRenderer.prototype.reset = function () {
  47901. this.renderList.reset();
  47902. };
  47903. BoundingBoxRenderer.prototype.render = function () {
  47904. if (this.renderList.length === 0) {
  47905. return;
  47906. }
  47907. this._prepareRessources();
  47908. if (!this._colorShader.isReady()) {
  47909. return;
  47910. }
  47911. var engine = this._scene.getEngine();
  47912. engine.setDepthWrite(false);
  47913. this._colorShader._preBind();
  47914. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  47915. var boundingBox = this.renderList.data[boundingBoxIndex];
  47916. var min = boundingBox.minimum;
  47917. var max = boundingBox.maximum;
  47918. var diff = max.subtract(min);
  47919. var median = min.add(diff.scale(0.5));
  47920. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47921. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47922. .multiply(boundingBox.getWorldMatrix());
  47923. // VBOs
  47924. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47925. if (this.showBackLines) {
  47926. // Back
  47927. engine.setDepthFunctionToGreaterOrEqual();
  47928. this._scene.resetCachedMaterial();
  47929. this._colorShader.setColor4("color", this.backColor.toColor4());
  47930. this._colorShader.bind(worldMatrix);
  47931. // Draw order
  47932. engine.draw(false, 0, 24);
  47933. }
  47934. // Front
  47935. engine.setDepthFunctionToLess();
  47936. this._scene.resetCachedMaterial();
  47937. this._colorShader.setColor4("color", this.frontColor.toColor4());
  47938. this._colorShader.bind(worldMatrix);
  47939. // Draw order
  47940. engine.draw(false, 0, 24);
  47941. }
  47942. this._colorShader.unbind();
  47943. engine.setDepthFunctionToLessOrEqual();
  47944. engine.setDepthWrite(true);
  47945. };
  47946. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  47947. this._prepareRessources();
  47948. if (!this._colorShader.isReady()) {
  47949. return;
  47950. }
  47951. var engine = this._scene.getEngine();
  47952. engine.setDepthWrite(false);
  47953. engine.setColorWrite(false);
  47954. this._colorShader._preBind();
  47955. var boundingBox = mesh._boundingInfo.boundingBox;
  47956. var min = boundingBox.minimum;
  47957. var max = boundingBox.maximum;
  47958. var diff = max.subtract(min);
  47959. var median = min.add(diff.scale(0.5));
  47960. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47961. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47962. .multiply(boundingBox.getWorldMatrix());
  47963. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47964. engine.setDepthFunctionToLess();
  47965. this._scene.resetCachedMaterial();
  47966. this._colorShader.bind(worldMatrix);
  47967. engine.draw(false, 0, 24);
  47968. this._colorShader.unbind();
  47969. engine.setDepthFunctionToLessOrEqual();
  47970. engine.setDepthWrite(true);
  47971. engine.setColorWrite(true);
  47972. };
  47973. BoundingBoxRenderer.prototype.dispose = function () {
  47974. if (!this._colorShader) {
  47975. return;
  47976. }
  47977. this.renderList.dispose();
  47978. this._colorShader.dispose();
  47979. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47980. if (buffer) {
  47981. buffer.dispose();
  47982. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47983. }
  47984. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47985. };
  47986. return BoundingBoxRenderer;
  47987. }());
  47988. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  47989. })(BABYLON || (BABYLON = {}));
  47990. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  47991. var BABYLON;
  47992. (function (BABYLON) {
  47993. var TextureTools = (function () {
  47994. function TextureTools() {
  47995. }
  47996. /**
  47997. * Uses the GPU to create a copy texture rescaled at a given size
  47998. * @param texture Texture to copy from
  47999. * @param width Desired width
  48000. * @param height Desired height
  48001. * @return Generated texture
  48002. */
  48003. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  48004. if (useBilinearMode === void 0) { useBilinearMode = true; }
  48005. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  48006. var scene = texture.getScene();
  48007. var engine = scene.getEngine();
  48008. rtt.wrapU = texture.wrapU;
  48009. rtt.wrapV = texture.wrapV;
  48010. rtt.uOffset = texture.uOffset;
  48011. rtt.vOffset = texture.vOffset;
  48012. rtt.uScale = texture.uScale;
  48013. rtt.vScale = texture.vScale;
  48014. rtt.uAng = texture.uAng;
  48015. rtt.vAng = texture.vAng;
  48016. rtt.wAng = texture.wAng;
  48017. rtt.coordinatesIndex = texture.coordinatesIndex;
  48018. rtt.level = texture.level;
  48019. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  48020. rtt._texture.isReady = false;
  48021. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48022. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48023. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48024. passPostProcess.getEffect().executeWhenCompiled(function () {
  48025. passPostProcess.onApply = function (effect) {
  48026. effect.setTexture("textureSampler", texture);
  48027. };
  48028. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  48029. engine.unBindFramebuffer(rtt.getInternalTexture());
  48030. rtt.disposeFramebufferObjects();
  48031. passPostProcess.dispose();
  48032. rtt._texture.isReady = true;
  48033. });
  48034. return rtt;
  48035. };
  48036. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  48037. if (!scene._environmentBRDFTexture) {
  48038. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48039. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48040. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48041. scene._environmentBRDFTexture = texture;
  48042. }
  48043. return scene._environmentBRDFTexture;
  48044. };
  48045. 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=";
  48046. return TextureTools;
  48047. }());
  48048. BABYLON.TextureTools = TextureTools;
  48049. })(BABYLON || (BABYLON = {}));
  48050. //# sourceMappingURL=babylon.textureTools.js.map
  48051. var BABYLON;
  48052. (function (BABYLON) {
  48053. var SphericalPolynomial = (function () {
  48054. function SphericalPolynomial() {
  48055. this.x = BABYLON.Vector3.Zero();
  48056. this.y = BABYLON.Vector3.Zero();
  48057. this.z = BABYLON.Vector3.Zero();
  48058. this.xx = BABYLON.Vector3.Zero();
  48059. this.yy = BABYLON.Vector3.Zero();
  48060. this.zz = BABYLON.Vector3.Zero();
  48061. this.xy = BABYLON.Vector3.Zero();
  48062. this.yz = BABYLON.Vector3.Zero();
  48063. this.zx = BABYLON.Vector3.Zero();
  48064. }
  48065. SphericalPolynomial.prototype.addAmbient = function (color) {
  48066. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  48067. this.xx = this.xx.add(colorVector);
  48068. this.yy = this.yy.add(colorVector);
  48069. this.zz = this.zz.add(colorVector);
  48070. };
  48071. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  48072. var result = new SphericalPolynomial();
  48073. result.x = harmonics.L11.scale(1.02333);
  48074. result.y = harmonics.L1_1.scale(1.02333);
  48075. result.z = harmonics.L10.scale(1.02333);
  48076. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  48077. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  48078. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  48079. result.yz = harmonics.L2_1.scale(0.858086);
  48080. result.zx = harmonics.L21.scale(0.858086);
  48081. result.xy = harmonics.L2_2.scale(0.858086);
  48082. result.scale(1.0 / Math.PI);
  48083. return result;
  48084. };
  48085. SphericalPolynomial.prototype.scale = function (scale) {
  48086. this.x = this.x.scale(scale);
  48087. this.y = this.y.scale(scale);
  48088. this.z = this.z.scale(scale);
  48089. this.xx = this.xx.scale(scale);
  48090. this.yy = this.yy.scale(scale);
  48091. this.zz = this.zz.scale(scale);
  48092. this.yz = this.yz.scale(scale);
  48093. this.zx = this.zx.scale(scale);
  48094. this.xy = this.xy.scale(scale);
  48095. };
  48096. return SphericalPolynomial;
  48097. }());
  48098. BABYLON.SphericalPolynomial = SphericalPolynomial;
  48099. var SphericalHarmonics = (function () {
  48100. function SphericalHarmonics() {
  48101. this.L00 = BABYLON.Vector3.Zero();
  48102. this.L1_1 = BABYLON.Vector3.Zero();
  48103. this.L10 = BABYLON.Vector3.Zero();
  48104. this.L11 = BABYLON.Vector3.Zero();
  48105. this.L2_2 = BABYLON.Vector3.Zero();
  48106. this.L2_1 = BABYLON.Vector3.Zero();
  48107. this.L20 = BABYLON.Vector3.Zero();
  48108. this.L21 = BABYLON.Vector3.Zero();
  48109. this.L22 = BABYLON.Vector3.Zero();
  48110. }
  48111. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  48112. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  48113. var c = colorVector.scale(deltaSolidAngle);
  48114. this.L00 = this.L00.add(c.scale(0.282095));
  48115. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  48116. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  48117. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  48118. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  48119. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  48120. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  48121. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  48122. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  48123. };
  48124. SphericalHarmonics.prototype.scale = function (scale) {
  48125. this.L00 = this.L00.scale(scale);
  48126. this.L1_1 = this.L1_1.scale(scale);
  48127. this.L10 = this.L10.scale(scale);
  48128. this.L11 = this.L11.scale(scale);
  48129. this.L2_2 = this.L2_2.scale(scale);
  48130. this.L2_1 = this.L2_1.scale(scale);
  48131. this.L20 = this.L20.scale(scale);
  48132. this.L21 = this.L21.scale(scale);
  48133. this.L22 = this.L22.scale(scale);
  48134. };
  48135. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  48136. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  48137. //
  48138. // E_lm = A_l * L_lm
  48139. //
  48140. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  48141. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  48142. // the scaling factors are given in equation 9.
  48143. // Constant (Band 0)
  48144. this.L00 = this.L00.scale(3.141593);
  48145. // Linear (Band 1)
  48146. this.L1_1 = this.L1_1.scale(2.094395);
  48147. this.L10 = this.L10.scale(2.094395);
  48148. this.L11 = this.L11.scale(2.094395);
  48149. // Quadratic (Band 2)
  48150. this.L2_2 = this.L2_2.scale(0.785398);
  48151. this.L2_1 = this.L2_1.scale(0.785398);
  48152. this.L20 = this.L20.scale(0.785398);
  48153. this.L21 = this.L21.scale(0.785398);
  48154. this.L22 = this.L22.scale(0.785398);
  48155. };
  48156. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  48157. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  48158. // L = (1/pi) * E * rho
  48159. //
  48160. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  48161. this.scale(1.0 / Math.PI);
  48162. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  48163. // (The pixel shader must apply albedo after texture fetches, etc).
  48164. };
  48165. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  48166. var result = new SphericalHarmonics();
  48167. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  48168. result.L1_1 = polynomial.y.scale(0.977204);
  48169. result.L10 = polynomial.z.scale(0.977204);
  48170. result.L11 = polynomial.x.scale(0.977204);
  48171. result.L2_2 = polynomial.xy.scale(1.16538);
  48172. result.L2_1 = polynomial.yz.scale(1.16538);
  48173. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  48174. result.L21 = polynomial.zx.scale(1.16538);
  48175. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  48176. result.scale(Math.PI);
  48177. return result;
  48178. };
  48179. return SphericalHarmonics;
  48180. }());
  48181. BABYLON.SphericalHarmonics = SphericalHarmonics;
  48182. })(BABYLON || (BABYLON = {}));
  48183. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  48184. var BABYLON;
  48185. (function (BABYLON) {
  48186. var Internals;
  48187. (function (Internals) {
  48188. var FileFaceOrientation = (function () {
  48189. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  48190. this.name = name;
  48191. this.worldAxisForNormal = worldAxisForNormal;
  48192. this.worldAxisForFileX = worldAxisForFileX;
  48193. this.worldAxisForFileY = worldAxisForFileY;
  48194. }
  48195. return FileFaceOrientation;
  48196. }());
  48197. ;
  48198. /**
  48199. * Helper class dealing with the extraction of spherical polynomial dataArray
  48200. * from a cube map.
  48201. */
  48202. var CubeMapToSphericalPolynomialTools = (function () {
  48203. function CubeMapToSphericalPolynomialTools() {
  48204. }
  48205. /**
  48206. * Converts a texture to the according Spherical Polynomial data.
  48207. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48208. *
  48209. * @param texture The texture to extract the information from.
  48210. * @return The Spherical Polynomial data.
  48211. */
  48212. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  48213. if (!texture.isCube) {
  48214. // Only supports cube Textures currently.
  48215. return null;
  48216. }
  48217. var size = texture.getSize().width;
  48218. var right = texture.readPixels(0);
  48219. var left = texture.readPixels(1);
  48220. var up;
  48221. var down;
  48222. if (texture.isRenderTarget) {
  48223. up = texture.readPixels(3);
  48224. down = texture.readPixels(2);
  48225. }
  48226. else {
  48227. up = texture.readPixels(2);
  48228. down = texture.readPixels(3);
  48229. }
  48230. var front = texture.readPixels(4);
  48231. var back = texture.readPixels(5);
  48232. var gammaSpace = texture.gammaSpace;
  48233. // Always read as RGBA.
  48234. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  48235. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  48236. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48237. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  48238. }
  48239. var cubeInfo = {
  48240. size: size,
  48241. right: right,
  48242. left: left,
  48243. up: up,
  48244. down: down,
  48245. front: front,
  48246. back: back,
  48247. format: format,
  48248. type: type,
  48249. gammaSpace: gammaSpace,
  48250. };
  48251. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  48252. };
  48253. /**
  48254. * Converts a cubemap to the according Spherical Polynomial data.
  48255. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48256. *
  48257. * @param cubeInfo The Cube map to extract the information from.
  48258. * @return The Spherical Polynomial data.
  48259. */
  48260. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  48261. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  48262. var totalSolidAngle = 0.0;
  48263. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  48264. var du = 2.0 / cubeInfo.size;
  48265. var dv = du;
  48266. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  48267. var minUV = du * 0.5 - 1.0;
  48268. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48269. var fileFace = this.FileFaces[faceIndex];
  48270. var dataArray = cubeInfo[fileFace.name];
  48271. var v = minUV;
  48272. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  48273. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  48274. // Because SP is still linear, so summation is fine in that basis.
  48275. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  48276. for (var y = 0; y < cubeInfo.size; y++) {
  48277. var u = minUV;
  48278. for (var x = 0; x < cubeInfo.size; x++) {
  48279. // World direction (not normalised)
  48280. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  48281. worldDirection.normalize();
  48282. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  48283. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  48284. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  48285. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  48286. // Handle Integer types.
  48287. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48288. r /= 255;
  48289. g /= 255;
  48290. b /= 255;
  48291. }
  48292. // Handle Gamma space textures.
  48293. if (cubeInfo.gammaSpace) {
  48294. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  48295. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  48296. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  48297. }
  48298. var color = new BABYLON.Color3(r, g, b);
  48299. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48300. totalSolidAngle += deltaSolidAngle;
  48301. u += du;
  48302. }
  48303. v += dv;
  48304. }
  48305. }
  48306. // Solid angle for entire sphere is 4*pi
  48307. var sphereSolidAngle = 4.0 * Math.PI;
  48308. // Adjust the solid angle to allow for how many faces we processed.
  48309. var facesProcessed = 6.0;
  48310. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  48311. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  48312. // This is needed because the numerical integration over the cube uses a
  48313. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  48314. // and also to compensate for accumulative error due to float precision in the summation.
  48315. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  48316. sphericalHarmonics.scale(correctionFactor);
  48317. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  48318. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  48319. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  48320. };
  48321. CubeMapToSphericalPolynomialTools.FileFaces = [
  48322. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  48323. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  48324. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  48325. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  48326. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  48327. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  48328. ];
  48329. return CubeMapToSphericalPolynomialTools;
  48330. }());
  48331. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  48332. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48333. })(BABYLON || (BABYLON = {}));
  48334. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  48335. var BABYLON;
  48336. (function (BABYLON) {
  48337. var Internals;
  48338. (function (Internals) {
  48339. /**
  48340. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  48341. */
  48342. var PanoramaToCubeMapTools = (function () {
  48343. function PanoramaToCubeMapTools() {
  48344. }
  48345. /**
  48346. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  48347. *
  48348. * @param float32Array The source data.
  48349. * @param inputWidth The width of the input panorama.
  48350. * @param inputhHeight The height of the input panorama.
  48351. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  48352. * @return The cubemap data
  48353. */
  48354. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  48355. if (!float32Array) {
  48356. throw "ConvertPanoramaToCubemap: input cannot be null";
  48357. }
  48358. if (float32Array.length != inputWidth * inputHeight * 3) {
  48359. throw "ConvertPanoramaToCubemap: input size is wrong";
  48360. }
  48361. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  48362. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  48363. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  48364. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  48365. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  48366. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  48367. return {
  48368. front: textureFront,
  48369. back: textureBack,
  48370. left: textureLeft,
  48371. right: textureRight,
  48372. up: textureUp,
  48373. down: textureDown,
  48374. size: size,
  48375. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  48376. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  48377. gammaSpace: false,
  48378. };
  48379. };
  48380. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  48381. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  48382. var textureArray = new Float32Array(buffer);
  48383. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  48384. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  48385. var dy = 1 / texSize;
  48386. var fy = 0;
  48387. for (var y = 0; y < texSize; y++) {
  48388. var xv1 = faceData[0];
  48389. var xv2 = faceData[2];
  48390. for (var x = 0; x < texSize; x++) {
  48391. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  48392. v.normalize();
  48393. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  48394. // 3 channels per pixels
  48395. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  48396. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  48397. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  48398. xv1 = xv1.add(rotDX1);
  48399. xv2 = xv2.add(rotDX2);
  48400. }
  48401. fy += dy;
  48402. }
  48403. return textureArray;
  48404. };
  48405. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  48406. var theta = Math.atan2(vDir.z, vDir.x);
  48407. var phi = Math.acos(vDir.y);
  48408. while (theta < -Math.PI)
  48409. theta += 2 * Math.PI;
  48410. while (theta > Math.PI)
  48411. theta -= 2 * Math.PI;
  48412. var dx = theta / Math.PI;
  48413. var dy = phi / Math.PI;
  48414. // recenter.
  48415. dx = dx * 0.5 + 0.5;
  48416. var px = Math.round(dx * inputWidth);
  48417. if (px < 0)
  48418. px = 0;
  48419. else if (px >= inputWidth)
  48420. px = inputWidth - 1;
  48421. var py = Math.round(dy * inputHeight);
  48422. if (py < 0)
  48423. py = 0;
  48424. else if (py >= inputHeight)
  48425. py = inputHeight - 1;
  48426. var inputY = (inputHeight - py - 1);
  48427. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  48428. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  48429. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  48430. return {
  48431. r: r,
  48432. g: g,
  48433. b: b
  48434. };
  48435. };
  48436. PanoramaToCubeMapTools.FACE_FRONT = [
  48437. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48438. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48439. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48440. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48441. ];
  48442. PanoramaToCubeMapTools.FACE_BACK = [
  48443. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48444. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48445. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48446. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48447. ];
  48448. PanoramaToCubeMapTools.FACE_RIGHT = [
  48449. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48450. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48451. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48452. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48453. ];
  48454. PanoramaToCubeMapTools.FACE_LEFT = [
  48455. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48456. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48457. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48458. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48459. ];
  48460. PanoramaToCubeMapTools.FACE_DOWN = [
  48461. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48462. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48463. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48464. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48465. ];
  48466. PanoramaToCubeMapTools.FACE_UP = [
  48467. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48468. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48469. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48470. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48471. ];
  48472. return PanoramaToCubeMapTools;
  48473. }());
  48474. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48475. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48476. })(BABYLON || (BABYLON = {}));
  48477. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  48478. var BABYLON;
  48479. (function (BABYLON) {
  48480. var Internals;
  48481. (function (Internals) {
  48482. ;
  48483. /**
  48484. * This groups tools to convert HDR texture to native colors array.
  48485. */
  48486. var HDRTools = (function () {
  48487. function HDRTools() {
  48488. }
  48489. HDRTools.Ldexp = function (mantissa, exponent) {
  48490. if (exponent > 1023) {
  48491. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48492. }
  48493. if (exponent < -1074) {
  48494. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48495. }
  48496. return mantissa * Math.pow(2, exponent);
  48497. };
  48498. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48499. if (exponent > 0) {
  48500. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48501. float32array[index + 0] = red * exponent;
  48502. float32array[index + 1] = green * exponent;
  48503. float32array[index + 2] = blue * exponent;
  48504. }
  48505. else {
  48506. float32array[index + 0] = 0;
  48507. float32array[index + 1] = 0;
  48508. float32array[index + 2] = 0;
  48509. }
  48510. };
  48511. HDRTools.readStringLine = function (uint8array, startIndex) {
  48512. var line = "";
  48513. var character = "";
  48514. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48515. character = String.fromCharCode(uint8array[i]);
  48516. if (character == "\n") {
  48517. break;
  48518. }
  48519. line += character;
  48520. }
  48521. return line;
  48522. };
  48523. /**
  48524. * Reads header information from an RGBE texture stored in a native array.
  48525. * More information on this format are available here:
  48526. * https://en.wikipedia.org/wiki/RGBE_image_format
  48527. *
  48528. * @param uint8array The binary file stored in native array.
  48529. * @return The header information.
  48530. */
  48531. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48532. var height = 0;
  48533. var width = 0;
  48534. var line = this.readStringLine(uint8array, 0);
  48535. if (line[0] != '#' || line[1] != '?') {
  48536. throw "Bad HDR Format.";
  48537. }
  48538. var endOfHeader = false;
  48539. var findFormat = false;
  48540. var lineIndex = 0;
  48541. do {
  48542. lineIndex += (line.length + 1);
  48543. line = this.readStringLine(uint8array, lineIndex);
  48544. if (line == "FORMAT=32-bit_rle_rgbe") {
  48545. findFormat = true;
  48546. }
  48547. else if (line.length == 0) {
  48548. endOfHeader = true;
  48549. }
  48550. } while (!endOfHeader);
  48551. if (!findFormat) {
  48552. throw "HDR Bad header format, unsupported FORMAT";
  48553. }
  48554. lineIndex += (line.length + 1);
  48555. line = this.readStringLine(uint8array, lineIndex);
  48556. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48557. var match = sizeRegexp.exec(line);
  48558. // TODO. Support +Y and -X if needed.
  48559. if (match.length < 3) {
  48560. throw "HDR Bad header format, no size";
  48561. }
  48562. width = parseInt(match[2]);
  48563. height = parseInt(match[1]);
  48564. if (width < 8 || width > 0x7fff) {
  48565. throw "HDR Bad header format, unsupported size";
  48566. }
  48567. lineIndex += (line.length + 1);
  48568. return {
  48569. height: height,
  48570. width: width,
  48571. dataPosition: lineIndex
  48572. };
  48573. };
  48574. /**
  48575. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48576. * This RGBE texture needs to store the information as a panorama.
  48577. *
  48578. * More information on this format are available here:
  48579. * https://en.wikipedia.org/wiki/RGBE_image_format
  48580. *
  48581. * @param buffer The binary file stored in an array buffer.
  48582. * @param size The expected size of the extracted cubemap.
  48583. * @return The Cube Map information.
  48584. */
  48585. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48586. var uint8array = new Uint8Array(buffer);
  48587. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48588. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48589. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48590. return cubeMapData;
  48591. };
  48592. /**
  48593. * Returns the pixels data extracted from an RGBE texture.
  48594. * This pixels will be stored left to right up to down in the R G B order in one array.
  48595. *
  48596. * More information on this format are available here:
  48597. * https://en.wikipedia.org/wiki/RGBE_image_format
  48598. *
  48599. * @param uint8array The binary file stored in an array buffer.
  48600. * @param hdrInfo The header information of the file.
  48601. * @return The pixels data in RGB right to left up to down order.
  48602. */
  48603. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48604. // Keep for multi format supports.
  48605. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48606. };
  48607. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48608. var num_scanlines = hdrInfo.height;
  48609. var scanline_width = hdrInfo.width;
  48610. var a, b, c, d, count;
  48611. var dataIndex = hdrInfo.dataPosition;
  48612. var index = 0, endIndex = 0, i = 0;
  48613. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48614. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48615. // 3 channels of 4 bytes per pixel in float.
  48616. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48617. var resultArray = new Float32Array(resultBuffer);
  48618. // read in each successive scanline
  48619. while (num_scanlines > 0) {
  48620. a = uint8array[dataIndex++];
  48621. b = uint8array[dataIndex++];
  48622. c = uint8array[dataIndex++];
  48623. d = uint8array[dataIndex++];
  48624. if (a != 2 || b != 2 || (c & 0x80)) {
  48625. // this file is not run length encoded
  48626. throw "HDR Bad header format, not RLE";
  48627. }
  48628. if (((c << 8) | d) != scanline_width) {
  48629. throw "HDR Bad header format, wrong scan line width";
  48630. }
  48631. index = 0;
  48632. // read each of the four channels for the scanline into the buffer
  48633. for (i = 0; i < 4; i++) {
  48634. endIndex = (i + 1) * scanline_width;
  48635. while (index < endIndex) {
  48636. a = uint8array[dataIndex++];
  48637. b = uint8array[dataIndex++];
  48638. if (a > 128) {
  48639. // a run of the same value
  48640. count = a - 128;
  48641. if ((count == 0) || (count > endIndex - index)) {
  48642. throw "HDR Bad Format, bad scanline data (run)";
  48643. }
  48644. while (count-- > 0) {
  48645. scanLineArray[index++] = b;
  48646. }
  48647. }
  48648. else {
  48649. // a non-run
  48650. count = a;
  48651. if ((count == 0) || (count > endIndex - index)) {
  48652. throw "HDR Bad Format, bad scanline data (non-run)";
  48653. }
  48654. scanLineArray[index++] = b;
  48655. if (--count > 0) {
  48656. for (var j = 0; j < count; j++) {
  48657. scanLineArray[index++] = uint8array[dataIndex++];
  48658. }
  48659. }
  48660. }
  48661. }
  48662. }
  48663. // now convert data from buffer into floats
  48664. for (i = 0; i < scanline_width; i++) {
  48665. a = scanLineArray[i];
  48666. b = scanLineArray[i + scanline_width];
  48667. c = scanLineArray[i + 2 * scanline_width];
  48668. d = scanLineArray[i + 3 * scanline_width];
  48669. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  48670. }
  48671. num_scanlines--;
  48672. }
  48673. return resultArray;
  48674. };
  48675. return HDRTools;
  48676. }());
  48677. Internals.HDRTools = HDRTools;
  48678. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48679. })(BABYLON || (BABYLON = {}));
  48680. //# sourceMappingURL=babylon.hdr.js.map
  48681. var BABYLON;
  48682. (function (BABYLON) {
  48683. /**
  48684. * This represents a texture coming from an HDR input.
  48685. *
  48686. * The only supported format is currently panorama picture stored in RGBE format.
  48687. * Example of such files can be found on HDRLib: http://hdrlib.com/
  48688. */
  48689. var HDRCubeTexture = (function (_super) {
  48690. __extends(HDRCubeTexture, _super);
  48691. /**
  48692. * Instantiates an HDRTexture from the following parameters.
  48693. *
  48694. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  48695. * @param scene The scene the texture will be used in
  48696. * @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.
  48697. * @param noMipmap Forces to not generate the mipmap if true
  48698. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  48699. * @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)
  48700. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  48701. */
  48702. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  48703. if (noMipmap === void 0) { noMipmap = false; }
  48704. if (generateHarmonics === void 0) { generateHarmonics = true; }
  48705. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  48706. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  48707. if (onLoad === void 0) { onLoad = null; }
  48708. if (onError === void 0) { onError = null; }
  48709. var _this = _super.call(this, scene) || this;
  48710. _this._useInGammaSpace = false;
  48711. _this._generateHarmonics = true;
  48712. _this._isBABYLONPreprocessed = false;
  48713. _this._onLoad = null;
  48714. _this._onError = null;
  48715. /**
  48716. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  48717. */
  48718. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  48719. /**
  48720. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  48721. * This is usefull at run time to apply the good shader.
  48722. */
  48723. _this.isPMREM = false;
  48724. _this._isBlocking = true;
  48725. if (!url) {
  48726. return _this;
  48727. }
  48728. _this.name = url;
  48729. _this.url = url;
  48730. _this.hasAlpha = false;
  48731. _this.isCube = true;
  48732. _this._textureMatrix = BABYLON.Matrix.Identity();
  48733. _this._onLoad = onLoad;
  48734. _this._onError = onError;
  48735. _this.gammaSpace = false;
  48736. if (size) {
  48737. _this._isBABYLONPreprocessed = false;
  48738. _this._noMipmap = noMipmap;
  48739. _this._size = size;
  48740. _this._useInGammaSpace = useInGammaSpace;
  48741. _this._usePMREMGenerator = usePMREMGenerator &&
  48742. scene.getEngine().getCaps().textureLOD &&
  48743. _this.getScene().getEngine().getCaps().textureFloat &&
  48744. !_this._useInGammaSpace;
  48745. }
  48746. else {
  48747. _this._isBABYLONPreprocessed = true;
  48748. _this._noMipmap = false;
  48749. _this._useInGammaSpace = false;
  48750. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  48751. _this.getScene().getEngine().getCaps().textureFloat &&
  48752. !_this._useInGammaSpace;
  48753. }
  48754. _this.isPMREM = _this._usePMREMGenerator;
  48755. _this._texture = _this._getFromCache(url, _this._noMipmap);
  48756. if (!_this._texture) {
  48757. if (!scene.useDelayedTextureLoading) {
  48758. _this.loadTexture();
  48759. }
  48760. else {
  48761. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  48762. }
  48763. }
  48764. return _this;
  48765. }
  48766. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  48767. /**
  48768. * Gets wether or not the texture is blocking during loading.
  48769. */
  48770. get: function () {
  48771. return this._isBlocking;
  48772. },
  48773. /**
  48774. * Sets wether or not the texture is blocking during loading.
  48775. */
  48776. set: function (value) {
  48777. this._isBlocking = value;
  48778. },
  48779. enumerable: true,
  48780. configurable: true
  48781. });
  48782. /**
  48783. * Occurs when the file is a preprocessed .babylon.hdr file.
  48784. */
  48785. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  48786. var _this = this;
  48787. var mipLevels = 0;
  48788. var floatArrayView = null;
  48789. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  48790. var mips = [];
  48791. var startIndex = 30;
  48792. for (var level = 0; level < mipLevels; level++) {
  48793. mips.push([]);
  48794. // Fill each pixel of the mip level.
  48795. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  48796. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48797. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  48798. mips[level].push(faceData);
  48799. startIndex += faceSize;
  48800. }
  48801. }
  48802. return mips;
  48803. } : null;
  48804. var callback = function (buffer) {
  48805. // Create Native Array Views
  48806. var intArrayView = new Int32Array(buffer);
  48807. floatArrayView = new Float32Array(buffer);
  48808. // Fill header.
  48809. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  48810. _this._size = intArrayView[1]; // CubeMap max mip face size.
  48811. // Update Texture Information.
  48812. _this._texture.updateSize(_this._size, _this._size);
  48813. // Fill polynomial information.
  48814. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  48815. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  48816. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  48817. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  48818. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  48819. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  48820. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  48821. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  48822. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  48823. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  48824. _this.sphericalPolynomial = sphericalPolynomial;
  48825. // Fill pixel data.
  48826. mipLevels = intArrayView[29]; // Number of mip levels.
  48827. var startIndex = 30;
  48828. var data = [];
  48829. var faceSize = Math.pow(_this._size, 2) * 3;
  48830. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48831. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  48832. startIndex += faceSize;
  48833. }
  48834. var results = [];
  48835. var byteArray = null;
  48836. // Push each faces.
  48837. for (var k = 0; k < 6; k++) {
  48838. var dataFace = null;
  48839. // To be deprecated.
  48840. if (version === 1) {
  48841. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  48842. dataFace = data[j];
  48843. }
  48844. // If special cases.
  48845. if (!mipmapGenerator) {
  48846. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48847. // 3 channels of 1 bytes per pixel in bytes.
  48848. var byteBuffer = new ArrayBuffer(faceSize);
  48849. byteArray = new Uint8Array(byteBuffer);
  48850. }
  48851. for (var i = 0; i < _this._size * _this._size; i++) {
  48852. // Put in gamma space if requested.
  48853. if (_this._useInGammaSpace) {
  48854. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48855. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48856. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48857. }
  48858. // Convert to int texture for fallback.
  48859. if (byteArray) {
  48860. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48861. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48862. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48863. // May use luminance instead if the result is not accurate.
  48864. var max = Math.max(Math.max(r, g), b);
  48865. if (max > 255) {
  48866. var scale = 255 / max;
  48867. r *= scale;
  48868. g *= scale;
  48869. b *= scale;
  48870. }
  48871. byteArray[(i * 3) + 0] = r;
  48872. byteArray[(i * 3) + 1] = g;
  48873. byteArray[(i * 3) + 2] = b;
  48874. }
  48875. }
  48876. }
  48877. // Fill the array accordingly.
  48878. if (byteArray) {
  48879. results.push(byteArray);
  48880. }
  48881. else {
  48882. results.push(dataFace);
  48883. }
  48884. }
  48885. return results;
  48886. };
  48887. 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);
  48888. };
  48889. /**
  48890. * Occurs when the file is raw .hdr file.
  48891. */
  48892. HDRCubeTexture.prototype.loadHDRTexture = function () {
  48893. var _this = this;
  48894. var callback = function (buffer) {
  48895. // Extract the raw linear data.
  48896. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  48897. // Generate harmonics if needed.
  48898. if (_this._generateHarmonics) {
  48899. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  48900. _this.sphericalPolynomial = sphericalPolynomial;
  48901. }
  48902. var results = [];
  48903. var byteArray = null;
  48904. // Push each faces.
  48905. for (var j = 0; j < 6; j++) {
  48906. // Create uintarray fallback.
  48907. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48908. // 3 channels of 1 bytes per pixel in bytes.
  48909. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  48910. byteArray = new Uint8Array(byteBuffer);
  48911. }
  48912. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  48913. // If special cases.
  48914. if (_this._useInGammaSpace || byteArray) {
  48915. for (var i = 0; i < _this._size * _this._size; i++) {
  48916. // Put in gamma space if requested.
  48917. if (_this._useInGammaSpace) {
  48918. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48919. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48920. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48921. }
  48922. // Convert to int texture for fallback.
  48923. if (byteArray) {
  48924. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48925. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48926. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48927. // May use luminance instead if the result is not accurate.
  48928. var max = Math.max(Math.max(r, g), b);
  48929. if (max > 255) {
  48930. var scale = 255 / max;
  48931. r *= scale;
  48932. g *= scale;
  48933. b *= scale;
  48934. }
  48935. byteArray[(i * 3) + 0] = r;
  48936. byteArray[(i * 3) + 1] = g;
  48937. byteArray[(i * 3) + 2] = b;
  48938. }
  48939. }
  48940. }
  48941. if (byteArray) {
  48942. results.push(byteArray);
  48943. }
  48944. else {
  48945. results.push(dataFace);
  48946. }
  48947. }
  48948. return results;
  48949. };
  48950. var mipmapGenerator = null;
  48951. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  48952. // if (!this._noMipmap &&
  48953. // this._usePMREMGenerator) {
  48954. // mipmapGenerator = (data: ArrayBufferView[]) => {
  48955. // // Custom setup of the generator matching with the PBR shader values.
  48956. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  48957. // this._size,
  48958. // this._size,
  48959. // 0,
  48960. // 3,
  48961. // this.getScene().getEngine().getCaps().textureFloat,
  48962. // 2048,
  48963. // 0.25,
  48964. // false,
  48965. // true);
  48966. // return generator.filterCubeMap();
  48967. // };
  48968. // }
  48969. 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);
  48970. };
  48971. /**
  48972. * Starts the loading process of the texture.
  48973. */
  48974. HDRCubeTexture.prototype.loadTexture = function () {
  48975. if (this._isBABYLONPreprocessed) {
  48976. this.loadBabylonTexture();
  48977. }
  48978. else {
  48979. this.loadHDRTexture();
  48980. }
  48981. };
  48982. HDRCubeTexture.prototype.clone = function () {
  48983. var size = this._isBABYLONPreprocessed ? null : this._size;
  48984. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  48985. // Base texture
  48986. newTexture.level = this.level;
  48987. newTexture.wrapU = this.wrapU;
  48988. newTexture.wrapV = this.wrapV;
  48989. newTexture.coordinatesIndex = this.coordinatesIndex;
  48990. newTexture.coordinatesMode = this.coordinatesMode;
  48991. return newTexture;
  48992. };
  48993. // Methods
  48994. HDRCubeTexture.prototype.delayLoad = function () {
  48995. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  48996. return;
  48997. }
  48998. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  48999. this._texture = this._getFromCache(this.url, this._noMipmap);
  49000. if (!this._texture) {
  49001. this.loadTexture();
  49002. }
  49003. };
  49004. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  49005. return this._textureMatrix;
  49006. };
  49007. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49008. this._textureMatrix = value;
  49009. };
  49010. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49011. var texture = null;
  49012. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  49013. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  49014. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  49015. texture.name = parsedTexture.name;
  49016. texture.hasAlpha = parsedTexture.hasAlpha;
  49017. texture.level = parsedTexture.level;
  49018. texture.coordinatesMode = parsedTexture.coordinatesMode;
  49019. texture.isBlocking = parsedTexture.isBlocking;
  49020. }
  49021. return texture;
  49022. };
  49023. HDRCubeTexture.prototype.serialize = function () {
  49024. if (!this.name) {
  49025. return null;
  49026. }
  49027. var serializationObject = {};
  49028. serializationObject.name = this.name;
  49029. serializationObject.hasAlpha = this.hasAlpha;
  49030. serializationObject.isCube = true;
  49031. serializationObject.level = this.level;
  49032. serializationObject.size = this._size;
  49033. serializationObject.coordinatesMode = this.coordinatesMode;
  49034. serializationObject.useInGammaSpace = this._useInGammaSpace;
  49035. serializationObject.generateHarmonics = this._generateHarmonics;
  49036. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  49037. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  49038. serializationObject.customType = "BABYLON.HDRCubeTexture";
  49039. serializationObject.noMipmap = this._noMipmap;
  49040. serializationObject.isBlocking = this._isBlocking;
  49041. return serializationObject;
  49042. };
  49043. /**
  49044. * Saves as a file the data contained in the texture in a binary format.
  49045. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  49046. * as the spherical used in the lighting.
  49047. * @param url The HDR file url.
  49048. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  49049. * @param onError Method called if any error happens during download.
  49050. * @return The packed binary data.
  49051. */
  49052. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  49053. if (onError === void 0) { onError = null; }
  49054. var callback = function (buffer) {
  49055. var data = new Blob([buffer], { type: 'application/octet-stream' });
  49056. // Returns a URL you can use as a href.
  49057. var objUrl = window.URL.createObjectURL(data);
  49058. // Simulates a link to it and click to dowload.
  49059. var a = document.createElement("a");
  49060. document.body.appendChild(a);
  49061. a.style.display = "none";
  49062. a.href = objUrl;
  49063. a.download = "envmap.babylon.hdr";
  49064. a.click();
  49065. };
  49066. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  49067. };
  49068. /**
  49069. * Serializes the data contained in the texture in a binary format.
  49070. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  49071. * as the spherical used in the lighting.
  49072. * @param url The HDR file url.
  49073. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  49074. * @param onError Method called if any error happens during download.
  49075. * @return The packed binary data.
  49076. */
  49077. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  49078. if (onError === void 0) { onError = null; }
  49079. // Needs the url tho create the texture.
  49080. if (!url) {
  49081. return null;
  49082. }
  49083. // Check Power of two size.
  49084. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  49085. return null;
  49086. }
  49087. // Coming Back in 3.1.
  49088. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  49089. return null;
  49090. };
  49091. HDRCubeTexture._facesMapping = [
  49092. "right",
  49093. "left",
  49094. "up",
  49095. "down",
  49096. "front",
  49097. "back"
  49098. ];
  49099. return HDRCubeTexture;
  49100. }(BABYLON.BaseTexture));
  49101. BABYLON.HDRCubeTexture = HDRCubeTexture;
  49102. })(BABYLON || (BABYLON = {}));
  49103. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  49104. var BABYLON;
  49105. (function (BABYLON) {
  49106. var DefaultLoadingScreen = (function () {
  49107. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  49108. if (_loadingText === void 0) { _loadingText = ""; }
  49109. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  49110. var _this = this;
  49111. this._renderingCanvas = _renderingCanvas;
  49112. this._loadingText = _loadingText;
  49113. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  49114. // Resize
  49115. this._resizeLoadingUI = function () {
  49116. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  49117. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  49118. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  49119. _this._loadingDiv.style.left = canvasRect.left + "px";
  49120. _this._loadingDiv.style.top = canvasRect.top + "px";
  49121. _this._loadingDiv.style.width = canvasRect.width + "px";
  49122. _this._loadingDiv.style.height = canvasRect.height + "px";
  49123. };
  49124. }
  49125. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  49126. if (this._loadingDiv) {
  49127. // Do not add a loading screen if there is already one
  49128. return;
  49129. }
  49130. this._loadingDiv = document.createElement("div");
  49131. this._loadingDiv.id = "babylonjsLoadingDiv";
  49132. this._loadingDiv.style.opacity = "0";
  49133. this._loadingDiv.style.transition = "opacity 1.5s ease";
  49134. // Loading text
  49135. this._loadingTextDiv = document.createElement("div");
  49136. this._loadingTextDiv.style.position = "absolute";
  49137. this._loadingTextDiv.style.left = "0";
  49138. this._loadingTextDiv.style.top = "50%";
  49139. this._loadingTextDiv.style.marginTop = "80px";
  49140. this._loadingTextDiv.style.width = "100%";
  49141. this._loadingTextDiv.style.height = "20px";
  49142. this._loadingTextDiv.style.fontFamily = "Arial";
  49143. this._loadingTextDiv.style.fontSize = "14px";
  49144. this._loadingTextDiv.style.color = "white";
  49145. this._loadingTextDiv.style.textAlign = "center";
  49146. this._loadingTextDiv.innerHTML = "Loading";
  49147. this._loadingDiv.appendChild(this._loadingTextDiv);
  49148. //set the predefined text
  49149. this._loadingTextDiv.innerHTML = this._loadingText;
  49150. // Generating keyframes
  49151. var style = document.createElement('style');
  49152. style.type = 'text/css';
  49153. 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 }";
  49154. style.innerHTML = keyFrames;
  49155. document.getElementsByTagName('head')[0].appendChild(style);
  49156. // Loading img
  49157. var imgBack = new Image();
  49158. 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";
  49159. imgBack.style.position = "absolute";
  49160. imgBack.style.left = "50%";
  49161. imgBack.style.top = "50%";
  49162. imgBack.style.marginLeft = "-60px";
  49163. imgBack.style.marginTop = "-60px";
  49164. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  49165. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  49166. imgBack.style.transformOrigin = "50% 50%";
  49167. imgBack.style.webkitTransformOrigin = "50% 50%";
  49168. this._loadingDiv.appendChild(imgBack);
  49169. this._resizeLoadingUI();
  49170. window.addEventListener("resize", this._resizeLoadingUI);
  49171. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  49172. document.body.appendChild(this._loadingDiv);
  49173. this._loadingDiv.style.opacity = "1";
  49174. };
  49175. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  49176. var _this = this;
  49177. if (!this._loadingDiv) {
  49178. return;
  49179. }
  49180. var onTransitionEnd = function () {
  49181. if (!_this._loadingDiv) {
  49182. return;
  49183. }
  49184. document.body.removeChild(_this._loadingDiv);
  49185. window.removeEventListener("resize", _this._resizeLoadingUI);
  49186. _this._loadingDiv = null;
  49187. };
  49188. this._loadingDiv.style.opacity = "0";
  49189. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  49190. };
  49191. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  49192. set: function (text) {
  49193. this._loadingText = text;
  49194. if (this._loadingTextDiv) {
  49195. this._loadingTextDiv.innerHTML = this._loadingText;
  49196. }
  49197. },
  49198. enumerable: true,
  49199. configurable: true
  49200. });
  49201. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  49202. get: function () {
  49203. return this._loadingDivBackgroundColor;
  49204. },
  49205. set: function (color) {
  49206. this._loadingDivBackgroundColor = color;
  49207. if (!this._loadingDiv) {
  49208. return;
  49209. }
  49210. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  49211. },
  49212. enumerable: true,
  49213. configurable: true
  49214. });
  49215. return DefaultLoadingScreen;
  49216. }());
  49217. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  49218. })(BABYLON || (BABYLON = {}));
  49219. //# sourceMappingURL=babylon.loadingScreen.js.map
  49220. var BABYLON;
  49221. (function (BABYLON) {
  49222. var SceneLoader = (function () {
  49223. function SceneLoader() {
  49224. }
  49225. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  49226. get: function () {
  49227. return 0;
  49228. },
  49229. enumerable: true,
  49230. configurable: true
  49231. });
  49232. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  49233. get: function () {
  49234. return 1;
  49235. },
  49236. enumerable: true,
  49237. configurable: true
  49238. });
  49239. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  49240. get: function () {
  49241. return 2;
  49242. },
  49243. enumerable: true,
  49244. configurable: true
  49245. });
  49246. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  49247. get: function () {
  49248. return 3;
  49249. },
  49250. enumerable: true,
  49251. configurable: true
  49252. });
  49253. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  49254. get: function () {
  49255. return SceneLoader._ForceFullSceneLoadingForIncremental;
  49256. },
  49257. set: function (value) {
  49258. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  49259. },
  49260. enumerable: true,
  49261. configurable: true
  49262. });
  49263. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  49264. get: function () {
  49265. return SceneLoader._ShowLoadingScreen;
  49266. },
  49267. set: function (value) {
  49268. SceneLoader._ShowLoadingScreen = value;
  49269. },
  49270. enumerable: true,
  49271. configurable: true
  49272. });
  49273. Object.defineProperty(SceneLoader, "loggingLevel", {
  49274. get: function () {
  49275. return SceneLoader._loggingLevel;
  49276. },
  49277. set: function (value) {
  49278. SceneLoader._loggingLevel = value;
  49279. },
  49280. enumerable: true,
  49281. configurable: true
  49282. });
  49283. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  49284. get: function () {
  49285. return SceneLoader._CleanBoneMatrixWeights;
  49286. },
  49287. set: function (value) {
  49288. SceneLoader._CleanBoneMatrixWeights = value;
  49289. },
  49290. enumerable: true,
  49291. configurable: true
  49292. });
  49293. SceneLoader._getDefaultPlugin = function () {
  49294. return SceneLoader._registeredPlugins[".babylon"];
  49295. };
  49296. SceneLoader._getPluginForExtension = function (extension) {
  49297. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  49298. if (registeredPlugin) {
  49299. return registeredPlugin;
  49300. }
  49301. return SceneLoader._getDefaultPlugin();
  49302. };
  49303. SceneLoader._getPluginForDirectLoad = function (data) {
  49304. for (var extension in SceneLoader._registeredPlugins) {
  49305. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  49306. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  49307. return SceneLoader._registeredPlugins[extension];
  49308. }
  49309. }
  49310. return SceneLoader._getDefaultPlugin();
  49311. };
  49312. SceneLoader._getPluginForFilename = function (sceneFilename) {
  49313. if (sceneFilename.name) {
  49314. sceneFilename = sceneFilename.name;
  49315. }
  49316. var dotPosition = sceneFilename.lastIndexOf(".");
  49317. var queryStringPosition = sceneFilename.indexOf("?");
  49318. if (queryStringPosition === -1) {
  49319. queryStringPosition = sceneFilename.length;
  49320. }
  49321. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  49322. return SceneLoader._getPluginForExtension(extension);
  49323. };
  49324. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  49325. SceneLoader._getDirectLoad = function (sceneFilename) {
  49326. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  49327. return sceneFilename.substr(5);
  49328. }
  49329. return null;
  49330. };
  49331. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49332. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  49333. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  49334. var plugin = registeredPlugin.plugin;
  49335. var useArrayBuffer = registeredPlugin.isBinary;
  49336. var database;
  49337. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  49338. var dataCallback = function (data) {
  49339. if (scene.isDisposed) {
  49340. onError("Scene has been disposed");
  49341. return;
  49342. }
  49343. scene.database = database;
  49344. try {
  49345. onSuccess(plugin, data);
  49346. }
  49347. catch (e) {
  49348. onError(null, e);
  49349. }
  49350. };
  49351. var manifestChecked = function (success) {
  49352. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  49353. onError(request.status + " " + request.statusText);
  49354. });
  49355. };
  49356. if (directLoad) {
  49357. dataCallback(directLoad);
  49358. return;
  49359. }
  49360. if (rootUrl.indexOf("file:") === -1) {
  49361. if (scene.getEngine().enableOfflineSupport) {
  49362. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  49363. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  49364. }
  49365. else {
  49366. manifestChecked(true);
  49367. }
  49368. }
  49369. else {
  49370. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  49371. }
  49372. };
  49373. // Public functions
  49374. SceneLoader.GetPluginForExtension = function (extension) {
  49375. return SceneLoader._getPluginForExtension(extension).plugin;
  49376. };
  49377. SceneLoader.RegisterPlugin = function (plugin) {
  49378. if (typeof plugin.extensions === "string") {
  49379. var extension = plugin.extensions;
  49380. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  49381. plugin: plugin,
  49382. isBinary: false
  49383. };
  49384. }
  49385. else {
  49386. var extensions = plugin.extensions;
  49387. Object.keys(extensions).forEach(function (extension) {
  49388. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  49389. plugin: plugin,
  49390. isBinary: extensions[extension].isBinary
  49391. };
  49392. });
  49393. }
  49394. };
  49395. /**
  49396. * Import meshes into a scene
  49397. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  49398. * @param rootUrl a string that defines the root url for scene and resources
  49399. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49400. * @param scene the instance of BABYLON.Scene to append to
  49401. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  49402. * @param onProgress a callback with a progress event for each file being loaded
  49403. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49404. */
  49405. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49406. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49407. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49408. return;
  49409. }
  49410. var loadingToken = {};
  49411. scene._addPendingData(loadingToken);
  49412. var errorHandler = function (message, exception) {
  49413. if (onError) {
  49414. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49415. }
  49416. scene._removePendingData(loadingToken);
  49417. };
  49418. var progressHandler = function (event) {
  49419. if (onProgress) {
  49420. onProgress(event);
  49421. }
  49422. };
  49423. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49424. if (plugin.importMesh) {
  49425. var syncedPlugin = plugin;
  49426. var meshes = [];
  49427. var particleSystems = [];
  49428. var skeletons = [];
  49429. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  49430. return;
  49431. }
  49432. if (onSuccess) {
  49433. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49434. onSuccess(meshes, particleSystems, skeletons);
  49435. scene._removePendingData(loadingToken);
  49436. }
  49437. }
  49438. else {
  49439. var asyncedPlugin = plugin;
  49440. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  49441. if (onSuccess) {
  49442. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49443. onSuccess(meshes, particleSystems, skeletons);
  49444. scene._removePendingData(loadingToken);
  49445. }
  49446. }, progressHandler, errorHandler);
  49447. }
  49448. }, progressHandler, errorHandler);
  49449. };
  49450. /**
  49451. * Load a scene
  49452. * @param rootUrl a string that defines the root url for scene and resources
  49453. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49454. * @param engine is the instance of BABYLON.Engine to use to create the scene
  49455. * @param onSuccess a callback with the scene when import succeeds
  49456. * @param onProgress a callback with a progress event for each file being loaded
  49457. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49458. */
  49459. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  49460. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  49461. };
  49462. /**
  49463. * Append a scene
  49464. * @param rootUrl a string that defines the root url for scene and resources
  49465. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49466. * @param scene is the instance of BABYLON.Scene to append to
  49467. * @param onSuccess a callback with the scene when import succeeds
  49468. * @param onProgress a callback with a progress event for each file being loaded
  49469. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49470. */
  49471. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49472. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49473. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49474. return;
  49475. }
  49476. if (SceneLoader.ShowLoadingScreen) {
  49477. scene.getEngine().displayLoadingUI();
  49478. }
  49479. var loadingToken = {};
  49480. scene._addPendingData(loadingToken);
  49481. var errorHandler = function (message, exception) {
  49482. if (onError) {
  49483. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49484. }
  49485. scene._removePendingData(loadingToken);
  49486. scene.getEngine().hideLoadingUI();
  49487. };
  49488. var progressHandler = function (event) {
  49489. if (onProgress) {
  49490. onProgress(event);
  49491. }
  49492. };
  49493. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49494. if (plugin.load) {
  49495. var syncedPlugin = plugin;
  49496. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  49497. return;
  49498. }
  49499. if (onSuccess) {
  49500. onSuccess(scene);
  49501. }
  49502. scene.loadingPluginName = plugin.name;
  49503. scene._removePendingData(loadingToken);
  49504. }
  49505. else {
  49506. var asyncedPlugin = plugin;
  49507. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  49508. if (onSuccess) {
  49509. onSuccess(scene);
  49510. }
  49511. scene.loadingPluginName = plugin.name;
  49512. scene._removePendingData(loadingToken);
  49513. }, progressHandler, errorHandler);
  49514. }
  49515. if (SceneLoader.ShowLoadingScreen) {
  49516. scene.executeWhenReady(function () {
  49517. scene.getEngine().hideLoadingUI();
  49518. });
  49519. }
  49520. }, progressHandler, errorHandler);
  49521. };
  49522. // Flags
  49523. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  49524. SceneLoader._ShowLoadingScreen = true;
  49525. SceneLoader._CleanBoneMatrixWeights = false;
  49526. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  49527. // Members
  49528. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  49529. SceneLoader._registeredPlugins = {};
  49530. return SceneLoader;
  49531. }());
  49532. BABYLON.SceneLoader = SceneLoader;
  49533. ;
  49534. })(BABYLON || (BABYLON = {}));
  49535. //# sourceMappingURL=babylon.sceneLoader.js.map
  49536. var BABYLON;
  49537. (function (BABYLON) {
  49538. var Internals;
  49539. (function (Internals) {
  49540. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  49541. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49542. var parsedMaterial = parsedData.materials[index];
  49543. if (parsedMaterial.id === id) {
  49544. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49545. }
  49546. }
  49547. return null;
  49548. };
  49549. var isDescendantOf = function (mesh, names, hierarchyIds) {
  49550. for (var i in names) {
  49551. if (mesh.name === names[i]) {
  49552. hierarchyIds.push(mesh.id);
  49553. return true;
  49554. }
  49555. }
  49556. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  49557. hierarchyIds.push(mesh.id);
  49558. return true;
  49559. }
  49560. return false;
  49561. };
  49562. var logOperation = function (operation, producer) {
  49563. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  49564. };
  49565. BABYLON.SceneLoader.RegisterPlugin({
  49566. name: "babylon.js",
  49567. extensions: ".babylon",
  49568. canDirectLoad: function (data) {
  49569. if (data.indexOf("babylon") !== -1) {
  49570. return true;
  49571. }
  49572. return false;
  49573. },
  49574. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  49575. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49576. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49577. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49578. // and avoid problems with multiple concurrent .babylon loads.
  49579. var log = "importMesh has failed JSON parse";
  49580. try {
  49581. var parsedData = JSON.parse(data);
  49582. log = "";
  49583. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49584. if (!meshesNames) {
  49585. meshesNames = null;
  49586. }
  49587. else if (!Array.isArray(meshesNames)) {
  49588. meshesNames = [meshesNames];
  49589. }
  49590. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49591. var loadedSkeletonsIds = [];
  49592. var loadedMaterialsIds = [];
  49593. var hierarchyIds = [];
  49594. var index;
  49595. var cache;
  49596. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49597. var parsedMesh = parsedData.meshes[index];
  49598. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  49599. if (meshesNames !== null) {
  49600. // Remove found mesh name from list.
  49601. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  49602. }
  49603. //Geometry?
  49604. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  49605. //does the file contain geometries?
  49606. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  49607. //find the correct geometry and add it to the scene
  49608. var found = false;
  49609. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  49610. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  49611. return;
  49612. }
  49613. else {
  49614. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  49615. if (parsedGeometryData.id === parsedMesh.geometryId) {
  49616. switch (geometryType) {
  49617. case "boxes":
  49618. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  49619. break;
  49620. case "spheres":
  49621. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  49622. break;
  49623. case "cylinders":
  49624. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  49625. break;
  49626. case "toruses":
  49627. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  49628. break;
  49629. case "grounds":
  49630. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  49631. break;
  49632. case "planes":
  49633. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  49634. break;
  49635. case "torusKnots":
  49636. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  49637. break;
  49638. case "vertexData":
  49639. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  49640. break;
  49641. }
  49642. found = true;
  49643. }
  49644. });
  49645. }
  49646. });
  49647. if (found === false) {
  49648. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  49649. }
  49650. }
  49651. }
  49652. // Material ?
  49653. if (parsedMesh.materialId) {
  49654. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  49655. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49656. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  49657. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  49658. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  49659. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  49660. var subMatId = parsedMultiMaterial.materials[matIndex];
  49661. loadedMaterialsIds.push(subMatId);
  49662. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  49663. log += "\n\tMaterial " + mat.toString(fullDetails);
  49664. }
  49665. loadedMaterialsIds.push(parsedMultiMaterial.id);
  49666. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49667. materialFound = true;
  49668. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  49669. break;
  49670. }
  49671. }
  49672. }
  49673. if (materialFound === false) {
  49674. loadedMaterialsIds.push(parsedMesh.materialId);
  49675. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  49676. if (!mat) {
  49677. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  49678. }
  49679. else {
  49680. log += "\n\tMaterial " + mat.toString(fullDetails);
  49681. }
  49682. }
  49683. }
  49684. // Skeleton ?
  49685. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49686. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  49687. if (skeletonAlreadyLoaded === false) {
  49688. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  49689. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  49690. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  49691. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49692. skeletons.push(skeleton);
  49693. loadedSkeletonsIds.push(parsedSkeleton.id);
  49694. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  49695. }
  49696. }
  49697. }
  49698. }
  49699. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49700. meshes.push(mesh);
  49701. log += "\n\tMesh " + mesh.toString(fullDetails);
  49702. }
  49703. }
  49704. // Connecting parents
  49705. var currentMesh;
  49706. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49707. currentMesh = scene.meshes[index];
  49708. if (currentMesh._waitingParentId) {
  49709. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  49710. currentMesh._waitingParentId = undefined;
  49711. }
  49712. }
  49713. // freeze and compute world matrix application
  49714. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49715. currentMesh = scene.meshes[index];
  49716. if (currentMesh._waitingFreezeWorldMatrix) {
  49717. currentMesh.freezeWorldMatrix();
  49718. currentMesh._waitingFreezeWorldMatrix = undefined;
  49719. }
  49720. else {
  49721. currentMesh.computeWorldMatrix(true);
  49722. }
  49723. }
  49724. }
  49725. // Particles
  49726. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49727. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49728. var parsedParticleSystem = parsedData.particleSystems[index];
  49729. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  49730. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  49731. }
  49732. }
  49733. }
  49734. return true;
  49735. }
  49736. catch (err) {
  49737. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  49738. log = null;
  49739. throw err;
  49740. }
  49741. finally {
  49742. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49743. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49744. }
  49745. }
  49746. },
  49747. load: function (scene, data, rootUrl) {
  49748. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49749. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49750. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49751. // and avoid problems with multiple concurrent .babylon loads.
  49752. var log = "importScene has failed JSON parse";
  49753. try {
  49754. var parsedData = JSON.parse(data);
  49755. log = "";
  49756. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49757. // Scene
  49758. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  49759. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  49760. }
  49761. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  49762. scene.autoClear = parsedData.autoClear;
  49763. }
  49764. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  49765. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  49766. }
  49767. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  49768. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  49769. }
  49770. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  49771. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  49772. }
  49773. // Fog
  49774. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  49775. scene.fogMode = parsedData.fogMode;
  49776. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  49777. scene.fogStart = parsedData.fogStart;
  49778. scene.fogEnd = parsedData.fogEnd;
  49779. scene.fogDensity = parsedData.fogDensity;
  49780. log += "\tFog mode for scene: ";
  49781. switch (scene.fogMode) {
  49782. // getters not compiling, so using hardcoded
  49783. case 1:
  49784. log += "exp\n";
  49785. break;
  49786. case 2:
  49787. log += "exp2\n";
  49788. break;
  49789. case 3:
  49790. log += "linear\n";
  49791. break;
  49792. }
  49793. }
  49794. //Physics
  49795. if (parsedData.physicsEnabled) {
  49796. var physicsPlugin;
  49797. if (parsedData.physicsEngine === "cannon") {
  49798. physicsPlugin = new BABYLON.CannonJSPlugin();
  49799. }
  49800. else if (parsedData.physicsEngine === "oimo") {
  49801. physicsPlugin = new BABYLON.OimoJSPlugin();
  49802. }
  49803. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  49804. //else - default engine, which is currently oimo
  49805. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  49806. scene.enablePhysics(physicsGravity, physicsPlugin);
  49807. }
  49808. // Metadata
  49809. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  49810. scene.metadata = parsedData.metadata;
  49811. }
  49812. //collisions, if defined. otherwise, default is true
  49813. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  49814. scene.collisionsEnabled = parsedData.collisionsEnabled;
  49815. }
  49816. scene.workerCollisions = !!parsedData.workerCollisions;
  49817. var index;
  49818. var cache;
  49819. // Lights
  49820. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  49821. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  49822. var parsedLight = parsedData.lights[index];
  49823. var light = BABYLON.Light.Parse(parsedLight, scene);
  49824. log += (index === 0 ? "\n\tLights:" : "");
  49825. log += "\n\t\t" + light.toString(fullDetails);
  49826. }
  49827. }
  49828. // Animations
  49829. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  49830. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  49831. var parsedAnimation = parsedData.animations[index];
  49832. var animation = BABYLON.Animation.Parse(parsedAnimation);
  49833. scene.animations.push(animation);
  49834. log += (index === 0 ? "\n\tAnimations:" : "");
  49835. log += "\n\t\t" + animation.toString(fullDetails);
  49836. }
  49837. }
  49838. if (parsedData.autoAnimate) {
  49839. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  49840. }
  49841. // Materials
  49842. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  49843. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49844. var parsedMaterial = parsedData.materials[index];
  49845. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49846. log += (index === 0 ? "\n\tMaterials:" : "");
  49847. log += "\n\t\t" + mat.toString(fullDetails);
  49848. }
  49849. }
  49850. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49851. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  49852. var parsedMultiMaterial = parsedData.multiMaterials[index];
  49853. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49854. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  49855. log += "\n\t\t" + mmat.toString(fullDetails);
  49856. }
  49857. }
  49858. // Morph targets
  49859. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  49860. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  49861. var managerData = _a[_i];
  49862. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  49863. }
  49864. }
  49865. // Skeletons
  49866. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49867. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  49868. var parsedSkeleton = parsedData.skeletons[index];
  49869. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49870. log += (index === 0 ? "\n\tSkeletons:" : "");
  49871. log += "\n\t\t" + skeleton.toString(fullDetails);
  49872. }
  49873. }
  49874. // Geometries
  49875. var geometries = parsedData.geometries;
  49876. if (geometries !== undefined && geometries !== null) {
  49877. // Boxes
  49878. var boxes = geometries.boxes;
  49879. if (boxes !== undefined && boxes !== null) {
  49880. for (index = 0, cache = boxes.length; index < cache; index++) {
  49881. var parsedBox = boxes[index];
  49882. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  49883. }
  49884. }
  49885. // Spheres
  49886. var spheres = geometries.spheres;
  49887. if (spheres !== undefined && spheres !== null) {
  49888. for (index = 0, cache = spheres.length; index < cache; index++) {
  49889. var parsedSphere = spheres[index];
  49890. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  49891. }
  49892. }
  49893. // Cylinders
  49894. var cylinders = geometries.cylinders;
  49895. if (cylinders !== undefined && cylinders !== null) {
  49896. for (index = 0, cache = cylinders.length; index < cache; index++) {
  49897. var parsedCylinder = cylinders[index];
  49898. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  49899. }
  49900. }
  49901. // Toruses
  49902. var toruses = geometries.toruses;
  49903. if (toruses !== undefined && toruses !== null) {
  49904. for (index = 0, cache = toruses.length; index < cache; index++) {
  49905. var parsedTorus = toruses[index];
  49906. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  49907. }
  49908. }
  49909. // Grounds
  49910. var grounds = geometries.grounds;
  49911. if (grounds !== undefined && grounds !== null) {
  49912. for (index = 0, cache = grounds.length; index < cache; index++) {
  49913. var parsedGround = grounds[index];
  49914. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  49915. }
  49916. }
  49917. // Planes
  49918. var planes = geometries.planes;
  49919. if (planes !== undefined && planes !== null) {
  49920. for (index = 0, cache = planes.length; index < cache; index++) {
  49921. var parsedPlane = planes[index];
  49922. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  49923. }
  49924. }
  49925. // TorusKnots
  49926. var torusKnots = geometries.torusKnots;
  49927. if (torusKnots !== undefined && torusKnots !== null) {
  49928. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  49929. var parsedTorusKnot = torusKnots[index];
  49930. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  49931. }
  49932. }
  49933. // VertexData
  49934. var vertexData = geometries.vertexData;
  49935. if (vertexData !== undefined && vertexData !== null) {
  49936. for (index = 0, cache = vertexData.length; index < cache; index++) {
  49937. var parsedVertexData = vertexData[index];
  49938. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  49939. }
  49940. }
  49941. }
  49942. // Meshes
  49943. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49944. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49945. var parsedMesh = parsedData.meshes[index];
  49946. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49947. log += (index === 0 ? "\n\tMeshes:" : "");
  49948. log += "\n\t\t" + mesh.toString(fullDetails);
  49949. }
  49950. }
  49951. // Cameras
  49952. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  49953. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  49954. var parsedCamera = parsedData.cameras[index];
  49955. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  49956. log += (index === 0 ? "\n\tCameras:" : "");
  49957. log += "\n\t\t" + camera.toString(fullDetails);
  49958. }
  49959. }
  49960. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  49961. scene.setActiveCameraByID(parsedData.activeCameraID);
  49962. }
  49963. // Browsing all the graph to connect the dots
  49964. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  49965. var camera = scene.cameras[index];
  49966. if (camera._waitingParentId) {
  49967. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  49968. camera._waitingParentId = undefined;
  49969. }
  49970. }
  49971. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49972. var light = scene.lights[index];
  49973. if (light._waitingParentId) {
  49974. light.parent = scene.getLastEntryByID(light._waitingParentId);
  49975. light._waitingParentId = undefined;
  49976. }
  49977. }
  49978. // Sounds
  49979. var loadedSounds = [];
  49980. var loadedSound;
  49981. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  49982. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  49983. var parsedSound = parsedData.sounds[index];
  49984. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49985. if (!parsedSound.url)
  49986. parsedSound.url = parsedSound.name;
  49987. if (!loadedSounds[parsedSound.url]) {
  49988. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  49989. loadedSounds[parsedSound.url] = loadedSound;
  49990. }
  49991. else {
  49992. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  49993. }
  49994. }
  49995. else {
  49996. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  49997. }
  49998. }
  49999. }
  50000. loadedSounds = [];
  50001. // Connect parents & children and parse actions
  50002. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50003. var mesh = scene.meshes[index];
  50004. if (mesh._waitingParentId) {
  50005. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  50006. mesh._waitingParentId = undefined;
  50007. }
  50008. if (mesh._waitingActions) {
  50009. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  50010. mesh._waitingActions = undefined;
  50011. }
  50012. }
  50013. // freeze world matrix application
  50014. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50015. var currentMesh = scene.meshes[index];
  50016. if (currentMesh._waitingFreezeWorldMatrix) {
  50017. currentMesh.freezeWorldMatrix();
  50018. currentMesh._waitingFreezeWorldMatrix = undefined;
  50019. }
  50020. else {
  50021. currentMesh.computeWorldMatrix(true);
  50022. }
  50023. }
  50024. // Particles Systems
  50025. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  50026. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  50027. var parsedParticleSystem = parsedData.particleSystems[index];
  50028. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  50029. }
  50030. }
  50031. // Lens flares
  50032. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  50033. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  50034. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  50035. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  50036. }
  50037. }
  50038. // Shadows
  50039. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  50040. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  50041. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  50042. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  50043. }
  50044. }
  50045. // Lights exclusions / inclusions
  50046. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  50047. var light = scene.lights[index];
  50048. // Excluded check
  50049. if (light._excludedMeshesIds.length > 0) {
  50050. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  50051. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  50052. if (excludedMesh) {
  50053. light.excludedMeshes.push(excludedMesh);
  50054. }
  50055. }
  50056. light._excludedMeshesIds = [];
  50057. }
  50058. // Included check
  50059. if (light._includedOnlyMeshesIds.length > 0) {
  50060. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  50061. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  50062. if (includedOnlyMesh) {
  50063. light.includedOnlyMeshes.push(includedOnlyMesh);
  50064. }
  50065. }
  50066. light._includedOnlyMeshesIds = [];
  50067. }
  50068. }
  50069. // Actions (scene)
  50070. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  50071. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  50072. }
  50073. // Finish
  50074. return true;
  50075. }
  50076. catch (err) {
  50077. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  50078. log = null;
  50079. throw err;
  50080. }
  50081. finally {
  50082. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  50083. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  50084. }
  50085. }
  50086. }
  50087. });
  50088. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50089. })(BABYLON || (BABYLON = {}));
  50090. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  50091. var BABYLON;
  50092. (function (BABYLON) {
  50093. var FilesInput = (function () {
  50094. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  50095. this._engine = engine;
  50096. this._currentScene = scene;
  50097. this._sceneLoadedCallback = sceneLoadedCallback;
  50098. this._progressCallback = progressCallback;
  50099. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  50100. this._textureLoadingCallback = textureLoadingCallback;
  50101. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  50102. this._onReloadCallback = onReloadCallback;
  50103. }
  50104. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  50105. var _this = this;
  50106. if (elementToMonitor) {
  50107. this._elementToMonitor = elementToMonitor;
  50108. this._dragEnterHandler = function (e) { _this.drag(e); };
  50109. this._dragOverHandler = function (e) { _this.drag(e); };
  50110. this._dropHandler = function (e) { _this.drop(e); };
  50111. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  50112. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  50113. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  50114. }
  50115. };
  50116. FilesInput.prototype.dispose = function () {
  50117. if (!this._elementToMonitor) {
  50118. return;
  50119. }
  50120. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  50121. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  50122. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  50123. };
  50124. FilesInput.prototype.renderFunction = function () {
  50125. if (this._additionalRenderLoopLogicCallback) {
  50126. this._additionalRenderLoopLogicCallback();
  50127. }
  50128. if (this._currentScene) {
  50129. if (this._textureLoadingCallback) {
  50130. var remaining = this._currentScene.getWaitingItemsCount();
  50131. if (remaining > 0) {
  50132. this._textureLoadingCallback(remaining);
  50133. }
  50134. }
  50135. this._currentScene.render();
  50136. }
  50137. };
  50138. FilesInput.prototype.drag = function (e) {
  50139. e.stopPropagation();
  50140. e.preventDefault();
  50141. };
  50142. FilesInput.prototype.drop = function (eventDrop) {
  50143. eventDrop.stopPropagation();
  50144. eventDrop.preventDefault();
  50145. this.loadFiles(eventDrop);
  50146. };
  50147. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  50148. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  50149. reader.readEntries(function (fileEntries) {
  50150. var remaining = fileEntries.length;
  50151. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  50152. var fileEntry = fileEntries_1[_i];
  50153. if (fileEntry.isFile) {
  50154. fileEntry.file(function (file) {
  50155. file.correctName = relativePath + file.name;
  50156. files.push(file);
  50157. remaining--;
  50158. if (remaining === 0) {
  50159. callback();
  50160. }
  50161. });
  50162. }
  50163. else {
  50164. remaining--;
  50165. if (remaining === 0) {
  50166. callback();
  50167. }
  50168. }
  50169. }
  50170. });
  50171. };
  50172. FilesInput.prototype._processFiles = function (files) {
  50173. for (var i = 0; i < files.length; i++) {
  50174. var name = files[i].correctName.toLowerCase();
  50175. var extension = name.split('.').pop();
  50176. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  50177. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  50178. this._sceneFileToLoad = files[i];
  50179. }
  50180. else {
  50181. FilesInput.FilesToLoad[name] = files[i];
  50182. }
  50183. }
  50184. if (this._onReloadCallback) {
  50185. this._onReloadCallback(this._sceneFileToLoad);
  50186. }
  50187. else {
  50188. this.reload();
  50189. }
  50190. };
  50191. FilesInput.prototype.loadFiles = function (event) {
  50192. var _this = this;
  50193. if (this._startingProcessingFilesCallback)
  50194. this._startingProcessingFilesCallback();
  50195. // Handling data transfer via drag'n'drop
  50196. if (event && event.dataTransfer && event.dataTransfer.files) {
  50197. this._filesToLoad = event.dataTransfer.files;
  50198. }
  50199. // Handling files from input files
  50200. if (event && event.target && event.target.files) {
  50201. this._filesToLoad = event.target.files;
  50202. }
  50203. if (this._filesToLoad && this._filesToLoad.length > 0) {
  50204. var files_1 = [];
  50205. var folders = [];
  50206. var items = event.dataTransfer ? event.dataTransfer.items : null;
  50207. for (var i = 0; i < this._filesToLoad.length; i++) {
  50208. var fileToLoad = this._filesToLoad[i];
  50209. var name_1 = fileToLoad.name.toLowerCase();
  50210. var type = fileToLoad.type;
  50211. var entry = void 0;
  50212. fileToLoad.correctName = name_1;
  50213. if (items) {
  50214. var item = items[i];
  50215. if (item.getAsEntry) {
  50216. entry = item.getAsEntry();
  50217. }
  50218. else if (item.webkitGetAsEntry) {
  50219. entry = item.webkitGetAsEntry();
  50220. }
  50221. }
  50222. if (!entry) {
  50223. files_1.push(fileToLoad);
  50224. }
  50225. else {
  50226. if (entry.isDirectory) {
  50227. folders.push(entry);
  50228. }
  50229. else {
  50230. files_1.push(fileToLoad);
  50231. }
  50232. }
  50233. }
  50234. if (folders.length === 0) {
  50235. this._processFiles(files_1);
  50236. }
  50237. else {
  50238. var remaining = folders.length;
  50239. // Extract folder content
  50240. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  50241. var folder = folders_1[_i];
  50242. this._handleFolderDrop(folder, files_1, function () {
  50243. remaining--;
  50244. if (remaining === 0) {
  50245. _this._processFiles(files_1);
  50246. }
  50247. });
  50248. }
  50249. }
  50250. }
  50251. };
  50252. FilesInput.prototype.reload = function () {
  50253. var _this = this;
  50254. // If a ".babylon" file has been provided
  50255. if (this._sceneFileToLoad) {
  50256. if (this._currentScene) {
  50257. if (BABYLON.Tools.errorsCount > 0) {
  50258. BABYLON.Tools.ClearLogCache();
  50259. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  50260. }
  50261. this._engine.stopRenderLoop();
  50262. this._currentScene.dispose();
  50263. }
  50264. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  50265. _this._currentScene = newScene;
  50266. if (_this._sceneLoadedCallback) {
  50267. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  50268. }
  50269. // Wait for textures and shaders to be ready
  50270. _this._currentScene.executeWhenReady(function () {
  50271. _this._engine.runRenderLoop(function () {
  50272. _this.renderFunction();
  50273. });
  50274. });
  50275. }, function (progress) {
  50276. if (_this._progressCallback) {
  50277. _this._progressCallback(progress);
  50278. }
  50279. });
  50280. }
  50281. else {
  50282. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  50283. }
  50284. };
  50285. FilesInput.FilesToLoad = new Array();
  50286. return FilesInput;
  50287. }());
  50288. BABYLON.FilesInput = FilesInput;
  50289. })(BABYLON || (BABYLON = {}));
  50290. //# sourceMappingURL=babylon.filesInput.js.map
  50291. var BABYLON;
  50292. (function (BABYLON) {
  50293. var FramingBehavior = (function () {
  50294. function FramingBehavior() {
  50295. this._mode = FramingBehavior.FitFrustumSidesMode;
  50296. this._radiusScale = 1.0;
  50297. this._positionScale = 0.5;
  50298. this._defaultElevation = 0.3;
  50299. this._elevationReturnTime = 1500;
  50300. this._elevationReturnWaitTime = 1000;
  50301. this._zoomStopsAnimation = false;
  50302. this._framingTime = 1500;
  50303. this._isPointerDown = false;
  50304. this._lastFrameTime = null;
  50305. this._lastInteractionTime = -Infinity;
  50306. // Framing control
  50307. this._animatables = new Array();
  50308. this._betaIsAnimating = false;
  50309. this._lastFrameRadius = 0;
  50310. }
  50311. Object.defineProperty(FramingBehavior.prototype, "name", {
  50312. get: function () {
  50313. return "Framing";
  50314. },
  50315. enumerable: true,
  50316. configurable: true
  50317. });
  50318. Object.defineProperty(FramingBehavior.prototype, "mode", {
  50319. /**
  50320. * Gets current mode used by the behavior.
  50321. */
  50322. get: function () {
  50323. return this._mode;
  50324. },
  50325. /**
  50326. * Sets the current mode used by the behavior
  50327. */
  50328. set: function (mode) {
  50329. this._mode = mode;
  50330. },
  50331. enumerable: true,
  50332. configurable: true
  50333. });
  50334. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  50335. /**
  50336. * Gets the scale applied to the radius
  50337. */
  50338. get: function () {
  50339. return this._radiusScale;
  50340. },
  50341. /**
  50342. * Sets the scale applied to the radius (1 by default)
  50343. */
  50344. set: function (radius) {
  50345. this._radiusScale = radius;
  50346. },
  50347. enumerable: true,
  50348. configurable: true
  50349. });
  50350. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  50351. /**
  50352. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  50353. */
  50354. get: function () {
  50355. return this._positionScale;
  50356. },
  50357. /**
  50358. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  50359. */
  50360. set: function (scale) {
  50361. this._positionScale = scale;
  50362. },
  50363. enumerable: true,
  50364. configurable: true
  50365. });
  50366. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  50367. /**
  50368. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  50369. * behaviour is triggered, in radians.
  50370. */
  50371. get: function () {
  50372. return this._defaultElevation;
  50373. },
  50374. /**
  50375. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  50376. * behaviour is triggered, in radians.
  50377. */
  50378. set: function (elevation) {
  50379. this._defaultElevation = elevation;
  50380. },
  50381. enumerable: true,
  50382. configurable: true
  50383. });
  50384. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  50385. /**
  50386. * Gets the time (in milliseconds) taken to return to the default beta position.
  50387. * Negative value indicates camera should not return to default.
  50388. */
  50389. get: function () {
  50390. return this._elevationReturnTime;
  50391. },
  50392. /**
  50393. * Sets the time (in milliseconds) taken to return to the default beta position.
  50394. * Negative value indicates camera should not return to default.
  50395. */
  50396. set: function (speed) {
  50397. this._elevationReturnTime = speed;
  50398. },
  50399. enumerable: true,
  50400. configurable: true
  50401. });
  50402. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  50403. /**
  50404. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  50405. */
  50406. get: function () {
  50407. return this._elevationReturnWaitTime;
  50408. },
  50409. /**
  50410. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  50411. */
  50412. set: function (time) {
  50413. this._elevationReturnWaitTime = time;
  50414. },
  50415. enumerable: true,
  50416. configurable: true
  50417. });
  50418. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  50419. /**
  50420. * Gets the flag that indicates if user zooming should stop animation.
  50421. */
  50422. get: function () {
  50423. return this._zoomStopsAnimation;
  50424. },
  50425. /**
  50426. * Sets the flag that indicates if user zooming should stop animation.
  50427. */
  50428. set: function (flag) {
  50429. this._zoomStopsAnimation = flag;
  50430. },
  50431. enumerable: true,
  50432. configurable: true
  50433. });
  50434. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  50435. /**
  50436. * Gets the transition time when framing the mesh, in milliseconds
  50437. */
  50438. get: function () {
  50439. return this._framingTime;
  50440. },
  50441. /**
  50442. * Sets the transition time when framing the mesh, in milliseconds
  50443. */
  50444. set: function (time) {
  50445. this._framingTime = time;
  50446. },
  50447. enumerable: true,
  50448. configurable: true
  50449. });
  50450. FramingBehavior.prototype.attach = function (camera) {
  50451. var _this = this;
  50452. this._attachedCamera = camera;
  50453. var scene = this._attachedCamera.getScene();
  50454. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  50455. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50456. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50457. _this._isPointerDown = true;
  50458. return;
  50459. }
  50460. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50461. _this._isPointerDown = false;
  50462. }
  50463. });
  50464. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50465. if (mesh) {
  50466. _this.zoomOnMesh(mesh);
  50467. }
  50468. });
  50469. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50470. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50471. _this._applyUserInteraction();
  50472. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  50473. // back to the default position after a given timeout
  50474. _this._maintainCameraAboveGround();
  50475. });
  50476. };
  50477. FramingBehavior.prototype.detach = function () {
  50478. var scene = this._attachedCamera.getScene();
  50479. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50480. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50481. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50482. this._attachedCamera = null;
  50483. };
  50484. /**
  50485. * Targets the given mesh and updates zoom level accordingly.
  50486. * @param mesh The mesh to target.
  50487. * @param radius Optional. If a cached radius position already exists, overrides default.
  50488. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50489. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50490. */
  50491. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ) {
  50492. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50493. mesh.computeWorldMatrix(true);
  50494. var boundingBox = mesh.getBoundingInfo().boundingBox;
  50495. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ);
  50496. };
  50497. /**
  50498. * Targets the given mesh and updates zoom level accordingly.
  50499. * @param mesh The mesh to target.
  50500. * @param radius Optional. If a cached radius position already exists, overrides default.
  50501. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50502. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50503. */
  50504. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ) {
  50505. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50506. var zoomTarget;
  50507. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  50508. var bottom = minimumWorld.y;
  50509. var top = maximumWorld.y;
  50510. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  50511. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  50512. if (focusOnOriginXZ) {
  50513. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  50514. }
  50515. else {
  50516. var centerWorld = minimumWorld.add(radiusWorld);
  50517. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  50518. }
  50519. if (!this._vectorTransition) {
  50520. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  50521. }
  50522. this._betaIsAnimating = true;
  50523. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  50524. // sets the radius and lower radius bounds
  50525. // Small delta ensures camera is not always at lower zoom limit.
  50526. var delta = 0.1;
  50527. var radius = 0;
  50528. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  50529. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50530. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  50531. radius = position;
  50532. }
  50533. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50534. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50535. if (this._attachedCamera.lowerRadiusLimit === null) {
  50536. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  50537. }
  50538. }
  50539. // transition to new radius
  50540. if (!this._radiusTransition) {
  50541. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50542. }
  50543. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime));
  50544. };
  50545. /**
  50546. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  50547. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  50548. * frustum width.
  50549. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  50550. * to fully enclose the mesh in the viewing frustum.
  50551. */
  50552. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  50553. var size = maximumWorld.subtract(minimumWorld);
  50554. var boxVectorGlobalDiagonal = size.length();
  50555. var frustumSlope = this._getFrustumSlope();
  50556. // Formula for setting distance
  50557. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  50558. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  50559. // Horizon distance
  50560. var radius = radiusWithoutFraming * this._radiusScale;
  50561. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  50562. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  50563. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  50564. var camera = this._attachedCamera;
  50565. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50566. // Don't exceed the requested limit
  50567. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  50568. }
  50569. // Don't exceed the upper radius limit
  50570. if (camera.upperRadiusLimit) {
  50571. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  50572. }
  50573. return distance;
  50574. };
  50575. /**
  50576. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  50577. * is automatically returned to its default position (expected to be above ground plane).
  50578. */
  50579. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  50580. var _this = this;
  50581. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  50582. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  50583. var limitBeta = Math.PI * 0.5;
  50584. // Bring the camera back up if below the ground plane
  50585. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  50586. this._betaIsAnimating = true;
  50587. //Transition to new position
  50588. this.stopAllAnimations();
  50589. if (!this._betaTransition) {
  50590. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50591. }
  50592. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  50593. _this._clearAnimationLocks();
  50594. _this.stopAllAnimations();
  50595. }));
  50596. }
  50597. };
  50598. /**
  50599. * Returns the frustum slope based on the canvas ratio and camera FOV
  50600. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  50601. */
  50602. FramingBehavior.prototype._getFrustumSlope = function () {
  50603. // Calculate the viewport ratio
  50604. // Aspect Ratio is Height/Width.
  50605. var camera = this._attachedCamera;
  50606. var engine = camera.getScene().getEngine();
  50607. var aspectRatio = engine.getAspectRatio(camera);
  50608. // Camera FOV is the vertical field of view (top-bottom) in radians.
  50609. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  50610. var frustumSlopeY = Math.tan(camera.fov / 2);
  50611. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  50612. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  50613. // along the forward vector.
  50614. var frustumSlopeX = frustumSlopeY * aspectRatio;
  50615. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  50616. };
  50617. /**
  50618. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  50619. */
  50620. FramingBehavior.prototype._clearAnimationLocks = function () {
  50621. this._betaIsAnimating = false;
  50622. };
  50623. /**
  50624. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50625. */
  50626. FramingBehavior.prototype._applyUserInteraction = function () {
  50627. if (this.isUserIsMoving) {
  50628. this._lastInteractionTime = BABYLON.Tools.Now;
  50629. this.stopAllAnimations();
  50630. this._clearAnimationLocks();
  50631. }
  50632. };
  50633. /**
  50634. * Stops and removes all animations that have been applied to the camera
  50635. */
  50636. FramingBehavior.prototype.stopAllAnimations = function () {
  50637. this._attachedCamera.animations = [];
  50638. while (this._animatables.length) {
  50639. if (this._animatables[0]) {
  50640. this._animatables[0].onAnimationEnd = null;
  50641. this._animatables[0].stop();
  50642. }
  50643. this._animatables.shift();
  50644. }
  50645. };
  50646. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  50647. /**
  50648. * Gets a value indicating if the user is moving the camera
  50649. */
  50650. get: function () {
  50651. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50652. this._attachedCamera.inertialBetaOffset !== 0 ||
  50653. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50654. this._attachedCamera.inertialPanningX !== 0 ||
  50655. this._attachedCamera.inertialPanningY !== 0 ||
  50656. this._isPointerDown;
  50657. },
  50658. enumerable: true,
  50659. configurable: true
  50660. });
  50661. /**
  50662. * The easing function used by animations
  50663. */
  50664. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  50665. /**
  50666. * The easing mode used by animations
  50667. */
  50668. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  50669. // Statics
  50670. /**
  50671. * The camera can move all the way towards the mesh.
  50672. */
  50673. FramingBehavior.IgnoreBoundsSizeMode = 0;
  50674. /**
  50675. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  50676. */
  50677. FramingBehavior.FitFrustumSidesMode = 1;
  50678. return FramingBehavior;
  50679. }());
  50680. BABYLON.FramingBehavior = FramingBehavior;
  50681. })(BABYLON || (BABYLON = {}));
  50682. //# sourceMappingURL=babylon.framingBehavior.js.map
  50683. var BABYLON;
  50684. (function (BABYLON) {
  50685. /**
  50686. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  50687. */
  50688. var BouncingBehavior = (function () {
  50689. function BouncingBehavior() {
  50690. /**
  50691. * The duration of the animation, in milliseconds
  50692. */
  50693. this.transitionDuration = 450;
  50694. /**
  50695. * Length of the distance animated by the transition when lower radius is reached
  50696. */
  50697. this.lowerRadiusTransitionRange = 2;
  50698. /**
  50699. * Length of the distance animated by the transition when upper radius is reached
  50700. */
  50701. this.upperRadiusTransitionRange = -2;
  50702. this._autoTransitionRange = false;
  50703. // Animations
  50704. this._radiusIsAnimating = false;
  50705. this._radiusBounceTransition = null;
  50706. this._animatables = new Array();
  50707. }
  50708. Object.defineProperty(BouncingBehavior.prototype, "name", {
  50709. get: function () {
  50710. return "Bouncing";
  50711. },
  50712. enumerable: true,
  50713. configurable: true
  50714. });
  50715. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  50716. /**
  50717. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50718. */
  50719. get: function () {
  50720. return this._autoTransitionRange;
  50721. },
  50722. /**
  50723. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50724. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  50725. */
  50726. set: function (value) {
  50727. var _this = this;
  50728. if (this._autoTransitionRange === value) {
  50729. return;
  50730. }
  50731. this._autoTransitionRange = value;
  50732. var camera = this._attachedCamera;
  50733. if (value) {
  50734. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50735. if (!mesh) {
  50736. return;
  50737. }
  50738. mesh.computeWorldMatrix(true);
  50739. var diagonal = mesh.getBoundingInfo().diagonalLength;
  50740. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  50741. _this.upperRadiusTransitionRange = diagonal * 0.05;
  50742. });
  50743. }
  50744. else if (this._onMeshTargetChangedObserver) {
  50745. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50746. }
  50747. },
  50748. enumerable: true,
  50749. configurable: true
  50750. });
  50751. BouncingBehavior.prototype.attach = function (camera) {
  50752. var _this = this;
  50753. this._attachedCamera = camera;
  50754. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50755. // Add the bounce animation to the lower radius limit
  50756. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  50757. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  50758. }
  50759. // Add the bounce animation to the upper radius limit
  50760. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  50761. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  50762. }
  50763. });
  50764. };
  50765. BouncingBehavior.prototype.detach = function () {
  50766. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50767. if (this._onMeshTargetChangedObserver) {
  50768. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50769. }
  50770. this._attachedCamera = null;
  50771. };
  50772. /**
  50773. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  50774. * @param radiusLimit The limit to check against.
  50775. * @return Bool to indicate if at limit.
  50776. */
  50777. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  50778. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  50779. return true;
  50780. }
  50781. return false;
  50782. };
  50783. /**
  50784. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  50785. * @param radiusDelta The delta by which to animate to. Can be negative.
  50786. */
  50787. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  50788. var _this = this;
  50789. if (!this._radiusBounceTransition) {
  50790. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  50791. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  50792. }
  50793. // Prevent zoom until bounce has completed
  50794. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  50795. this._attachedCamera.wheelPrecision = Infinity;
  50796. this._attachedCamera.inertialRadiusOffset = 0;
  50797. // Animate to the radius limit
  50798. this.stopAllAnimations();
  50799. this._radiusIsAnimating = true;
  50800. 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(); }));
  50801. };
  50802. /**
  50803. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  50804. */
  50805. BouncingBehavior.prototype._clearAnimationLocks = function () {
  50806. this._radiusIsAnimating = false;
  50807. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  50808. };
  50809. /**
  50810. * Stops and removes all animations that have been applied to the camera
  50811. */
  50812. BouncingBehavior.prototype.stopAllAnimations = function () {
  50813. this._attachedCamera.animations = [];
  50814. while (this._animatables.length) {
  50815. this._animatables[0].onAnimationEnd = null;
  50816. this._animatables[0].stop();
  50817. this._animatables.shift();
  50818. }
  50819. };
  50820. /**
  50821. * The easing function used by animations
  50822. */
  50823. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  50824. /**
  50825. * The easing mode used by animations
  50826. */
  50827. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  50828. return BouncingBehavior;
  50829. }());
  50830. BABYLON.BouncingBehavior = BouncingBehavior;
  50831. })(BABYLON || (BABYLON = {}));
  50832. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  50833. var BABYLON;
  50834. (function (BABYLON) {
  50835. var AutoRotationBehavior = (function () {
  50836. function AutoRotationBehavior() {
  50837. this._zoomStopsAnimation = false;
  50838. this._idleRotationSpeed = 0.05;
  50839. this._idleRotationWaitTime = 2000;
  50840. this._idleRotationSpinupTime = 2000;
  50841. this._isPointerDown = false;
  50842. this._lastFrameTime = null;
  50843. this._lastInteractionTime = -Infinity;
  50844. this._cameraRotationSpeed = 0;
  50845. this._lastFrameRadius = 0;
  50846. }
  50847. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  50848. get: function () {
  50849. return "AutoRotation";
  50850. },
  50851. enumerable: true,
  50852. configurable: true
  50853. });
  50854. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  50855. /**
  50856. * Gets the flag that indicates if user zooming should stop animation.
  50857. */
  50858. get: function () {
  50859. return this._zoomStopsAnimation;
  50860. },
  50861. /**
  50862. * Sets the flag that indicates if user zooming should stop animation.
  50863. */
  50864. set: function (flag) {
  50865. this._zoomStopsAnimation = flag;
  50866. },
  50867. enumerable: true,
  50868. configurable: true
  50869. });
  50870. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  50871. /**
  50872. * Gets the default speed at which the camera rotates around the model.
  50873. */
  50874. get: function () {
  50875. return this._idleRotationSpeed;
  50876. },
  50877. /**
  50878. * Sets the default speed at which the camera rotates around the model.
  50879. */
  50880. set: function (speed) {
  50881. this._idleRotationSpeed = speed;
  50882. },
  50883. enumerable: true,
  50884. configurable: true
  50885. });
  50886. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  50887. /**
  50888. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  50889. */
  50890. get: function () {
  50891. return this._idleRotationWaitTime;
  50892. },
  50893. /**
  50894. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  50895. */
  50896. set: function (time) {
  50897. this._idleRotationWaitTime = time;
  50898. },
  50899. enumerable: true,
  50900. configurable: true
  50901. });
  50902. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  50903. /**
  50904. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50905. */
  50906. get: function () {
  50907. return this._idleRotationSpinupTime;
  50908. },
  50909. /**
  50910. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50911. */
  50912. set: function (time) {
  50913. this._idleRotationSpinupTime = time;
  50914. },
  50915. enumerable: true,
  50916. configurable: true
  50917. });
  50918. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  50919. /**
  50920. * Gets a value indicating if the camera is currently rotating because of this behavior
  50921. */
  50922. get: function () {
  50923. return Math.abs(this._cameraRotationSpeed) > 0;
  50924. },
  50925. enumerable: true,
  50926. configurable: true
  50927. });
  50928. AutoRotationBehavior.prototype.attach = function (camera) {
  50929. var _this = this;
  50930. this._attachedCamera = camera;
  50931. var scene = this._attachedCamera.getScene();
  50932. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50933. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50934. _this._isPointerDown = true;
  50935. return;
  50936. }
  50937. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50938. _this._isPointerDown = false;
  50939. }
  50940. });
  50941. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50942. var now = BABYLON.Tools.Now;
  50943. var dt = 0;
  50944. if (_this._lastFrameTime != null) {
  50945. dt = now - _this._lastFrameTime;
  50946. }
  50947. _this._lastFrameTime = now;
  50948. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50949. _this._applyUserInteraction();
  50950. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  50951. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  50952. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  50953. // Step camera rotation by rotation speed
  50954. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  50955. });
  50956. };
  50957. AutoRotationBehavior.prototype.detach = function () {
  50958. var scene = this._attachedCamera.getScene();
  50959. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50960. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50961. this._attachedCamera = null;
  50962. };
  50963. /**
  50964. * Returns true if user is scrolling.
  50965. * @return true if user is scrolling.
  50966. */
  50967. AutoRotationBehavior.prototype._userIsZooming = function () {
  50968. return this._attachedCamera.inertialRadiusOffset !== 0;
  50969. };
  50970. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  50971. var zoomHasHitLimit = false;
  50972. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  50973. zoomHasHitLimit = true;
  50974. }
  50975. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  50976. this._lastFrameRadius = this._attachedCamera.radius;
  50977. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  50978. };
  50979. /**
  50980. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50981. */
  50982. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  50983. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  50984. this._lastInteractionTime = BABYLON.Tools.Now;
  50985. }
  50986. };
  50987. // Tools
  50988. AutoRotationBehavior.prototype._userIsMoving = function () {
  50989. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50990. this._attachedCamera.inertialBetaOffset !== 0 ||
  50991. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50992. this._attachedCamera.inertialPanningX !== 0 ||
  50993. this._attachedCamera.inertialPanningY !== 0 ||
  50994. this._isPointerDown;
  50995. };
  50996. return AutoRotationBehavior;
  50997. }());
  50998. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  50999. })(BABYLON || (BABYLON = {}));
  51000. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  51001. var BABYLON;
  51002. (function (BABYLON) {
  51003. var MorphTarget = (function () {
  51004. function MorphTarget(name, influence) {
  51005. if (influence === void 0) { influence = 0; }
  51006. this.name = name;
  51007. this.animations = new Array();
  51008. this.onInfluenceChanged = new BABYLON.Observable();
  51009. this.influence = influence;
  51010. }
  51011. Object.defineProperty(MorphTarget.prototype, "influence", {
  51012. get: function () {
  51013. return this._influence;
  51014. },
  51015. set: function (influence) {
  51016. if (this._influence === influence) {
  51017. return;
  51018. }
  51019. var previous = this._influence;
  51020. this._influence = influence;
  51021. if (this.onInfluenceChanged.hasObservers) {
  51022. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  51023. }
  51024. },
  51025. enumerable: true,
  51026. configurable: true
  51027. });
  51028. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  51029. get: function () {
  51030. return this._normals !== undefined;
  51031. },
  51032. enumerable: true,
  51033. configurable: true
  51034. });
  51035. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  51036. get: function () {
  51037. return this._tangents !== undefined;
  51038. },
  51039. enumerable: true,
  51040. configurable: true
  51041. });
  51042. MorphTarget.prototype.setPositions = function (data) {
  51043. this._positions = new Float32Array(data);
  51044. };
  51045. MorphTarget.prototype.getPositions = function () {
  51046. return this._positions;
  51047. };
  51048. MorphTarget.prototype.setNormals = function (data) {
  51049. this._normals = new Float32Array(data);
  51050. };
  51051. MorphTarget.prototype.getNormals = function () {
  51052. return this._normals;
  51053. };
  51054. MorphTarget.prototype.setTangents = function (data) {
  51055. this._tangents = new Float32Array(data);
  51056. };
  51057. MorphTarget.prototype.getTangents = function () {
  51058. return this._tangents;
  51059. };
  51060. /**
  51061. * Serializes the current target into a Serialization object.
  51062. * Returns the serialized object.
  51063. */
  51064. MorphTarget.prototype.serialize = function () {
  51065. var serializationObject = {};
  51066. serializationObject.name = this.name;
  51067. serializationObject.influence = this.influence;
  51068. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  51069. if (this.hasNormals) {
  51070. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  51071. }
  51072. if (this.hasTangents) {
  51073. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  51074. }
  51075. return serializationObject;
  51076. };
  51077. // Statics
  51078. MorphTarget.Parse = function (serializationObject) {
  51079. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  51080. result.setPositions(serializationObject.positions);
  51081. if (serializationObject.normals) {
  51082. result.setNormals(serializationObject.normals);
  51083. }
  51084. if (serializationObject.tangents) {
  51085. result.setTangents(serializationObject.tangents);
  51086. }
  51087. return result;
  51088. };
  51089. MorphTarget.FromMesh = function (mesh, name, influence) {
  51090. if (!name) {
  51091. name = mesh.name;
  51092. }
  51093. var result = new MorphTarget(name, influence);
  51094. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  51095. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  51096. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  51097. }
  51098. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  51099. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  51100. }
  51101. return result;
  51102. };
  51103. return MorphTarget;
  51104. }());
  51105. BABYLON.MorphTarget = MorphTarget;
  51106. })(BABYLON || (BABYLON = {}));
  51107. //# sourceMappingURL=babylon.morphTarget.js.map
  51108. var BABYLON;
  51109. (function (BABYLON) {
  51110. var MorphTargetManager = (function () {
  51111. function MorphTargetManager(scene) {
  51112. this._targets = new Array();
  51113. this._targetObservable = new Array();
  51114. this._activeTargets = new BABYLON.SmartArray(16);
  51115. this._supportsNormals = false;
  51116. this._supportsTangents = false;
  51117. this._vertexCount = 0;
  51118. this._uniqueId = 0;
  51119. this._tempInfluences = new Array();
  51120. if (!scene) {
  51121. scene = BABYLON.Engine.LastCreatedScene;
  51122. }
  51123. this._scene = scene;
  51124. this._scene.morphTargetManagers.push(this);
  51125. this._uniqueId = scene.getUniqueId();
  51126. }
  51127. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  51128. get: function () {
  51129. return this._uniqueId;
  51130. },
  51131. enumerable: true,
  51132. configurable: true
  51133. });
  51134. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  51135. get: function () {
  51136. return this._vertexCount;
  51137. },
  51138. enumerable: true,
  51139. configurable: true
  51140. });
  51141. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  51142. get: function () {
  51143. return this._supportsNormals;
  51144. },
  51145. enumerable: true,
  51146. configurable: true
  51147. });
  51148. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  51149. get: function () {
  51150. return this._supportsTangents;
  51151. },
  51152. enumerable: true,
  51153. configurable: true
  51154. });
  51155. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  51156. get: function () {
  51157. return this._targets.length;
  51158. },
  51159. enumerable: true,
  51160. configurable: true
  51161. });
  51162. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  51163. get: function () {
  51164. return this._activeTargets.length;
  51165. },
  51166. enumerable: true,
  51167. configurable: true
  51168. });
  51169. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  51170. get: function () {
  51171. return this._influences;
  51172. },
  51173. enumerable: true,
  51174. configurable: true
  51175. });
  51176. MorphTargetManager.prototype.getActiveTarget = function (index) {
  51177. return this._activeTargets.data[index];
  51178. };
  51179. MorphTargetManager.prototype.getTarget = function (index) {
  51180. return this._targets[index];
  51181. };
  51182. MorphTargetManager.prototype.addTarget = function (target) {
  51183. var _this = this;
  51184. if (this._vertexCount) {
  51185. if (this._vertexCount !== target.getPositions().length / 3) {
  51186. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  51187. return;
  51188. }
  51189. }
  51190. this._targets.push(target);
  51191. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  51192. _this._syncActiveTargets(needUpdate);
  51193. }));
  51194. this._syncActiveTargets(true);
  51195. };
  51196. MorphTargetManager.prototype.removeTarget = function (target) {
  51197. var index = this._targets.indexOf(target);
  51198. if (index >= 0) {
  51199. this._targets.splice(index, 1);
  51200. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  51201. this._vertexCount = 0;
  51202. this._syncActiveTargets(true);
  51203. }
  51204. };
  51205. /**
  51206. * Serializes the current manager into a Serialization object.
  51207. * Returns the serialized object.
  51208. */
  51209. MorphTargetManager.prototype.serialize = function () {
  51210. var serializationObject = {};
  51211. serializationObject.id = this.uniqueId;
  51212. serializationObject.targets = [];
  51213. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  51214. var target = _a[_i];
  51215. serializationObject.targets.push(target.serialize());
  51216. }
  51217. return serializationObject;
  51218. };
  51219. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  51220. this._syncActiveTargets(needUpdate);
  51221. };
  51222. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  51223. var influenceCount = 0;
  51224. this._activeTargets.reset();
  51225. this._supportsNormals = true;
  51226. this._supportsTangents = true;
  51227. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  51228. var target = _a[_i];
  51229. if (target.influence > 0) {
  51230. this._activeTargets.push(target);
  51231. this._tempInfluences[influenceCount++] = target.influence;
  51232. this._supportsNormals = this._supportsNormals && target.hasNormals;
  51233. this._supportsTangents = this._supportsTangents && target.hasTangents;
  51234. if (this._vertexCount === 0) {
  51235. this._vertexCount = target.getPositions().length / 3;
  51236. }
  51237. }
  51238. }
  51239. if (!this._influences || this._influences.length !== influenceCount) {
  51240. this._influences = new Float32Array(influenceCount);
  51241. }
  51242. for (var index = 0; index < influenceCount; index++) {
  51243. this._influences[index] = this._tempInfluences[index];
  51244. }
  51245. if (needUpdate) {
  51246. // Flag meshes as dirty to resync with the active targets
  51247. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  51248. var mesh = _c[_b];
  51249. if (mesh.morphTargetManager === this) {
  51250. mesh._syncGeometryWithMorphTargetManager();
  51251. }
  51252. }
  51253. }
  51254. };
  51255. // Statics
  51256. MorphTargetManager.Parse = function (serializationObject, scene) {
  51257. var result = new MorphTargetManager(scene);
  51258. result._uniqueId = serializationObject.id;
  51259. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  51260. var targetData = _a[_i];
  51261. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  51262. }
  51263. return result;
  51264. };
  51265. return MorphTargetManager;
  51266. }());
  51267. BABYLON.MorphTargetManager = MorphTargetManager;
  51268. })(BABYLON || (BABYLON = {}));
  51269. //# sourceMappingURL=babylon.morphTargetManager.js.map
  51270. 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}"};
  51271. 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};"};
  51272. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  51273. var BABYLON;
  51274. (function (BABYLON) {
  51275. var GridMaterialDefines = (function (_super) {
  51276. __extends(GridMaterialDefines, _super);
  51277. function GridMaterialDefines() {
  51278. var _this = _super.call(this) || this;
  51279. _this.TRANSPARENT = false;
  51280. _this.FOG = false;
  51281. _this.PREMULTIPLYALPHA = false;
  51282. _this.rebuild();
  51283. return _this;
  51284. }
  51285. return GridMaterialDefines;
  51286. }(BABYLON.MaterialDefines));
  51287. /**
  51288. * The grid materials allows you to wrap any shape with a grid.
  51289. * Colors are customizable.
  51290. */
  51291. var GridMaterial = (function (_super) {
  51292. __extends(GridMaterial, _super);
  51293. /**
  51294. * constructor
  51295. * @param name The name given to the material in order to identify it afterwards.
  51296. * @param scene The scene the material is used in.
  51297. */
  51298. function GridMaterial(name, scene) {
  51299. var _this = _super.call(this, name, scene) || this;
  51300. /**
  51301. * Main color of the grid (e.g. between lines)
  51302. */
  51303. _this.mainColor = BABYLON.Color3.Black();
  51304. /**
  51305. * Color of the grid lines.
  51306. */
  51307. _this.lineColor = BABYLON.Color3.Teal();
  51308. /**
  51309. * The scale of the grid compared to unit.
  51310. */
  51311. _this.gridRatio = 1.0;
  51312. /**
  51313. * The frequency of thicker lines.
  51314. */
  51315. _this.majorUnitFrequency = 10;
  51316. /**
  51317. * The visibility of minor units in the grid.
  51318. */
  51319. _this.minorUnitVisibility = 0.33;
  51320. /**
  51321. * The grid opacity outside of the lines.
  51322. */
  51323. _this.opacity = 1.0;
  51324. /**
  51325. * Determine RBG output is premultiplied by alpha value.
  51326. */
  51327. _this.preMultiplyAlpha = false;
  51328. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  51329. return _this;
  51330. }
  51331. /**
  51332. * Returns wehter or not the grid requires alpha blending.
  51333. */
  51334. GridMaterial.prototype.needAlphaBlending = function () {
  51335. return this.opacity < 1.0;
  51336. };
  51337. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  51338. if (this.isFrozen) {
  51339. if (this._wasPreviouslyReady && subMesh.effect) {
  51340. return true;
  51341. }
  51342. }
  51343. if (!subMesh._materialDefines) {
  51344. subMesh._materialDefines = new GridMaterialDefines();
  51345. }
  51346. var defines = subMesh._materialDefines;
  51347. var scene = this.getScene();
  51348. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  51349. if (this._renderId === scene.getRenderId()) {
  51350. return true;
  51351. }
  51352. }
  51353. var engine = scene.getEngine();
  51354. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  51355. defines.TRANSPARENT = !defines.TRANSPARENT;
  51356. defines.markAsUnprocessed();
  51357. }
  51358. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  51359. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  51360. defines.markAsUnprocessed();
  51361. }
  51362. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  51363. // Get correct effect
  51364. if (defines.isDirty) {
  51365. defines.markAsProcessed();
  51366. scene.resetCachedMaterial();
  51367. // Attributes
  51368. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  51369. // Defines
  51370. var join = defines.toString();
  51371. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  51372. }
  51373. if (!subMesh.effect.isReady()) {
  51374. return false;
  51375. }
  51376. this._renderId = scene.getRenderId();
  51377. this._wasPreviouslyReady = true;
  51378. return true;
  51379. };
  51380. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  51381. var scene = this.getScene();
  51382. var defines = subMesh._materialDefines;
  51383. if (!defines) {
  51384. return;
  51385. }
  51386. var effect = subMesh.effect;
  51387. this._activeEffect = effect;
  51388. // Matrices
  51389. this.bindOnlyWorldMatrix(world);
  51390. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  51391. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  51392. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  51393. // Uniforms
  51394. if (this._mustRebind(scene, effect)) {
  51395. this._activeEffect.setColor3("mainColor", this.mainColor);
  51396. this._activeEffect.setColor3("lineColor", this.lineColor);
  51397. this._gridControl.x = this.gridRatio;
  51398. this._gridControl.y = Math.round(this.majorUnitFrequency);
  51399. this._gridControl.z = this.minorUnitVisibility;
  51400. this._gridControl.w = this.opacity;
  51401. this._activeEffect.setVector4("gridControl", this._gridControl);
  51402. }
  51403. // Fog
  51404. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  51405. this._afterBind(mesh, this._activeEffect);
  51406. };
  51407. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  51408. _super.prototype.dispose.call(this, forceDisposeEffect);
  51409. };
  51410. GridMaterial.prototype.clone = function (name) {
  51411. var _this = this;
  51412. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  51413. };
  51414. GridMaterial.prototype.serialize = function () {
  51415. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51416. serializationObject.customType = "BABYLON.GridMaterial";
  51417. return serializationObject;
  51418. };
  51419. GridMaterial.prototype.getClassName = function () {
  51420. return "GridMaterial";
  51421. };
  51422. GridMaterial.Parse = function (source, scene, rootUrl) {
  51423. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  51424. };
  51425. __decorate([
  51426. BABYLON.serializeAsColor3()
  51427. ], GridMaterial.prototype, "mainColor", void 0);
  51428. __decorate([
  51429. BABYLON.serializeAsColor3()
  51430. ], GridMaterial.prototype, "lineColor", void 0);
  51431. __decorate([
  51432. BABYLON.serialize()
  51433. ], GridMaterial.prototype, "gridRatio", void 0);
  51434. __decorate([
  51435. BABYLON.serialize()
  51436. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  51437. __decorate([
  51438. BABYLON.serialize()
  51439. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  51440. __decorate([
  51441. BABYLON.serialize()
  51442. ], GridMaterial.prototype, "opacity", void 0);
  51443. __decorate([
  51444. BABYLON.serialize()
  51445. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  51446. return GridMaterial;
  51447. }(BABYLON.PushMaterial));
  51448. BABYLON.GridMaterial = GridMaterial;
  51449. })(BABYLON || (BABYLON = {}));
  51450. //# sourceMappingURL=babylon.gridmaterial.js.map
  51451. 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}";
  51452. 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}";
  51453. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  51454. var BABYLON;
  51455. (function (BABYLON) {
  51456. var GLTFLoaderCoordinateSystemMode;
  51457. (function (GLTFLoaderCoordinateSystemMode) {
  51458. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  51459. // 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.
  51460. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  51461. // The glTF right-handed data is not transformed in any form and is loaded directly.
  51462. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  51463. // Sets the useRightHandedSystem flag on the scene.
  51464. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  51465. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  51466. var GLTFFileLoader = (function () {
  51467. function GLTFFileLoader() {
  51468. // V2 options
  51469. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  51470. this.name = "gltf";
  51471. this.extensions = {
  51472. ".gltf": { isBinary: false },
  51473. ".glb": { isBinary: true }
  51474. };
  51475. }
  51476. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  51477. var loaderData = GLTFFileLoader._parse(data, onError);
  51478. if (!loaderData) {
  51479. return;
  51480. }
  51481. var loader = this._getLoader(loaderData, onError);
  51482. if (!loader) {
  51483. return;
  51484. }
  51485. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51486. };
  51487. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  51488. var loaderData = GLTFFileLoader._parse(data, onError);
  51489. if (!loaderData) {
  51490. return;
  51491. }
  51492. var loader = this._getLoader(loaderData, onError);
  51493. if (!loader) {
  51494. return;
  51495. }
  51496. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51497. };
  51498. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  51499. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  51500. };
  51501. GLTFFileLoader._parse = function (data, onError) {
  51502. if (data instanceof ArrayBuffer) {
  51503. return GLTFFileLoader._parseBinary(data, onError);
  51504. }
  51505. try {
  51506. return {
  51507. json: JSON.parse(data),
  51508. bin: null
  51509. };
  51510. }
  51511. catch (e) {
  51512. onError(e.message);
  51513. return null;
  51514. }
  51515. };
  51516. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  51517. var loaderVersion = { major: 2, minor: 0 };
  51518. var asset = loaderData.json.asset || {};
  51519. var version = GLTFFileLoader._parseVersion(asset.version);
  51520. if (!version) {
  51521. onError("Invalid version: " + asset.version);
  51522. return null;
  51523. }
  51524. if (asset.minVersion !== undefined) {
  51525. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  51526. if (!minVersion) {
  51527. onError("Invalid minimum version: " + asset.minVersion);
  51528. return null;
  51529. }
  51530. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  51531. onError("Incompatible minimum version: " + asset.minVersion);
  51532. return null;
  51533. }
  51534. }
  51535. var createLoaders = {
  51536. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  51537. 2: GLTFFileLoader.CreateGLTFLoaderV2
  51538. };
  51539. var createLoader = createLoaders[version.major];
  51540. if (!createLoader) {
  51541. onError("Unsupported version: " + asset.version);
  51542. return null;
  51543. }
  51544. return createLoader(this);
  51545. };
  51546. GLTFFileLoader._parseBinary = function (data, onError) {
  51547. var Binary = {
  51548. Magic: 0x46546C67
  51549. };
  51550. var binaryReader = new BinaryReader(data);
  51551. var magic = binaryReader.readUint32();
  51552. if (magic !== Binary.Magic) {
  51553. onError("Unexpected magic: " + magic);
  51554. return null;
  51555. }
  51556. var version = binaryReader.readUint32();
  51557. switch (version) {
  51558. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  51559. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  51560. }
  51561. onError("Unsupported version: " + version);
  51562. return null;
  51563. };
  51564. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  51565. var ContentFormat = {
  51566. JSON: 0
  51567. };
  51568. var length = binaryReader.readUint32();
  51569. if (length != binaryReader.getLength()) {
  51570. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51571. return null;
  51572. }
  51573. var contentLength = binaryReader.readUint32();
  51574. var contentFormat = binaryReader.readUint32();
  51575. var content;
  51576. switch (contentFormat) {
  51577. case ContentFormat.JSON:
  51578. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  51579. break;
  51580. default:
  51581. onError("Unexpected content format: " + contentFormat);
  51582. return null;
  51583. }
  51584. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  51585. var body = binaryReader.readUint8Array(bytesRemaining);
  51586. return {
  51587. json: content,
  51588. bin: body
  51589. };
  51590. };
  51591. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  51592. var ChunkFormat = {
  51593. JSON: 0x4E4F534A,
  51594. BIN: 0x004E4942
  51595. };
  51596. var length = binaryReader.readUint32();
  51597. if (length !== binaryReader.getLength()) {
  51598. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51599. return null;
  51600. }
  51601. // JSON chunk
  51602. var chunkLength = binaryReader.readUint32();
  51603. var chunkFormat = binaryReader.readUint32();
  51604. if (chunkFormat !== ChunkFormat.JSON) {
  51605. onError("First chunk format is not JSON");
  51606. return null;
  51607. }
  51608. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  51609. // Look for BIN chunk
  51610. var bin = null;
  51611. while (binaryReader.getPosition() < binaryReader.getLength()) {
  51612. chunkLength = binaryReader.readUint32();
  51613. chunkFormat = binaryReader.readUint32();
  51614. switch (chunkFormat) {
  51615. case ChunkFormat.JSON:
  51616. onError("Unexpected JSON chunk");
  51617. return null;
  51618. case ChunkFormat.BIN:
  51619. bin = binaryReader.readUint8Array(chunkLength);
  51620. break;
  51621. default:
  51622. // ignore unrecognized chunkFormat
  51623. binaryReader.skipBytes(chunkLength);
  51624. break;
  51625. }
  51626. }
  51627. return {
  51628. json: json,
  51629. bin: bin
  51630. };
  51631. };
  51632. GLTFFileLoader._parseVersion = function (version) {
  51633. if (!version) {
  51634. return null;
  51635. }
  51636. var parts = version.split(".");
  51637. if (parts.length != 2) {
  51638. return null;
  51639. }
  51640. var major = +parts[0];
  51641. if (isNaN(major)) {
  51642. return null;
  51643. }
  51644. var minor = +parts[1];
  51645. if (isNaN(minor)) {
  51646. return null;
  51647. }
  51648. return {
  51649. major: major,
  51650. minor: minor
  51651. };
  51652. };
  51653. GLTFFileLoader._compareVersion = function (a, b) {
  51654. if (a.major > b.major)
  51655. return 1;
  51656. if (a.major < b.major)
  51657. return -1;
  51658. if (a.minor > b.minor)
  51659. return 1;
  51660. if (a.minor < b.minor)
  51661. return -1;
  51662. return 0;
  51663. };
  51664. GLTFFileLoader._decodeBufferToText = function (view) {
  51665. var result = "";
  51666. var length = view.byteLength;
  51667. for (var i = 0; i < length; ++i) {
  51668. result += String.fromCharCode(view[i]);
  51669. }
  51670. return result;
  51671. };
  51672. // V1 options
  51673. GLTFFileLoader.HomogeneousCoordinates = false;
  51674. GLTFFileLoader.IncrementalLoading = true;
  51675. return GLTFFileLoader;
  51676. }());
  51677. BABYLON.GLTFFileLoader = GLTFFileLoader;
  51678. var BinaryReader = (function () {
  51679. function BinaryReader(arrayBuffer) {
  51680. this._arrayBuffer = arrayBuffer;
  51681. this._dataView = new DataView(arrayBuffer);
  51682. this._byteOffset = 0;
  51683. }
  51684. BinaryReader.prototype.getPosition = function () {
  51685. return this._byteOffset;
  51686. };
  51687. BinaryReader.prototype.getLength = function () {
  51688. return this._arrayBuffer.byteLength;
  51689. };
  51690. BinaryReader.prototype.readUint32 = function () {
  51691. var value = this._dataView.getUint32(this._byteOffset, true);
  51692. this._byteOffset += 4;
  51693. return value;
  51694. };
  51695. BinaryReader.prototype.readUint8Array = function (length) {
  51696. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  51697. this._byteOffset += length;
  51698. return value;
  51699. };
  51700. BinaryReader.prototype.skipBytes = function (length) {
  51701. this._byteOffset += length;
  51702. };
  51703. return BinaryReader;
  51704. }());
  51705. if (BABYLON.SceneLoader) {
  51706. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  51707. }
  51708. })(BABYLON || (BABYLON = {}));
  51709. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  51710. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51711. var BABYLON;
  51712. (function (BABYLON) {
  51713. var GLTF1;
  51714. (function (GLTF1) {
  51715. /**
  51716. * Enums
  51717. */
  51718. var EComponentType;
  51719. (function (EComponentType) {
  51720. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  51721. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51722. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  51723. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51724. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  51725. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  51726. var EShaderType;
  51727. (function (EShaderType) {
  51728. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  51729. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  51730. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  51731. var EParameterType;
  51732. (function (EParameterType) {
  51733. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  51734. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51735. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  51736. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51737. EParameterType[EParameterType["INT"] = 5124] = "INT";
  51738. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  51739. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  51740. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  51741. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  51742. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  51743. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  51744. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  51745. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  51746. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  51747. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  51748. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  51749. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  51750. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  51751. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  51752. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  51753. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  51754. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  51755. var ETextureWrapMode;
  51756. (function (ETextureWrapMode) {
  51757. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  51758. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  51759. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  51760. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  51761. var ETextureFilterType;
  51762. (function (ETextureFilterType) {
  51763. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  51764. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  51765. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  51766. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  51767. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  51768. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  51769. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  51770. var ETextureFormat;
  51771. (function (ETextureFormat) {
  51772. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  51773. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  51774. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  51775. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  51776. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  51777. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  51778. var ECullingType;
  51779. (function (ECullingType) {
  51780. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  51781. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  51782. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  51783. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  51784. var EBlendingFunction;
  51785. (function (EBlendingFunction) {
  51786. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  51787. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  51788. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  51789. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  51790. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  51791. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  51792. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  51793. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  51794. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  51795. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  51796. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  51797. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  51798. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  51799. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  51800. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  51801. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  51802. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  51803. })(BABYLON || (BABYLON = {}));
  51804. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  51805. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51806. var BABYLON;
  51807. (function (BABYLON) {
  51808. var GLTF1;
  51809. (function (GLTF1) {
  51810. /**
  51811. * Tokenizer. Used for shaders compatibility
  51812. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  51813. */
  51814. var ETokenType;
  51815. (function (ETokenType) {
  51816. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  51817. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  51818. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  51819. })(ETokenType || (ETokenType = {}));
  51820. var Tokenizer = (function () {
  51821. function Tokenizer(toParse) {
  51822. this._pos = 0;
  51823. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  51824. this._toParse = toParse;
  51825. this._maxPos = toParse.length;
  51826. }
  51827. Tokenizer.prototype.getNextToken = function () {
  51828. if (this.isEnd())
  51829. return ETokenType.END_OF_INPUT;
  51830. this.currentString = this.read();
  51831. this.currentToken = ETokenType.UNKNOWN;
  51832. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  51833. this.currentToken = ETokenType.IDENTIFIER;
  51834. this.currentIdentifier = this.currentString;
  51835. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  51836. this.currentIdentifier += this.currentString;
  51837. this.forward();
  51838. }
  51839. }
  51840. return this.currentToken;
  51841. };
  51842. Tokenizer.prototype.peek = function () {
  51843. return this._toParse[this._pos];
  51844. };
  51845. Tokenizer.prototype.read = function () {
  51846. return this._toParse[this._pos++];
  51847. };
  51848. Tokenizer.prototype.forward = function () {
  51849. this._pos++;
  51850. };
  51851. Tokenizer.prototype.isEnd = function () {
  51852. return this._pos >= this._maxPos;
  51853. };
  51854. return Tokenizer;
  51855. }());
  51856. /**
  51857. * Values
  51858. */
  51859. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  51860. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  51861. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  51862. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  51863. /**
  51864. * Parse
  51865. */
  51866. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  51867. for (var buf in parsedBuffers) {
  51868. var parsedBuffer = parsedBuffers[buf];
  51869. gltfRuntime.buffers[buf] = parsedBuffer;
  51870. gltfRuntime.buffersCount++;
  51871. }
  51872. };
  51873. var parseShaders = function (parsedShaders, gltfRuntime) {
  51874. for (var sha in parsedShaders) {
  51875. var parsedShader = parsedShaders[sha];
  51876. gltfRuntime.shaders[sha] = parsedShader;
  51877. gltfRuntime.shaderscount++;
  51878. }
  51879. };
  51880. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  51881. for (var object in parsedObjects) {
  51882. var parsedObject = parsedObjects[object];
  51883. gltfRuntime[runtimeProperty][object] = parsedObject;
  51884. }
  51885. };
  51886. /**
  51887. * Utils
  51888. */
  51889. var normalizeUVs = function (buffer) {
  51890. if (!buffer) {
  51891. return;
  51892. }
  51893. for (var i = 0; i < buffer.length / 2; i++) {
  51894. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  51895. }
  51896. };
  51897. var replaceInString = function (str, searchValue, replaceValue) {
  51898. while (str.indexOf(searchValue) !== -1) {
  51899. str = str.replace(searchValue, replaceValue);
  51900. }
  51901. return str;
  51902. };
  51903. var getAttribute = function (attributeParameter) {
  51904. if (attributeParameter.semantic === "NORMAL") {
  51905. return "normal";
  51906. }
  51907. else if (attributeParameter.semantic === "POSITION") {
  51908. return "position";
  51909. }
  51910. else if (attributeParameter.semantic === "JOINT") {
  51911. return "matricesIndices";
  51912. }
  51913. else if (attributeParameter.semantic === "WEIGHT") {
  51914. return "matricesWeights";
  51915. }
  51916. else if (attributeParameter.semantic === "COLOR") {
  51917. return "color";
  51918. }
  51919. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  51920. var channel = Number(attributeParameter.semantic.split("_")[1]);
  51921. return "uv" + (channel === 0 ? "" : channel + 1);
  51922. }
  51923. };
  51924. /**
  51925. * Returns the animation path (glTF -> Babylon)
  51926. */
  51927. var getAnimationPath = function (path) {
  51928. var index = glTFAnimationPaths.indexOf(path);
  51929. if (index !== -1) {
  51930. return babylonAnimationPaths[index];
  51931. }
  51932. return path;
  51933. };
  51934. /**
  51935. * Loads and creates animations
  51936. */
  51937. var loadAnimations = function (gltfRuntime) {
  51938. for (var anim in gltfRuntime.animations) {
  51939. var animation = gltfRuntime.animations[anim];
  51940. var lastAnimation = null;
  51941. for (var i = 0; i < animation.channels.length; i++) {
  51942. // Get parameters and load buffers
  51943. var channel = animation.channels[i];
  51944. var sampler = animation.samplers[channel.sampler];
  51945. if (!sampler) {
  51946. continue;
  51947. }
  51948. var inputData = null;
  51949. var outputData = null;
  51950. if (animation.parameters) {
  51951. inputData = animation.parameters[sampler.input];
  51952. outputData = animation.parameters[sampler.output];
  51953. }
  51954. else {
  51955. inputData = sampler.input;
  51956. outputData = sampler.output;
  51957. }
  51958. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  51959. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  51960. var targetID = channel.target.id;
  51961. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  51962. if (targetNode === null) {
  51963. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  51964. }
  51965. if (targetNode === null) {
  51966. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  51967. continue;
  51968. }
  51969. var isBone = targetNode instanceof BABYLON.Bone;
  51970. // Get target path (position, rotation or scaling)
  51971. var targetPath = channel.target.path;
  51972. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  51973. if (targetPathIndex !== -1) {
  51974. targetPath = babylonAnimationPaths[targetPathIndex];
  51975. }
  51976. // Determine animation type
  51977. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  51978. if (!isBone) {
  51979. if (targetPath === "rotationQuaternion") {
  51980. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  51981. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  51982. }
  51983. else {
  51984. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  51985. }
  51986. }
  51987. // Create animation and key frames
  51988. var babylonAnimation = null;
  51989. var keys = [];
  51990. var arrayOffset = 0;
  51991. var modifyKey = false;
  51992. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  51993. babylonAnimation = lastAnimation;
  51994. modifyKey = true;
  51995. }
  51996. if (!modifyKey) {
  51997. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51998. }
  51999. // For each frame
  52000. for (var j = 0; j < bufferInput.length; j++) {
  52001. var value = null;
  52002. if (targetPath === "rotationQuaternion") {
  52003. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  52004. arrayOffset += 4;
  52005. }
  52006. else {
  52007. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  52008. arrayOffset += 3;
  52009. }
  52010. if (isBone) {
  52011. var bone = targetNode;
  52012. var translation = BABYLON.Vector3.Zero();
  52013. var rotationQuaternion = new BABYLON.Quaternion();
  52014. var scaling = BABYLON.Vector3.Zero();
  52015. // Warning on decompose
  52016. var mat = bone.getBaseMatrix();
  52017. if (modifyKey) {
  52018. mat = lastAnimation.getKeys()[j].value;
  52019. }
  52020. mat.decompose(scaling, rotationQuaternion, translation);
  52021. if (targetPath === "position") {
  52022. translation = value;
  52023. }
  52024. else if (targetPath === "rotationQuaternion") {
  52025. rotationQuaternion = value;
  52026. }
  52027. else {
  52028. scaling = value;
  52029. }
  52030. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  52031. }
  52032. if (!modifyKey) {
  52033. keys.push({
  52034. frame: bufferInput[j],
  52035. value: value
  52036. });
  52037. }
  52038. else {
  52039. lastAnimation.getKeys()[j].value = value;
  52040. }
  52041. }
  52042. // Finish
  52043. if (!modifyKey) {
  52044. babylonAnimation.setKeys(keys);
  52045. targetNode.animations.push(babylonAnimation);
  52046. }
  52047. lastAnimation = babylonAnimation;
  52048. gltfRuntime.scene.stopAnimation(targetNode);
  52049. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  52050. }
  52051. }
  52052. };
  52053. /**
  52054. * Returns the bones transformation matrix
  52055. */
  52056. var configureBoneTransformation = function (node) {
  52057. var mat = null;
  52058. if (node.translation || node.rotation || node.scale) {
  52059. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  52060. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  52061. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  52062. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  52063. }
  52064. else {
  52065. mat = BABYLON.Matrix.FromArray(node.matrix);
  52066. }
  52067. return mat;
  52068. };
  52069. /**
  52070. * Returns the parent bone
  52071. */
  52072. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  52073. // Try to find
  52074. for (var i = 0; i < newSkeleton.bones.length; i++) {
  52075. if (newSkeleton.bones[i].name === jointName) {
  52076. return newSkeleton.bones[i];
  52077. }
  52078. }
  52079. // Not found, search in gltf nodes
  52080. var nodes = gltfRuntime.nodes;
  52081. for (var nde in nodes) {
  52082. var node = nodes[nde];
  52083. if (!node.jointName) {
  52084. continue;
  52085. }
  52086. var children = node.children;
  52087. for (var i = 0; i < children.length; i++) {
  52088. var child = gltfRuntime.nodes[children[i]];
  52089. if (!child.jointName) {
  52090. continue;
  52091. }
  52092. if (child.jointName === jointName) {
  52093. var mat = configureBoneTransformation(node);
  52094. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  52095. bone.id = nde;
  52096. return bone;
  52097. }
  52098. }
  52099. }
  52100. return null;
  52101. };
  52102. /**
  52103. * Returns the appropriate root node
  52104. */
  52105. var getNodeToRoot = function (nodesToRoot, id) {
  52106. for (var i = 0; i < nodesToRoot.length; i++) {
  52107. var nodeToRoot = nodesToRoot[i];
  52108. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  52109. var child = nodeToRoot.node.children[j];
  52110. if (child === id) {
  52111. return nodeToRoot.bone;
  52112. }
  52113. }
  52114. }
  52115. return null;
  52116. };
  52117. /**
  52118. * Returns the node with the joint name
  52119. */
  52120. var getJointNode = function (gltfRuntime, jointName) {
  52121. var nodes = gltfRuntime.nodes;
  52122. var node = nodes[jointName];
  52123. if (node) {
  52124. return {
  52125. node: node,
  52126. id: jointName
  52127. };
  52128. }
  52129. for (var nde in nodes) {
  52130. node = nodes[nde];
  52131. if (node.jointName === jointName) {
  52132. return {
  52133. node: node,
  52134. id: nde
  52135. };
  52136. }
  52137. }
  52138. return null;
  52139. };
  52140. /**
  52141. * Checks if a nodes is in joints
  52142. */
  52143. var nodeIsInJoints = function (skins, id) {
  52144. for (var i = 0; i < skins.jointNames.length; i++) {
  52145. if (skins.jointNames[i] === id) {
  52146. return true;
  52147. }
  52148. }
  52149. return false;
  52150. };
  52151. /**
  52152. * Fills the nodes to root for bones and builds hierarchy
  52153. */
  52154. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  52155. // Creates nodes for root
  52156. for (var nde in gltfRuntime.nodes) {
  52157. var node = gltfRuntime.nodes[nde];
  52158. var id = nde;
  52159. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  52160. continue;
  52161. }
  52162. // Create node to root bone
  52163. var mat = configureBoneTransformation(node);
  52164. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  52165. bone.id = id;
  52166. nodesToRoot.push({ bone: bone, node: node, id: id });
  52167. }
  52168. // Parenting
  52169. for (var i = 0; i < nodesToRoot.length; i++) {
  52170. var nodeToRoot = nodesToRoot[i];
  52171. var children = nodeToRoot.node.children;
  52172. for (var j = 0; j < children.length; j++) {
  52173. var child = null;
  52174. for (var k = 0; k < nodesToRoot.length; k++) {
  52175. if (nodesToRoot[k].id === children[j]) {
  52176. child = nodesToRoot[k];
  52177. break;
  52178. }
  52179. }
  52180. if (child) {
  52181. child.bone._parent = nodeToRoot.bone;
  52182. nodeToRoot.bone.children.push(child.bone);
  52183. }
  52184. }
  52185. }
  52186. };
  52187. var printMat = function (m) {
  52188. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  52189. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  52190. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  52191. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  52192. };
  52193. /**
  52194. * Imports a skeleton
  52195. */
  52196. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  52197. if (!newSkeleton) {
  52198. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  52199. }
  52200. if (!skins.babylonSkeleton) {
  52201. return newSkeleton;
  52202. }
  52203. // Matrices
  52204. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  52205. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52206. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  52207. // Find the root bones
  52208. var nodesToRoot = [];
  52209. var nodesToRootToAdd = [];
  52210. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  52211. newSkeleton.bones = [];
  52212. // Joints
  52213. for (var i = 0; i < skins.jointNames.length; i++) {
  52214. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  52215. var node = jointNode.node;
  52216. if (!node) {
  52217. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  52218. continue;
  52219. }
  52220. var id = jointNode.id;
  52221. // Optimize, if the bone already exists...
  52222. var existingBone = gltfRuntime.scene.getBoneByID(id);
  52223. if (existingBone) {
  52224. newSkeleton.bones.push(existingBone);
  52225. continue;
  52226. }
  52227. // Search for parent bone
  52228. var foundBone = false;
  52229. var parentBone = null;
  52230. for (var j = 0; j < i; j++) {
  52231. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  52232. if (!joint) {
  52233. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  52234. continue;
  52235. }
  52236. var children = joint.children;
  52237. if (!children) {
  52238. continue;
  52239. }
  52240. foundBone = false;
  52241. for (var k = 0; k < children.length; k++) {
  52242. if (children[k] === id) {
  52243. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  52244. foundBone = true;
  52245. break;
  52246. }
  52247. }
  52248. if (foundBone) {
  52249. break;
  52250. }
  52251. }
  52252. // Create bone
  52253. var mat = configureBoneTransformation(node);
  52254. if (!parentBone && nodesToRoot.length > 0) {
  52255. parentBone = getNodeToRoot(nodesToRoot, id);
  52256. if (parentBone) {
  52257. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  52258. nodesToRootToAdd.push(parentBone);
  52259. }
  52260. }
  52261. }
  52262. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  52263. bone.id = id;
  52264. }
  52265. // Polish
  52266. var bones = newSkeleton.bones;
  52267. newSkeleton.bones = [];
  52268. for (var i = 0; i < skins.jointNames.length; i++) {
  52269. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  52270. if (!jointNode) {
  52271. continue;
  52272. }
  52273. for (var j = 0; j < bones.length; j++) {
  52274. if (bones[j].id === jointNode.id) {
  52275. newSkeleton.bones.push(bones[j]);
  52276. break;
  52277. }
  52278. }
  52279. }
  52280. newSkeleton.prepare();
  52281. // Finish
  52282. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  52283. newSkeleton.bones.push(nodesToRootToAdd[i]);
  52284. }
  52285. return newSkeleton;
  52286. };
  52287. /**
  52288. * Imports a mesh and its geometries
  52289. */
  52290. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  52291. if (!newMesh) {
  52292. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52293. newMesh.id = id;
  52294. }
  52295. if (!node.babylonNode) {
  52296. return newMesh;
  52297. }
  52298. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  52299. if (!newMesh.material) {
  52300. newMesh.material = multiMat;
  52301. }
  52302. var vertexData = new BABYLON.VertexData();
  52303. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  52304. var verticesStarts = [];
  52305. var verticesCounts = [];
  52306. var indexStarts = [];
  52307. var indexCounts = [];
  52308. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  52309. var meshID = meshes[meshIndex];
  52310. var mesh = gltfRuntime.meshes[meshID];
  52311. if (!mesh) {
  52312. continue;
  52313. }
  52314. // Positions, normals and UVs
  52315. for (var i = 0; i < mesh.primitives.length; i++) {
  52316. // Temporary vertex data
  52317. var tempVertexData = new BABYLON.VertexData();
  52318. var primitive = mesh.primitives[i];
  52319. if (primitive.mode !== 4) {
  52320. // continue;
  52321. }
  52322. var attributes = primitive.attributes;
  52323. var accessor = null;
  52324. var buffer = null;
  52325. // Set positions, normal and uvs
  52326. for (var semantic in attributes) {
  52327. // Link accessor and buffer view
  52328. accessor = gltfRuntime.accessors[attributes[semantic]];
  52329. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52330. if (semantic === "NORMAL") {
  52331. tempVertexData.normals = new Float32Array(buffer.length);
  52332. tempVertexData.normals.set(buffer);
  52333. }
  52334. else if (semantic === "POSITION") {
  52335. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  52336. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  52337. for (var j = 0; j < buffer.length; j += 4) {
  52338. tempVertexData.positions[j] = buffer[j];
  52339. tempVertexData.positions[j + 1] = buffer[j + 1];
  52340. tempVertexData.positions[j + 2] = buffer[j + 2];
  52341. }
  52342. }
  52343. else {
  52344. tempVertexData.positions = new Float32Array(buffer.length);
  52345. tempVertexData.positions.set(buffer);
  52346. }
  52347. verticesCounts.push(tempVertexData.positions.length);
  52348. }
  52349. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  52350. var channel = Number(semantic.split("_")[1]);
  52351. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  52352. var uvs = new Float32Array(buffer.length);
  52353. uvs.set(buffer);
  52354. normalizeUVs(uvs);
  52355. tempVertexData.set(uvs, uvKind);
  52356. }
  52357. else if (semantic === "JOINT") {
  52358. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  52359. tempVertexData.matricesIndices.set(buffer);
  52360. }
  52361. else if (semantic === "WEIGHT") {
  52362. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  52363. tempVertexData.matricesWeights.set(buffer);
  52364. }
  52365. else if (semantic === "COLOR") {
  52366. tempVertexData.colors = new Float32Array(buffer.length);
  52367. tempVertexData.colors.set(buffer);
  52368. }
  52369. }
  52370. // Indices
  52371. accessor = gltfRuntime.accessors[primitive.indices];
  52372. if (accessor) {
  52373. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52374. tempVertexData.indices = new Int32Array(buffer.length);
  52375. tempVertexData.indices.set(buffer);
  52376. indexCounts.push(tempVertexData.indices.length);
  52377. }
  52378. else {
  52379. // Set indices on the fly
  52380. var indices = [];
  52381. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  52382. indices.push(j);
  52383. }
  52384. tempVertexData.indices = new Int32Array(indices);
  52385. indexCounts.push(tempVertexData.indices.length);
  52386. }
  52387. vertexData.merge(tempVertexData);
  52388. tempVertexData = undefined;
  52389. // Sub material
  52390. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  52391. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  52392. // Update vertices start and index start
  52393. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  52394. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  52395. }
  52396. }
  52397. // Apply geometry
  52398. geometry.setAllVerticesData(vertexData, false);
  52399. newMesh.computeWorldMatrix(true);
  52400. // Apply submeshes
  52401. newMesh.subMeshes = [];
  52402. var index = 0;
  52403. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  52404. var meshID = meshes[meshIndex];
  52405. var mesh = gltfRuntime.meshes[meshID];
  52406. if (!mesh) {
  52407. continue;
  52408. }
  52409. for (var i = 0; i < mesh.primitives.length; i++) {
  52410. if (mesh.primitives[i].mode !== 4) {
  52411. //continue;
  52412. }
  52413. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  52414. index++;
  52415. }
  52416. }
  52417. // Finish
  52418. return newMesh;
  52419. };
  52420. /**
  52421. * Configure node transformation from position, rotation and scaling
  52422. */
  52423. var configureNode = function (newNode, position, rotation, scaling) {
  52424. if (newNode.position) {
  52425. newNode.position = position;
  52426. }
  52427. if (newNode.rotationQuaternion || newNode.rotation) {
  52428. newNode.rotationQuaternion = rotation;
  52429. }
  52430. if (newNode.scaling) {
  52431. newNode.scaling = scaling;
  52432. }
  52433. };
  52434. /**
  52435. * Configures node from transformation matrix
  52436. */
  52437. var configureNodeFromMatrix = function (newNode, node, parent) {
  52438. if (node.matrix) {
  52439. var position = new BABYLON.Vector3(0, 0, 0);
  52440. var rotation = new BABYLON.Quaternion();
  52441. var scaling = new BABYLON.Vector3(0, 0, 0);
  52442. var mat = BABYLON.Matrix.FromArray(node.matrix);
  52443. mat.decompose(scaling, rotation, position);
  52444. configureNode(newNode, position, rotation, scaling);
  52445. }
  52446. else {
  52447. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  52448. }
  52449. newNode.computeWorldMatrix(true);
  52450. };
  52451. /**
  52452. * Imports a node
  52453. */
  52454. var importNode = function (gltfRuntime, node, id, parent) {
  52455. var lastNode = null;
  52456. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  52457. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  52458. return null;
  52459. }
  52460. }
  52461. // Meshes
  52462. if (node.skin) {
  52463. if (node.meshes) {
  52464. var skin = gltfRuntime.skins[node.skin];
  52465. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  52466. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  52467. if (newMesh.skeleton === null) {
  52468. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  52469. if (!skin.babylonSkeleton) {
  52470. skin.babylonSkeleton = newMesh.skeleton;
  52471. }
  52472. }
  52473. lastNode = newMesh;
  52474. }
  52475. }
  52476. else if (node.meshes) {
  52477. /**
  52478. * Improve meshes property
  52479. */
  52480. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  52481. lastNode = newMesh;
  52482. }
  52483. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52484. var light = gltfRuntime.lights[node.light];
  52485. if (light) {
  52486. if (light.type === "ambient") {
  52487. var ambienLight = light[light.type];
  52488. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52489. hemiLight.name = node.name;
  52490. if (ambienLight.color) {
  52491. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  52492. }
  52493. lastNode = hemiLight;
  52494. }
  52495. else if (light.type === "directional") {
  52496. var directionalLight = light[light.type];
  52497. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52498. dirLight.name = node.name;
  52499. if (directionalLight.color) {
  52500. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  52501. }
  52502. lastNode = dirLight;
  52503. }
  52504. else if (light.type === "point") {
  52505. var pointLight = light[light.type];
  52506. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52507. ptLight.name = node.name;
  52508. if (pointLight.color) {
  52509. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  52510. }
  52511. lastNode = ptLight;
  52512. }
  52513. else if (light.type === "spot") {
  52514. var spotLight = light[light.type];
  52515. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  52516. spLight.name = node.name;
  52517. if (spotLight.color) {
  52518. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  52519. }
  52520. if (spotLight.fallOfAngle) {
  52521. spLight.angle = spotLight.fallOfAngle;
  52522. }
  52523. if (spotLight.fallOffExponent) {
  52524. spLight.exponent = spotLight.fallOffExponent;
  52525. }
  52526. lastNode = spLight;
  52527. }
  52528. }
  52529. }
  52530. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52531. var camera = gltfRuntime.cameras[node.camera];
  52532. if (camera) {
  52533. if (camera.type === "orthographic") {
  52534. var orthographicCamera = camera[camera.type];
  52535. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52536. orthoCamera.name = node.name;
  52537. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  52538. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52539. lastNode = orthoCamera;
  52540. }
  52541. else if (camera.type === "perspective") {
  52542. var perspectiveCamera = camera[camera.type];
  52543. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52544. persCamera.name = node.name;
  52545. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52546. if (!perspectiveCamera.aspectRatio) {
  52547. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  52548. }
  52549. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  52550. persCamera.maxZ = perspectiveCamera.zfar;
  52551. persCamera.minZ = perspectiveCamera.znear;
  52552. }
  52553. lastNode = persCamera;
  52554. }
  52555. }
  52556. }
  52557. // Empty node
  52558. if (!node.jointName) {
  52559. if (node.babylonNode) {
  52560. return node.babylonNode;
  52561. }
  52562. else if (lastNode === null) {
  52563. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52564. node.babylonNode = dummy;
  52565. lastNode = dummy;
  52566. }
  52567. }
  52568. if (lastNode !== null) {
  52569. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  52570. configureNodeFromMatrix(lastNode, node, parent);
  52571. }
  52572. else {
  52573. var translation = node.translation || [0, 0, 0];
  52574. var rotation = node.rotation || [0, 0, 0, 1];
  52575. var scale = node.scale || [1, 1, 1];
  52576. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  52577. }
  52578. lastNode.updateCache(true);
  52579. node.babylonNode = lastNode;
  52580. }
  52581. return lastNode;
  52582. };
  52583. /**
  52584. * Traverses nodes and creates them
  52585. */
  52586. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  52587. var node = gltfRuntime.nodes[id];
  52588. var newNode = null;
  52589. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  52590. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  52591. meshIncluded = true;
  52592. }
  52593. else {
  52594. meshIncluded = false;
  52595. }
  52596. }
  52597. else {
  52598. meshIncluded = true;
  52599. }
  52600. if (!node.jointName && meshIncluded) {
  52601. newNode = importNode(gltfRuntime, node, id, parent);
  52602. if (newNode !== null) {
  52603. newNode.id = id;
  52604. newNode.parent = parent;
  52605. }
  52606. }
  52607. if (node.children) {
  52608. for (var i = 0; i < node.children.length; i++) {
  52609. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  52610. }
  52611. }
  52612. };
  52613. /**
  52614. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  52615. */
  52616. var postLoad = function (gltfRuntime) {
  52617. // Nodes
  52618. var currentScene = gltfRuntime.currentScene;
  52619. if (currentScene) {
  52620. for (var i = 0; i < currentScene.nodes.length; i++) {
  52621. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52622. }
  52623. }
  52624. else {
  52625. for (var thing in gltfRuntime.scenes) {
  52626. currentScene = gltfRuntime.scenes[thing];
  52627. for (var i = 0; i < currentScene.nodes.length; i++) {
  52628. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52629. }
  52630. }
  52631. }
  52632. // Set animations
  52633. loadAnimations(gltfRuntime);
  52634. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  52635. var skeleton = gltfRuntime.scene.skeletons[i];
  52636. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  52637. }
  52638. };
  52639. /**
  52640. * onBind shaderrs callback to set uniforms and matrices
  52641. */
  52642. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  52643. var materialValues = material.values || technique.parameters;
  52644. for (var unif in unTreatedUniforms) {
  52645. var uniform = unTreatedUniforms[unif];
  52646. var type = uniform.type;
  52647. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  52648. if (uniform.semantic && !uniform.source && !uniform.node) {
  52649. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  52650. }
  52651. else if (uniform.semantic && (uniform.source || uniform.node)) {
  52652. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  52653. if (source === null) {
  52654. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  52655. }
  52656. if (source === null) {
  52657. continue;
  52658. }
  52659. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  52660. }
  52661. }
  52662. else {
  52663. var value = materialValues[technique.uniforms[unif]];
  52664. if (!value) {
  52665. continue;
  52666. }
  52667. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52668. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  52669. if (texture === null || texture === undefined) {
  52670. continue;
  52671. }
  52672. shaderMaterial.getEffect().setTexture(unif, texture);
  52673. }
  52674. else {
  52675. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  52676. }
  52677. }
  52678. }
  52679. onSuccess(shaderMaterial);
  52680. };
  52681. /**
  52682. * Prepare uniforms to send the only one time
  52683. * Loads the appropriate textures
  52684. */
  52685. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  52686. var materialValues = material.values || technique.parameters;
  52687. var techniqueUniforms = technique.uniforms;
  52688. /**
  52689. * Prepare values here (not matrices)
  52690. */
  52691. for (var unif in unTreatedUniforms) {
  52692. var uniform = unTreatedUniforms[unif];
  52693. var type = uniform.type;
  52694. var value = materialValues[techniqueUniforms[unif]];
  52695. if (value === undefined) {
  52696. // In case the value is the same for all materials
  52697. value = uniform.value;
  52698. }
  52699. if (!value) {
  52700. continue;
  52701. }
  52702. var onLoadTexture = function (uniformName) {
  52703. return function (texture) {
  52704. if (uniform.value) {
  52705. // Static uniform
  52706. shaderMaterial.setTexture(uniformName, texture);
  52707. delete unTreatedUniforms[uniformName];
  52708. }
  52709. };
  52710. };
  52711. // Texture (sampler2D)
  52712. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52713. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  52714. }
  52715. else {
  52716. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  52717. // Static uniform
  52718. delete unTreatedUniforms[unif];
  52719. }
  52720. }
  52721. }
  52722. };
  52723. /**
  52724. * Shader compilation failed
  52725. */
  52726. var onShaderCompileError = function (program, shaderMaterial, onError) {
  52727. return function (effect, error) {
  52728. shaderMaterial.dispose(true);
  52729. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  52730. };
  52731. };
  52732. /**
  52733. * Shader compilation success
  52734. */
  52735. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  52736. return function (_) {
  52737. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  52738. shaderMaterial.onBind = function (mesh) {
  52739. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  52740. };
  52741. };
  52742. };
  52743. /**
  52744. * Returns the appropriate uniform if already handled by babylon
  52745. */
  52746. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  52747. for (var unif in technique.uniforms) {
  52748. var uniform = technique.uniforms[unif];
  52749. var uniformParameter = technique.parameters[uniform];
  52750. if (tokenizer.currentIdentifier === unif) {
  52751. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  52752. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52753. if (transformIndex !== -1) {
  52754. delete unTreatedUniforms[unif];
  52755. return babylonTransforms[transformIndex];
  52756. }
  52757. }
  52758. }
  52759. }
  52760. return tokenizer.currentIdentifier;
  52761. };
  52762. /**
  52763. * All shaders loaded. Create materials one by one
  52764. */
  52765. var importMaterials = function (gltfRuntime) {
  52766. // Create materials
  52767. for (var mat in gltfRuntime.materials) {
  52768. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  52769. }
  52770. };
  52771. /**
  52772. * Implementation of the base glTF spec
  52773. */
  52774. var GLTFLoaderBase = (function () {
  52775. function GLTFLoaderBase() {
  52776. }
  52777. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  52778. var gltfRuntime = {
  52779. extensions: {},
  52780. accessors: {},
  52781. buffers: {},
  52782. bufferViews: {},
  52783. meshes: {},
  52784. lights: {},
  52785. cameras: {},
  52786. nodes: {},
  52787. images: {},
  52788. textures: {},
  52789. shaders: {},
  52790. programs: {},
  52791. samplers: {},
  52792. techniques: {},
  52793. materials: {},
  52794. animations: {},
  52795. skins: {},
  52796. extensionsUsed: [],
  52797. scenes: {},
  52798. buffersCount: 0,
  52799. shaderscount: 0,
  52800. scene: scene,
  52801. rootUrl: rootUrl,
  52802. loadedBufferCount: 0,
  52803. loadedBufferViews: {},
  52804. loadedShaderCount: 0,
  52805. importOnlyMeshes: false,
  52806. dummyNodes: []
  52807. };
  52808. // Parse
  52809. if (parsedData.extensions) {
  52810. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  52811. }
  52812. if (parsedData.extensionsUsed) {
  52813. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  52814. }
  52815. if (parsedData.buffers) {
  52816. parseBuffers(parsedData.buffers, gltfRuntime);
  52817. }
  52818. if (parsedData.bufferViews) {
  52819. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  52820. }
  52821. if (parsedData.accessors) {
  52822. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  52823. }
  52824. if (parsedData.meshes) {
  52825. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  52826. }
  52827. if (parsedData.lights) {
  52828. parseObject(parsedData.lights, "lights", gltfRuntime);
  52829. }
  52830. if (parsedData.cameras) {
  52831. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  52832. }
  52833. if (parsedData.nodes) {
  52834. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  52835. }
  52836. if (parsedData.images) {
  52837. parseObject(parsedData.images, "images", gltfRuntime);
  52838. }
  52839. if (parsedData.textures) {
  52840. parseObject(parsedData.textures, "textures", gltfRuntime);
  52841. }
  52842. if (parsedData.shaders) {
  52843. parseShaders(parsedData.shaders, gltfRuntime);
  52844. }
  52845. if (parsedData.programs) {
  52846. parseObject(parsedData.programs, "programs", gltfRuntime);
  52847. }
  52848. if (parsedData.samplers) {
  52849. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  52850. }
  52851. if (parsedData.techniques) {
  52852. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  52853. }
  52854. if (parsedData.materials) {
  52855. parseObject(parsedData.materials, "materials", gltfRuntime);
  52856. }
  52857. if (parsedData.animations) {
  52858. parseObject(parsedData.animations, "animations", gltfRuntime);
  52859. }
  52860. if (parsedData.skins) {
  52861. parseObject(parsedData.skins, "skins", gltfRuntime);
  52862. }
  52863. if (parsedData.scenes) {
  52864. gltfRuntime.scenes = parsedData.scenes;
  52865. }
  52866. if (parsedData.scene && parsedData.scenes) {
  52867. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  52868. }
  52869. return gltfRuntime;
  52870. };
  52871. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  52872. var buffer = gltfRuntime.buffers[id];
  52873. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  52874. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  52875. }
  52876. else {
  52877. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  52878. onError(request.status + " " + request.statusText);
  52879. });
  52880. }
  52881. };
  52882. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  52883. var texture = gltfRuntime.textures[id];
  52884. if (!texture || !texture.source) {
  52885. onError(null);
  52886. return;
  52887. }
  52888. if (texture.babylonTexture) {
  52889. onSuccess(null);
  52890. return;
  52891. }
  52892. var source = gltfRuntime.images[texture.source];
  52893. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  52894. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  52895. }
  52896. else {
  52897. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  52898. onError(request.status + " " + request.statusText);
  52899. });
  52900. }
  52901. };
  52902. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  52903. var texture = gltfRuntime.textures[id];
  52904. if (texture.babylonTexture) {
  52905. onSuccess(texture.babylonTexture);
  52906. return;
  52907. }
  52908. var sampler = gltfRuntime.samplers[texture.sampler];
  52909. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  52910. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  52911. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  52912. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  52913. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  52914. var blob = new Blob([buffer]);
  52915. var blobURL = URL.createObjectURL(blob);
  52916. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  52917. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  52918. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  52919. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  52920. newTexture.name = id;
  52921. texture.babylonTexture = newTexture;
  52922. onSuccess(newTexture);
  52923. };
  52924. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  52925. var shader = gltfRuntime.shaders[id];
  52926. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  52927. var shaderString = atob(shader.uri.split(",")[1]);
  52928. onSuccess(shaderString);
  52929. }
  52930. else {
  52931. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  52932. onError(request.status + " " + request.statusText);
  52933. });
  52934. }
  52935. };
  52936. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  52937. var material = gltfRuntime.materials[id];
  52938. var technique = gltfRuntime.techniques[material.technique];
  52939. if (!technique) {
  52940. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  52941. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  52942. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52943. onSuccess(defaultMaterial);
  52944. return;
  52945. }
  52946. var program = gltfRuntime.programs[technique.program];
  52947. var states = technique.states;
  52948. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  52949. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  52950. var newVertexShader = "";
  52951. var newPixelShader = "";
  52952. var vertexTokenizer = new Tokenizer(vertexShader);
  52953. var pixelTokenizer = new Tokenizer(pixelShader);
  52954. var unTreatedUniforms = {};
  52955. var uniforms = [];
  52956. var attributes = [];
  52957. var samplers = [];
  52958. // Fill uniform, sampler2D and attributes
  52959. for (var unif in technique.uniforms) {
  52960. var uniform = technique.uniforms[unif];
  52961. var uniformParameter = technique.parameters[uniform];
  52962. unTreatedUniforms[unif] = uniformParameter;
  52963. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  52964. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52965. if (transformIndex !== -1) {
  52966. uniforms.push(babylonTransforms[transformIndex]);
  52967. delete unTreatedUniforms[unif];
  52968. }
  52969. else {
  52970. uniforms.push(unif);
  52971. }
  52972. }
  52973. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  52974. samplers.push(unif);
  52975. }
  52976. else {
  52977. uniforms.push(unif);
  52978. }
  52979. }
  52980. for (var attr in technique.attributes) {
  52981. var attribute = technique.attributes[attr];
  52982. var attributeParameter = technique.parameters[attribute];
  52983. if (attributeParameter.semantic) {
  52984. attributes.push(getAttribute(attributeParameter));
  52985. }
  52986. }
  52987. // Configure vertex shader
  52988. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  52989. var tokenType = vertexTokenizer.currentToken;
  52990. if (tokenType !== ETokenType.IDENTIFIER) {
  52991. newVertexShader += vertexTokenizer.currentString;
  52992. continue;
  52993. }
  52994. var foundAttribute = false;
  52995. for (var attr in technique.attributes) {
  52996. var attribute = technique.attributes[attr];
  52997. var attributeParameter = technique.parameters[attribute];
  52998. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  52999. newVertexShader += getAttribute(attributeParameter);
  53000. foundAttribute = true;
  53001. break;
  53002. }
  53003. }
  53004. if (foundAttribute) {
  53005. continue;
  53006. }
  53007. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  53008. }
  53009. // Configure pixel shader
  53010. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  53011. var tokenType = pixelTokenizer.currentToken;
  53012. if (tokenType !== ETokenType.IDENTIFIER) {
  53013. newPixelShader += pixelTokenizer.currentString;
  53014. continue;
  53015. }
  53016. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  53017. }
  53018. // Create shader material
  53019. var shaderPath = {
  53020. vertex: program.vertexShader + id,
  53021. fragment: program.fragmentShader + id
  53022. };
  53023. var options = {
  53024. attributes: attributes,
  53025. uniforms: uniforms,
  53026. samplers: samplers,
  53027. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  53028. };
  53029. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  53030. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  53031. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  53032. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  53033. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  53034. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  53035. if (states && states.functions) {
  53036. var functions = states.functions;
  53037. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  53038. shaderMaterial.backFaceCulling = false;
  53039. }
  53040. var blendFunc = functions.blendFuncSeparate;
  53041. if (blendFunc) {
  53042. 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) {
  53043. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  53044. }
  53045. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  53046. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  53047. }
  53048. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  53049. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  53050. }
  53051. 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) {
  53052. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  53053. }
  53054. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  53055. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  53056. }
  53057. 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) {
  53058. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  53059. }
  53060. }
  53061. }
  53062. };
  53063. return GLTFLoaderBase;
  53064. }());
  53065. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  53066. /**
  53067. * glTF V1 Loader
  53068. */
  53069. var GLTFLoader = (function () {
  53070. function GLTFLoader() {
  53071. }
  53072. GLTFLoader.RegisterExtension = function (extension) {
  53073. if (GLTFLoader.Extensions[extension.name]) {
  53074. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  53075. return;
  53076. }
  53077. GLTFLoader.Extensions[extension.name] = extension;
  53078. };
  53079. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53080. var _this = this;
  53081. scene.useRightHandedSystem = true;
  53082. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  53083. gltfRuntime.importOnlyMeshes = true;
  53084. if (meshesNames === "") {
  53085. gltfRuntime.importMeshesNames = [];
  53086. }
  53087. else if (typeof meshesNames === "string") {
  53088. gltfRuntime.importMeshesNames = [meshesNames];
  53089. }
  53090. else if (meshesNames && !(meshesNames instanceof Array)) {
  53091. gltfRuntime.importMeshesNames = [meshesNames];
  53092. }
  53093. else {
  53094. gltfRuntime.importMeshesNames = [];
  53095. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  53096. }
  53097. // Create nodes
  53098. _this._createNodes(gltfRuntime);
  53099. var meshes = [];
  53100. var skeletons = [];
  53101. // Fill arrays of meshes and skeletons
  53102. for (var nde in gltfRuntime.nodes) {
  53103. var node = gltfRuntime.nodes[nde];
  53104. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  53105. meshes.push(node.babylonNode);
  53106. }
  53107. }
  53108. for (var skl in gltfRuntime.skins) {
  53109. var skin = gltfRuntime.skins[skl];
  53110. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  53111. skeletons.push(skin.babylonSkeleton);
  53112. }
  53113. }
  53114. // Load buffers, shaders, materials, etc.
  53115. _this._loadBuffersAsync(gltfRuntime, function () {
  53116. _this._loadShadersAsync(gltfRuntime, function () {
  53117. importMaterials(gltfRuntime);
  53118. postLoad(gltfRuntime);
  53119. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  53120. onSuccess(meshes, null, skeletons);
  53121. }
  53122. });
  53123. }, onProgress);
  53124. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  53125. onSuccess(meshes, null, skeletons);
  53126. }
  53127. }, onError);
  53128. return true;
  53129. };
  53130. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53131. var _this = this;
  53132. scene.useRightHandedSystem = true;
  53133. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  53134. // Load runtime extensios
  53135. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  53136. // Create nodes
  53137. _this._createNodes(gltfRuntime);
  53138. // Load buffers, shaders, materials, etc.
  53139. _this._loadBuffersAsync(gltfRuntime, function () {
  53140. _this._loadShadersAsync(gltfRuntime, function () {
  53141. importMaterials(gltfRuntime);
  53142. postLoad(gltfRuntime);
  53143. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  53144. onSuccess();
  53145. }
  53146. });
  53147. });
  53148. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  53149. onSuccess();
  53150. }
  53151. }, onError);
  53152. }, onError);
  53153. };
  53154. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  53155. var hasShaders = false;
  53156. var processShader = function (sha, shader) {
  53157. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  53158. gltfRuntime.loadedShaderCount++;
  53159. if (shaderString) {
  53160. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  53161. }
  53162. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  53163. onload();
  53164. }
  53165. }, function () {
  53166. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  53167. });
  53168. };
  53169. for (var sha in gltfRuntime.shaders) {
  53170. hasShaders = true;
  53171. var shader = gltfRuntime.shaders[sha];
  53172. if (shader) {
  53173. processShader.bind(this, sha, shader)();
  53174. }
  53175. else {
  53176. BABYLON.Tools.Error("No shader named: " + sha);
  53177. }
  53178. }
  53179. if (!hasShaders) {
  53180. onload();
  53181. }
  53182. };
  53183. ;
  53184. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  53185. var hasBuffers = false;
  53186. var processBuffer = function (buf, buffer) {
  53187. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  53188. gltfRuntime.loadedBufferCount++;
  53189. if (bufferView) {
  53190. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  53191. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  53192. }
  53193. gltfRuntime.loadedBufferViews[buf] = bufferView;
  53194. }
  53195. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  53196. onLoad();
  53197. }
  53198. }, function () {
  53199. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  53200. });
  53201. };
  53202. for (var buf in gltfRuntime.buffers) {
  53203. hasBuffers = true;
  53204. var buffer = gltfRuntime.buffers[buf];
  53205. if (buffer) {
  53206. processBuffer.bind(this, buf, buffer)();
  53207. }
  53208. else {
  53209. BABYLON.Tools.Error("No buffer named: " + buf);
  53210. }
  53211. }
  53212. if (!hasBuffers) {
  53213. onLoad();
  53214. }
  53215. };
  53216. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  53217. var currentScene = gltfRuntime.currentScene;
  53218. if (currentScene) {
  53219. // Only one scene even if multiple scenes are defined
  53220. for (var i = 0; i < currentScene.nodes.length; i++) {
  53221. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  53222. }
  53223. }
  53224. else {
  53225. // Load all scenes
  53226. for (var thing in gltfRuntime.scenes) {
  53227. currentScene = gltfRuntime.scenes[thing];
  53228. for (var i = 0; i < currentScene.nodes.length; i++) {
  53229. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  53230. }
  53231. }
  53232. }
  53233. };
  53234. GLTFLoader.Extensions = {};
  53235. return GLTFLoader;
  53236. }());
  53237. GLTF1.GLTFLoader = GLTFLoader;
  53238. ;
  53239. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  53240. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53241. })(BABYLON || (BABYLON = {}));
  53242. //# sourceMappingURL=babylon.glTFLoader.js.map
  53243. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53244. var BABYLON;
  53245. (function (BABYLON) {
  53246. var GLTF1;
  53247. (function (GLTF1) {
  53248. /**
  53249. * Utils functions for GLTF
  53250. */
  53251. var GLTFUtils = (function () {
  53252. function GLTFUtils() {
  53253. }
  53254. /**
  53255. * Sets the given "parameter" matrix
  53256. * @param scene: the {BABYLON.Scene} object
  53257. * @param source: the source node where to pick the matrix
  53258. * @param parameter: the GLTF technique parameter
  53259. * @param uniformName: the name of the shader's uniform
  53260. * @param shaderMaterial: the shader material
  53261. */
  53262. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  53263. var mat = null;
  53264. if (parameter.semantic === "MODEL") {
  53265. mat = source.getWorldMatrix();
  53266. }
  53267. else if (parameter.semantic === "PROJECTION") {
  53268. mat = scene.getProjectionMatrix();
  53269. }
  53270. else if (parameter.semantic === "VIEW") {
  53271. mat = scene.getViewMatrix();
  53272. }
  53273. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  53274. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  53275. }
  53276. else if (parameter.semantic === "MODELVIEW") {
  53277. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  53278. }
  53279. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  53280. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  53281. }
  53282. else if (parameter.semantic === "MODELINVERSE") {
  53283. mat = source.getWorldMatrix().invert();
  53284. }
  53285. else if (parameter.semantic === "VIEWINVERSE") {
  53286. mat = scene.getViewMatrix().invert();
  53287. }
  53288. else if (parameter.semantic === "PROJECTIONINVERSE") {
  53289. mat = scene.getProjectionMatrix().invert();
  53290. }
  53291. else if (parameter.semantic === "MODELVIEWINVERSE") {
  53292. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  53293. }
  53294. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  53295. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  53296. }
  53297. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  53298. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  53299. }
  53300. else {
  53301. debugger;
  53302. }
  53303. switch (parameter.type) {
  53304. case GLTF1.EParameterType.FLOAT_MAT2:
  53305. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  53306. break;
  53307. case GLTF1.EParameterType.FLOAT_MAT3:
  53308. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  53309. break;
  53310. case GLTF1.EParameterType.FLOAT_MAT4:
  53311. shaderMaterial.setMatrix(uniformName, mat);
  53312. break;
  53313. default: break;
  53314. }
  53315. };
  53316. /**
  53317. * Sets the given "parameter" matrix
  53318. * @param shaderMaterial: the shader material
  53319. * @param uniform: the name of the shader's uniform
  53320. * @param value: the value of the uniform
  53321. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  53322. */
  53323. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  53324. switch (type) {
  53325. case GLTF1.EParameterType.FLOAT:
  53326. shaderMaterial.setFloat(uniform, value);
  53327. return true;
  53328. case GLTF1.EParameterType.FLOAT_VEC2:
  53329. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  53330. return true;
  53331. case GLTF1.EParameterType.FLOAT_VEC3:
  53332. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  53333. return true;
  53334. case GLTF1.EParameterType.FLOAT_VEC4:
  53335. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  53336. return true;
  53337. default: return false;
  53338. }
  53339. };
  53340. /**
  53341. * If the uri is a base64 string
  53342. * @param uri: the uri to test
  53343. */
  53344. GLTFUtils.IsBase64 = function (uri) {
  53345. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  53346. };
  53347. /**
  53348. * Decode the base64 uri
  53349. * @param uri: the uri to decode
  53350. */
  53351. GLTFUtils.DecodeBase64 = function (uri) {
  53352. var decodedString = atob(uri.split(",")[1]);
  53353. var bufferLength = decodedString.length;
  53354. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  53355. for (var i = 0; i < bufferLength; i++) {
  53356. bufferView[i] = decodedString.charCodeAt(i);
  53357. }
  53358. return bufferView.buffer;
  53359. };
  53360. /**
  53361. * Returns the wrap mode of the texture
  53362. * @param mode: the mode value
  53363. */
  53364. GLTFUtils.GetWrapMode = function (mode) {
  53365. switch (mode) {
  53366. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  53367. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  53368. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  53369. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  53370. }
  53371. };
  53372. /**
  53373. * Returns the byte stride giving an accessor
  53374. * @param accessor: the GLTF accessor objet
  53375. */
  53376. GLTFUtils.GetByteStrideFromType = function (accessor) {
  53377. // Needs this function since "byteStride" isn't requiered in glTF format
  53378. var type = accessor.type;
  53379. switch (type) {
  53380. case "VEC2": return 2;
  53381. case "VEC3": return 3;
  53382. case "VEC4": return 4;
  53383. case "MAT2": return 4;
  53384. case "MAT3": return 9;
  53385. case "MAT4": return 16;
  53386. default: return 1;
  53387. }
  53388. };
  53389. /**
  53390. * Returns the texture filter mode giving a mode value
  53391. * @param mode: the filter mode value
  53392. */
  53393. GLTFUtils.GetTextureFilterMode = function (mode) {
  53394. switch (mode) {
  53395. case GLTF1.ETextureFilterType.LINEAR:
  53396. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  53397. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  53398. case GLTF1.ETextureFilterType.NEAREST:
  53399. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  53400. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  53401. }
  53402. };
  53403. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  53404. var byteOffset = bufferView.byteOffset + byteOffset;
  53405. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  53406. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  53407. throw new Error("Buffer access is out of range");
  53408. }
  53409. var buffer = loadedBufferView.buffer;
  53410. byteOffset += loadedBufferView.byteOffset;
  53411. switch (componentType) {
  53412. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  53413. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  53414. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  53415. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  53416. default: return new Float32Array(buffer, byteOffset, byteLength);
  53417. }
  53418. };
  53419. /**
  53420. * Returns a buffer from its accessor
  53421. * @param gltfRuntime: the GLTF runtime
  53422. * @param accessor: the GLTF accessor
  53423. */
  53424. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  53425. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  53426. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  53427. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  53428. };
  53429. /**
  53430. * Decodes a buffer view into a string
  53431. * @param view: the buffer view
  53432. */
  53433. GLTFUtils.DecodeBufferToText = function (view) {
  53434. var result = "";
  53435. var length = view.byteLength;
  53436. for (var i = 0; i < length; ++i) {
  53437. result += String.fromCharCode(view[i]);
  53438. }
  53439. return result;
  53440. };
  53441. /**
  53442. * Returns the default material of gltf. Related to
  53443. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  53444. * @param scene: the Babylon.js scene
  53445. */
  53446. GLTFUtils.GetDefaultMaterial = function (scene) {
  53447. if (!GLTFUtils._DefaultMaterial) {
  53448. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  53449. "precision highp float;",
  53450. "",
  53451. "uniform mat4 worldView;",
  53452. "uniform mat4 projection;",
  53453. "",
  53454. "attribute vec3 position;",
  53455. "",
  53456. "void main(void)",
  53457. "{",
  53458. " gl_Position = projection * worldView * vec4(position, 1.0);",
  53459. "}"
  53460. ].join("\n");
  53461. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  53462. "precision highp float;",
  53463. "",
  53464. "uniform vec4 u_emission;",
  53465. "",
  53466. "void main(void)",
  53467. "{",
  53468. " gl_FragColor = u_emission;",
  53469. "}"
  53470. ].join("\n");
  53471. var shaderPath = {
  53472. vertex: "GLTFDefaultMaterial",
  53473. fragment: "GLTFDefaultMaterial"
  53474. };
  53475. var options = {
  53476. attributes: ["position"],
  53477. uniforms: ["worldView", "projection", "u_emission"],
  53478. samplers: [],
  53479. needAlphaBlending: false
  53480. };
  53481. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  53482. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  53483. }
  53484. return GLTFUtils._DefaultMaterial;
  53485. };
  53486. // The GLTF default material
  53487. GLTFUtils._DefaultMaterial = null;
  53488. return GLTFUtils;
  53489. }());
  53490. GLTF1.GLTFUtils = GLTFUtils;
  53491. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53492. })(BABYLON || (BABYLON = {}));
  53493. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  53494. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53495. var BABYLON;
  53496. (function (BABYLON) {
  53497. var GLTF1;
  53498. (function (GLTF1) {
  53499. var GLTFLoaderExtension = (function () {
  53500. function GLTFLoaderExtension(name) {
  53501. this._name = name;
  53502. }
  53503. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  53504. get: function () {
  53505. return this._name;
  53506. },
  53507. enumerable: true,
  53508. configurable: true
  53509. });
  53510. /**
  53511. * Defines an override for loading the runtime
  53512. * Return true to stop further extensions from loading the runtime
  53513. */
  53514. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53515. return false;
  53516. };
  53517. /**
  53518. * Defines an onverride for creating gltf runtime
  53519. * Return true to stop further extensions from creating the runtime
  53520. */
  53521. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53522. return false;
  53523. };
  53524. /**
  53525. * Defines an override for loading buffers
  53526. * Return true to stop further extensions from loading this buffer
  53527. */
  53528. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53529. return false;
  53530. };
  53531. /**
  53532. * Defines an override for loading texture buffers
  53533. * Return true to stop further extensions from loading this texture data
  53534. */
  53535. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53536. return false;
  53537. };
  53538. /**
  53539. * Defines an override for creating textures
  53540. * Return true to stop further extensions from loading this texture
  53541. */
  53542. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53543. return false;
  53544. };
  53545. /**
  53546. * Defines an override for loading shader strings
  53547. * Return true to stop further extensions from loading this shader data
  53548. */
  53549. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53550. return false;
  53551. };
  53552. /**
  53553. * Defines an override for loading materials
  53554. * Return true to stop further extensions from loading this material
  53555. */
  53556. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53557. return false;
  53558. };
  53559. // ---------
  53560. // Utilities
  53561. // ---------
  53562. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53563. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53564. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  53565. }, function () {
  53566. setTimeout(function () {
  53567. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53568. });
  53569. });
  53570. };
  53571. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53572. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53573. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  53574. }, function () {
  53575. setTimeout(function () {
  53576. onSuccess();
  53577. });
  53578. });
  53579. };
  53580. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53581. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53582. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53583. }, function () {
  53584. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53585. });
  53586. };
  53587. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  53588. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  53589. };
  53590. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53591. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53592. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53593. }, function () {
  53594. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53595. });
  53596. };
  53597. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53598. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53599. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53600. }, function () {
  53601. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53602. });
  53603. };
  53604. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53605. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53606. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53607. }, function () {
  53608. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53609. });
  53610. };
  53611. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53612. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53613. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53614. }, function () {
  53615. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53616. });
  53617. };
  53618. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  53619. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  53620. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  53621. if (func(loaderExtension)) {
  53622. return;
  53623. }
  53624. }
  53625. defaultFunc();
  53626. };
  53627. return GLTFLoaderExtension;
  53628. }());
  53629. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  53630. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53631. })(BABYLON || (BABYLON = {}));
  53632. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  53633. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53634. var BABYLON;
  53635. (function (BABYLON) {
  53636. var GLTF1;
  53637. (function (GLTF1) {
  53638. var BinaryExtensionBufferName = "binary_glTF";
  53639. var EContentFormat;
  53640. (function (EContentFormat) {
  53641. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  53642. })(EContentFormat || (EContentFormat = {}));
  53643. ;
  53644. ;
  53645. ;
  53646. var GLTFBinaryExtension = (function (_super) {
  53647. __extends(GLTFBinaryExtension, _super);
  53648. function GLTFBinaryExtension() {
  53649. return _super.call(this, "KHR_binary_glTF") || this;
  53650. }
  53651. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53652. var extensionsUsed = data.json.extensionsUsed;
  53653. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  53654. return false;
  53655. }
  53656. this._bin = data.bin;
  53657. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53658. return true;
  53659. };
  53660. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53661. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  53662. return false;
  53663. }
  53664. if (id !== BinaryExtensionBufferName) {
  53665. return false;
  53666. }
  53667. onSuccess(this._bin);
  53668. return true;
  53669. };
  53670. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53671. var texture = gltfRuntime.textures[id];
  53672. var source = gltfRuntime.images[texture.source];
  53673. if (!source.extensions || !(this.name in source.extensions)) {
  53674. return false;
  53675. }
  53676. var sourceExt = source.extensions[this.name];
  53677. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  53678. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53679. onSuccess(buffer);
  53680. return true;
  53681. };
  53682. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53683. var shader = gltfRuntime.shaders[id];
  53684. if (!shader.extensions || !(this.name in shader.extensions)) {
  53685. return false;
  53686. }
  53687. var binaryExtensionShader = shader.extensions[this.name];
  53688. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  53689. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53690. setTimeout(function () {
  53691. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  53692. onSuccess(shaderString);
  53693. });
  53694. return true;
  53695. };
  53696. return GLTFBinaryExtension;
  53697. }(GLTF1.GLTFLoaderExtension));
  53698. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  53699. var BinaryReader = (function () {
  53700. function BinaryReader(arrayBuffer) {
  53701. this._arrayBuffer = arrayBuffer;
  53702. this._dataView = new DataView(arrayBuffer);
  53703. this._byteOffset = 0;
  53704. }
  53705. BinaryReader.prototype.getUint32 = function () {
  53706. var value = this._dataView.getUint32(this._byteOffset, true);
  53707. this._byteOffset += 4;
  53708. return value;
  53709. };
  53710. BinaryReader.prototype.getUint8Array = function (length) {
  53711. if (!length) {
  53712. length = this._arrayBuffer.byteLength - this._byteOffset;
  53713. }
  53714. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  53715. this._byteOffset += length;
  53716. return value;
  53717. };
  53718. return BinaryReader;
  53719. }());
  53720. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  53721. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53722. })(BABYLON || (BABYLON = {}));
  53723. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  53724. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53725. var BABYLON;
  53726. (function (BABYLON) {
  53727. var GLTF1;
  53728. (function (GLTF1) {
  53729. ;
  53730. ;
  53731. ;
  53732. var GLTFMaterialsCommonExtension = (function (_super) {
  53733. __extends(GLTFMaterialsCommonExtension, _super);
  53734. function GLTFMaterialsCommonExtension() {
  53735. return _super.call(this, "KHR_materials_common") || this;
  53736. }
  53737. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53738. if (!gltfRuntime.extensions)
  53739. return false;
  53740. var extension = gltfRuntime.extensions[this.name];
  53741. if (!extension)
  53742. return false;
  53743. // Create lights
  53744. var lights = extension.lights;
  53745. if (lights) {
  53746. for (var thing in lights) {
  53747. var light = lights[thing];
  53748. switch (light.type) {
  53749. case "ambient":
  53750. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  53751. var ambient = light.ambient;
  53752. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  53753. break;
  53754. case "point":
  53755. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  53756. var point = light.point;
  53757. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  53758. break;
  53759. case "directional":
  53760. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  53761. var directional = light.directional;
  53762. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  53763. break;
  53764. case "spot":
  53765. var spot = light.spot;
  53766. 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);
  53767. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  53768. break;
  53769. default:
  53770. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  53771. break;
  53772. }
  53773. }
  53774. }
  53775. return false;
  53776. };
  53777. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53778. var material = gltfRuntime.materials[id];
  53779. if (!material || !material.extensions)
  53780. return false;
  53781. var extension = material.extensions[this.name];
  53782. if (!extension)
  53783. return false;
  53784. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  53785. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  53786. if (extension.technique === "CONSTANT") {
  53787. standardMaterial.disableLighting = true;
  53788. }
  53789. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  53790. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  53791. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  53792. // Ambient
  53793. if (typeof extension.values.ambient === "string") {
  53794. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  53795. }
  53796. else {
  53797. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  53798. }
  53799. // Diffuse
  53800. if (typeof extension.values.diffuse === "string") {
  53801. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  53802. }
  53803. else {
  53804. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  53805. }
  53806. // Emission
  53807. if (typeof extension.values.emission === "string") {
  53808. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  53809. }
  53810. else {
  53811. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  53812. }
  53813. // Specular
  53814. if (typeof extension.values.specular === "string") {
  53815. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  53816. }
  53817. else {
  53818. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  53819. }
  53820. return true;
  53821. };
  53822. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  53823. // Create buffer from texture url
  53824. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  53825. // Create texture from buffer
  53826. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  53827. }, onError);
  53828. };
  53829. return GLTFMaterialsCommonExtension;
  53830. }(GLTF1.GLTFLoaderExtension));
  53831. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  53832. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  53833. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53834. })(BABYLON || (BABYLON = {}));
  53835. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  53836. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53837. var BABYLON;
  53838. (function (BABYLON) {
  53839. var GLTF2;
  53840. (function (GLTF2) {
  53841. /**
  53842. * Enums
  53843. */
  53844. var EComponentType;
  53845. (function (EComponentType) {
  53846. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  53847. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  53848. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  53849. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  53850. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  53851. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  53852. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  53853. var EMeshPrimitiveMode;
  53854. (function (EMeshPrimitiveMode) {
  53855. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  53856. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  53857. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  53858. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  53859. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  53860. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  53861. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  53862. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  53863. var ETextureMagFilter;
  53864. (function (ETextureMagFilter) {
  53865. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  53866. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  53867. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  53868. var ETextureMinFilter;
  53869. (function (ETextureMinFilter) {
  53870. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  53871. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  53872. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  53873. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  53874. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  53875. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  53876. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  53877. var ETextureWrapMode;
  53878. (function (ETextureWrapMode) {
  53879. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  53880. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  53881. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  53882. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  53883. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  53884. })(BABYLON || (BABYLON = {}));
  53885. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  53886. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53887. var BABYLON;
  53888. (function (BABYLON) {
  53889. var GLTF2;
  53890. (function (GLTF2) {
  53891. var GLTFLoader = (function () {
  53892. function GLTFLoader(parent) {
  53893. this._renderReady = false;
  53894. this._disposed = false;
  53895. this._objectURLs = new Array();
  53896. this._blockPendingTracking = false;
  53897. // Observable with boolean indicating success or error.
  53898. this._renderReadyObservable = new BABYLON.Observable();
  53899. // Count of pending work that needs to complete before the asset is rendered.
  53900. this._renderPendingCount = 0;
  53901. // Count of pending work that needs to complete before the loader is cleared.
  53902. this._loaderPendingCount = 0;
  53903. this._parent = parent;
  53904. }
  53905. GLTFLoader.RegisterExtension = function (extension) {
  53906. if (GLTFLoader.Extensions[extension.name]) {
  53907. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  53908. return;
  53909. }
  53910. GLTFLoader.Extensions[extension.name] = extension;
  53911. // Keep the order of registration so that extensions registered first are called first.
  53912. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  53913. };
  53914. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  53915. get: function () {
  53916. return this._gltf;
  53917. },
  53918. enumerable: true,
  53919. configurable: true
  53920. });
  53921. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  53922. get: function () {
  53923. return this._babylonScene;
  53924. },
  53925. enumerable: true,
  53926. configurable: true
  53927. });
  53928. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  53929. if (this._renderReady) {
  53930. func();
  53931. }
  53932. else {
  53933. this._renderReadyObservable.add(func);
  53934. }
  53935. };
  53936. GLTFLoader.prototype.dispose = function () {
  53937. if (this._disposed) {
  53938. return;
  53939. }
  53940. this._disposed = true;
  53941. // Revoke object urls created during load
  53942. this._objectURLs.forEach(function (url) { return URL.revokeObjectURL(url); });
  53943. this._objectURLs.length = 0;
  53944. this._gltf = undefined;
  53945. this._babylonScene = undefined;
  53946. this._rootUrl = undefined;
  53947. this._defaultMaterial = undefined;
  53948. this._successCallback = undefined;
  53949. this._errorCallback = undefined;
  53950. this._renderReady = false;
  53951. this._renderReadyObservable.clear();
  53952. this._renderPendingCount = 0;
  53953. this._loaderPendingCount = 0;
  53954. };
  53955. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53956. var _this = this;
  53957. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  53958. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  53959. }, onProgress, onError);
  53960. };
  53961. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53962. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  53963. };
  53964. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53965. this._loadData(data);
  53966. this._babylonScene = scene;
  53967. this._rootUrl = rootUrl;
  53968. this._successCallback = onSuccess;
  53969. this._progressCallback = onProgress;
  53970. this._errorCallback = onError;
  53971. this.addPendingData(this);
  53972. this._loadScene(nodeNames);
  53973. this._loadAnimations();
  53974. this.removePendingData(this);
  53975. };
  53976. GLTFLoader.prototype._onError = function (message) {
  53977. this._errorCallback(message);
  53978. this.dispose();
  53979. };
  53980. GLTFLoader.prototype._onProgress = function (event) {
  53981. this._progressCallback(event);
  53982. };
  53983. GLTFLoader.prototype._onRenderReady = function () {
  53984. switch (this._parent.coordinateSystemMode) {
  53985. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  53986. if (!this._babylonScene.useRightHandedSystem) {
  53987. this._addRightHandToLeftHandRootTransform();
  53988. }
  53989. break;
  53990. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  53991. // do nothing
  53992. break;
  53993. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  53994. this._babylonScene.useRightHandedSystem = true;
  53995. break;
  53996. default:
  53997. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  53998. break;
  53999. }
  54000. this._showMeshes();
  54001. this._startAnimations();
  54002. this._successCallback();
  54003. this._renderReadyObservable.notifyObservers(this);
  54004. };
  54005. GLTFLoader.prototype._onLoaderComplete = function () {
  54006. if (this._parent.onComplete) {
  54007. this._parent.onComplete();
  54008. }
  54009. };
  54010. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  54011. if (this._parent.onFirstLODComplete) {
  54012. this._parent.onFirstLODComplete();
  54013. }
  54014. };
  54015. GLTFLoader.prototype._loadData = function (data) {
  54016. this._gltf = data.json;
  54017. var binaryBuffer;
  54018. var buffers = this._gltf.buffers;
  54019. if (buffers.length > 0 && buffers[0].uri === undefined) {
  54020. binaryBuffer = buffers[0];
  54021. }
  54022. if (data.bin) {
  54023. if (binaryBuffer) {
  54024. if (binaryBuffer.byteLength != data.bin.byteLength) {
  54025. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  54026. }
  54027. }
  54028. else {
  54029. BABYLON.Tools.Warn("Unexpected BIN chunk");
  54030. }
  54031. binaryBuffer.loadedData = data.bin;
  54032. }
  54033. };
  54034. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  54035. var rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  54036. rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  54037. rootMesh.rotation.y = Math.PI;
  54038. var nodes = this._gltf.nodes;
  54039. for (var i = 0; i < nodes.length; i++) {
  54040. var mesh = nodes[i].babylonMesh;
  54041. if (mesh && !mesh.parent) {
  54042. mesh.parent = rootMesh;
  54043. }
  54044. }
  54045. };
  54046. GLTFLoader.prototype._getMeshes = function () {
  54047. var meshes = [];
  54048. var nodes = this._gltf.nodes;
  54049. if (nodes) {
  54050. nodes.forEach(function (node) {
  54051. if (node.babylonMesh) {
  54052. meshes.push(node.babylonMesh);
  54053. }
  54054. });
  54055. }
  54056. return meshes;
  54057. };
  54058. GLTFLoader.prototype._getSkeletons = function () {
  54059. var skeletons = [];
  54060. var skins = this._gltf.skins;
  54061. if (skins) {
  54062. skins.forEach(function (skin) {
  54063. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  54064. skeletons.push(skin.babylonSkeleton);
  54065. }
  54066. });
  54067. }
  54068. return skeletons;
  54069. };
  54070. GLTFLoader.prototype._getAnimationTargets = function () {
  54071. var targets = [];
  54072. var animations = this._gltf.animations;
  54073. if (animations) {
  54074. animations.forEach(function (animation) {
  54075. targets.push.apply(targets, animation.targets);
  54076. });
  54077. }
  54078. return targets;
  54079. };
  54080. GLTFLoader.prototype._showMeshes = function () {
  54081. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  54082. };
  54083. GLTFLoader.prototype._startAnimations = function () {
  54084. var _this = this;
  54085. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  54086. };
  54087. GLTFLoader.prototype._loadScene = function (nodeNames) {
  54088. var _this = this;
  54089. var scene = this._gltf.scenes[this._gltf.scene || 0];
  54090. var nodeIndices = scene.nodes;
  54091. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  54092. node.index = index;
  54093. node.parent = parentNode;
  54094. return true;
  54095. });
  54096. var materials = this._gltf.materials;
  54097. if (materials) {
  54098. materials.forEach(function (material, index) { return material.index = index; });
  54099. }
  54100. if (nodeNames) {
  54101. if (!(nodeNames instanceof Array)) {
  54102. nodeNames = [nodeNames];
  54103. }
  54104. var filteredNodeIndices = new Array();
  54105. this._traverseNodes(nodeIndices, function (node) {
  54106. if (nodeNames.indexOf(node.name) === -1) {
  54107. return true;
  54108. }
  54109. filteredNodeIndices.push(node.index);
  54110. return false;
  54111. });
  54112. nodeIndices = filteredNodeIndices;
  54113. }
  54114. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  54115. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  54116. };
  54117. GLTFLoader.prototype._loadSkin = function (node) {
  54118. var _this = this;
  54119. if (node.skin !== undefined) {
  54120. var skin = this._gltf.skins[node.skin];
  54121. var skeletonId = "skeleton" + node.skin;
  54122. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  54123. skin.index = node.skin;
  54124. for (var i = 0; i < skin.joints.length; i++) {
  54125. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  54126. }
  54127. if (skin.skeleton === undefined) {
  54128. // TODO: handle when skeleton is not defined
  54129. throw new Error("Not implemented");
  54130. }
  54131. if (skin.inverseBindMatrices === undefined) {
  54132. // TODO: handle when inverse bind matrices are not defined
  54133. throw new Error("Not implemented");
  54134. }
  54135. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  54136. this._loadAccessorAsync(accessor, function (data) {
  54137. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  54138. });
  54139. }
  54140. return true;
  54141. };
  54142. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  54143. var jointIndex = skin.joints.indexOf(node.index);
  54144. if (jointIndex === -1) {
  54145. this._createBone(node, skin);
  54146. }
  54147. var babylonBone = node.babylonSkinToBones[skin.index];
  54148. // TODO: explain the math
  54149. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  54150. matrix.invertToRef(matrix);
  54151. if (parentNode) {
  54152. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  54153. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  54154. }
  54155. babylonBone.updateMatrix(matrix);
  54156. return true;
  54157. };
  54158. GLTFLoader.prototype._createBone = function (node, skin) {
  54159. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  54160. node.babylonSkinToBones = node.babylonSkinToBones || {};
  54161. node.babylonSkinToBones[skin.index] = babylonBone;
  54162. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  54163. node.babylonAnimationTargets.push(babylonBone);
  54164. return babylonBone;
  54165. };
  54166. GLTFLoader.prototype._loadMesh = function (node) {
  54167. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  54168. babylonMesh.isVisible = false;
  54169. this._loadTransform(node, babylonMesh);
  54170. if (node.mesh !== undefined) {
  54171. var mesh = this._gltf.meshes[node.mesh];
  54172. this._loadMeshData(node, mesh, babylonMesh);
  54173. }
  54174. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  54175. node.babylonMesh = babylonMesh;
  54176. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  54177. node.babylonAnimationTargets.push(node.babylonMesh);
  54178. if (node.skin !== undefined) {
  54179. var skin = this._gltf.skins[node.skin];
  54180. babylonMesh.skeleton = skin.babylonSkeleton;
  54181. }
  54182. if (node.camera !== undefined) {
  54183. // TODO: handle cameras
  54184. }
  54185. return true;
  54186. };
  54187. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  54188. var _this = this;
  54189. babylonMesh.name = mesh.name || babylonMesh.name;
  54190. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  54191. babylonMesh.material = babylonMultiMaterial;
  54192. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  54193. var vertexData = new BABYLON.VertexData();
  54194. vertexData.positions = [];
  54195. vertexData.indices = [];
  54196. var subMeshInfos = [];
  54197. var loadedPrimitives = 0;
  54198. var totalPrimitives = mesh.primitives.length;
  54199. var _loop_1 = function (i) {
  54200. var primitive = mesh.primitives[i];
  54201. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  54202. // TODO: handle other primitive modes
  54203. throw new Error("Not implemented");
  54204. }
  54205. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  54206. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  54207. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  54208. subMeshInfos.push({
  54209. materialIndex: i,
  54210. verticesStart: vertexData.positions.length,
  54211. verticesCount: subVertexData.positions.length,
  54212. indicesStart: vertexData.indices.length,
  54213. indicesCount: subVertexData.indices.length,
  54214. loadMaterial: function () {
  54215. if (primitive.material === undefined) {
  54216. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  54217. }
  54218. else {
  54219. var material = _this._gltf.materials[primitive.material];
  54220. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  54221. if (isNew && _this._parent.onMaterialLoaded) {
  54222. _this._parent.onMaterialLoaded(babylonMaterial);
  54223. }
  54224. if (_this._parent.onBeforeMaterialReadyAsync) {
  54225. _this.addLoaderPendingData(material);
  54226. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  54227. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  54228. _this.removeLoaderPendingData(material);
  54229. });
  54230. }
  54231. else {
  54232. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  54233. }
  54234. });
  54235. }
  54236. }
  54237. });
  54238. vertexData.merge(subVertexData);
  54239. if (++loadedPrimitives === totalPrimitives) {
  54240. geometry.setAllVerticesData(vertexData, false);
  54241. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  54242. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  54243. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  54244. babylonMesh.subMeshes = [];
  54245. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  54246. }
  54247. });
  54248. };
  54249. var this_1 = this;
  54250. for (var i = 0; i < totalPrimitives; i++) {
  54251. _loop_1(i);
  54252. }
  54253. };
  54254. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  54255. var _this = this;
  54256. var attributes = primitive.attributes;
  54257. if (!attributes) {
  54258. this._onError("Primitive has no attributes");
  54259. return;
  54260. }
  54261. var vertexData = new BABYLON.VertexData();
  54262. var loadedAttributes = 0;
  54263. var totalAttributes = Object.keys(attributes).length;
  54264. var _loop_2 = function (semantic) {
  54265. accessor = this_2._gltf.accessors[attributes[semantic]];
  54266. this_2._loadAccessorAsync(accessor, function (data) {
  54267. switch (semantic) {
  54268. case "NORMAL":
  54269. vertexData.normals = data;
  54270. break;
  54271. case "POSITION":
  54272. vertexData.positions = data;
  54273. break;
  54274. case "TANGENT":
  54275. vertexData.tangents = data;
  54276. break;
  54277. case "TEXCOORD_0":
  54278. vertexData.uvs = data;
  54279. break;
  54280. case "TEXCOORD_1":
  54281. vertexData.uvs2 = data;
  54282. break;
  54283. case "JOINTS_0":
  54284. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  54285. break;
  54286. case "WEIGHTS_0":
  54287. vertexData.matricesWeights = data;
  54288. break;
  54289. case "COLOR_0":
  54290. vertexData.colors = data;
  54291. break;
  54292. default:
  54293. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  54294. break;
  54295. }
  54296. if (++loadedAttributes === totalAttributes) {
  54297. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  54298. if (indicesAccessor) {
  54299. _this._loadAccessorAsync(indicesAccessor, function (data) {
  54300. vertexData.indices = data;
  54301. onSuccess(vertexData);
  54302. });
  54303. }
  54304. else {
  54305. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  54306. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  54307. onSuccess(vertexData);
  54308. }
  54309. }
  54310. });
  54311. };
  54312. var this_2 = this, accessor;
  54313. for (var semantic in attributes) {
  54314. _loop_2(semantic);
  54315. }
  54316. };
  54317. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  54318. var targets = primitive.targets;
  54319. if (!targets) {
  54320. return;
  54321. }
  54322. if (!babylonMesh.morphTargetManager) {
  54323. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  54324. }
  54325. for (var index = 0; index < targets.length; index++) {
  54326. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  54327. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  54328. }
  54329. };
  54330. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  54331. var targets = primitive.targets;
  54332. if (!targets) {
  54333. return;
  54334. }
  54335. var _loop_3 = function () {
  54336. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  54337. attributes = targets[index];
  54338. var _loop_4 = function (semantic) {
  54339. accessor = this_3._gltf.accessors[attributes[semantic]];
  54340. this_3._loadAccessorAsync(accessor, function (data) {
  54341. if (accessor.name) {
  54342. babylonMorphTarget.name = accessor.name;
  54343. }
  54344. // glTF stores morph target information as deltas while babylon.js expects the final data.
  54345. // As a result we have to add the original data to the delta to calculate the final data.
  54346. var values = data;
  54347. switch (semantic) {
  54348. case "NORMAL":
  54349. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  54350. babylonMorphTarget.setNormals(values);
  54351. break;
  54352. case "POSITION":
  54353. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  54354. babylonMorphTarget.setPositions(values);
  54355. break;
  54356. case "TANGENT":
  54357. // Tangent data for morph targets is stored as xyz delta.
  54358. // The vertexData.tangent is stored as xyzw.
  54359. // So we need to skip every fourth vertexData.tangent.
  54360. for (var i = 0, j = 0; i < values.length; i++, j++) {
  54361. values[i] += vertexData.tangents[j];
  54362. if ((i + 1) % 3 == 0) {
  54363. j++;
  54364. }
  54365. }
  54366. babylonMorphTarget.setTangents(values);
  54367. break;
  54368. default:
  54369. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  54370. break;
  54371. }
  54372. });
  54373. };
  54374. for (var semantic in attributes) {
  54375. _loop_4(semantic);
  54376. }
  54377. };
  54378. var this_3 = this, attributes, accessor;
  54379. for (var index = 0; index < targets.length; index++) {
  54380. _loop_3();
  54381. }
  54382. };
  54383. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  54384. var position = BABYLON.Vector3.Zero();
  54385. var rotation = BABYLON.Quaternion.Identity();
  54386. var scaling = BABYLON.Vector3.One();
  54387. if (node.matrix) {
  54388. var mat = BABYLON.Matrix.FromArray(node.matrix);
  54389. mat.decompose(scaling, rotation, position);
  54390. }
  54391. else {
  54392. if (node.translation)
  54393. position = BABYLON.Vector3.FromArray(node.translation);
  54394. if (node.rotation)
  54395. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  54396. if (node.scale)
  54397. scaling = BABYLON.Vector3.FromArray(node.scale);
  54398. }
  54399. babylonMesh.position = position;
  54400. babylonMesh.rotationQuaternion = rotation;
  54401. babylonMesh.scaling = scaling;
  54402. };
  54403. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  54404. if (parentNode === void 0) { parentNode = null; }
  54405. for (var i = 0; i < indices.length; i++) {
  54406. this._traverseNode(indices[i], action, parentNode);
  54407. }
  54408. };
  54409. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  54410. if (parentNode === void 0) { parentNode = null; }
  54411. var node = this._gltf.nodes[index];
  54412. if (!action(node, index, parentNode)) {
  54413. return;
  54414. }
  54415. if (node.children) {
  54416. for (var i = 0; i < node.children.length; i++) {
  54417. this._traverseNode(node.children[i], action, node);
  54418. }
  54419. }
  54420. };
  54421. GLTFLoader.prototype._loadAnimations = function () {
  54422. var animations = this._gltf.animations;
  54423. if (!animations || animations.length === 0) {
  54424. return;
  54425. }
  54426. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  54427. var animation = animations[animationIndex];
  54428. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  54429. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  54430. }
  54431. }
  54432. };
  54433. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  54434. var channel = animation.channels[channelIndex];
  54435. var samplerIndex = channel.sampler;
  54436. var sampler = animation.samplers[samplerIndex];
  54437. var targetNode = this._gltf.nodes[channel.target.node];
  54438. if (!targetNode) {
  54439. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  54440. return;
  54441. }
  54442. var targetPath = {
  54443. "translation": "position",
  54444. "rotation": "rotationQuaternion",
  54445. "scale": "scaling",
  54446. "weights": "influence"
  54447. }[channel.target.path];
  54448. if (!targetPath) {
  54449. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  54450. return;
  54451. }
  54452. var animationType = {
  54453. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54454. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  54455. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54456. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  54457. }[targetPath];
  54458. var inputData;
  54459. var outputData;
  54460. var checkSuccess = function () {
  54461. if (!inputData || !outputData) {
  54462. return;
  54463. }
  54464. var outputBufferOffset = 0;
  54465. var getNextOutputValue = {
  54466. "position": function () {
  54467. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54468. outputBufferOffset += 3;
  54469. return value;
  54470. },
  54471. "rotationQuaternion": function () {
  54472. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  54473. outputBufferOffset += 4;
  54474. return value;
  54475. },
  54476. "scaling": function () {
  54477. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54478. outputBufferOffset += 3;
  54479. return value;
  54480. },
  54481. "influence": function () {
  54482. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  54483. var value = new Array(numTargets);
  54484. for (var i = 0; i < numTargets; i++) {
  54485. value[i] = outputData[outputBufferOffset++];
  54486. }
  54487. return value;
  54488. },
  54489. }[targetPath];
  54490. var getNextKey = {
  54491. "LINEAR": function (frameIndex) { return ({
  54492. frame: inputData[frameIndex],
  54493. value: getNextOutputValue()
  54494. }); },
  54495. "CUBICSPLINE": function (frameIndex) { return ({
  54496. frame: inputData[frameIndex],
  54497. inTangent: getNextOutputValue(),
  54498. value: getNextOutputValue(),
  54499. outTangent: getNextOutputValue()
  54500. }); },
  54501. }[sampler.interpolation];
  54502. var keys = new Array(inputData.length);
  54503. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  54504. keys[frameIndex] = getNextKey(frameIndex);
  54505. }
  54506. animation.targets = animation.targets || [];
  54507. if (targetPath === "influence") {
  54508. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  54509. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  54510. var morphTarget = morphTargetManager.getTarget(targetIndex);
  54511. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  54512. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54513. babylonAnimation.setKeys(keys.map(function (key) { return ({
  54514. frame: key.frame,
  54515. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  54516. value: key.value[targetIndex],
  54517. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  54518. }); }));
  54519. morphTarget.animations.push(babylonAnimation);
  54520. animation.targets.push(morphTarget);
  54521. }
  54522. }
  54523. else {
  54524. var animationName = animation.name || "anim" + animationIndex;
  54525. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54526. babylonAnimation.setKeys(keys);
  54527. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  54528. var target = targetNode.babylonAnimationTargets[i];
  54529. target.animations.push(babylonAnimation.clone());
  54530. animation.targets.push(target);
  54531. }
  54532. }
  54533. };
  54534. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  54535. inputData = data;
  54536. checkSuccess();
  54537. });
  54538. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  54539. outputData = data;
  54540. checkSuccess();
  54541. });
  54542. };
  54543. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  54544. var _this = this;
  54545. var buffer = this._gltf.buffers[index];
  54546. this.addPendingData(buffer);
  54547. if (buffer.loadedData) {
  54548. setTimeout(function () {
  54549. onSuccess(buffer.loadedData);
  54550. _this.removePendingData(buffer);
  54551. });
  54552. }
  54553. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  54554. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  54555. buffer.loadedData = new Uint8Array(data);
  54556. setTimeout(function () {
  54557. onSuccess(buffer.loadedData);
  54558. _this.removePendingData(buffer);
  54559. });
  54560. }
  54561. else if (buffer.loadedObservable) {
  54562. buffer.loadedObservable.add(function (buffer) {
  54563. onSuccess(buffer.loadedData);
  54564. _this.removePendingData(buffer);
  54565. });
  54566. }
  54567. else {
  54568. buffer.loadedObservable = new BABYLON.Observable();
  54569. buffer.loadedObservable.add(function (buffer) {
  54570. onSuccess(buffer.loadedData);
  54571. _this.removePendingData(buffer);
  54572. });
  54573. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  54574. buffer.loadedData = new Uint8Array(data);
  54575. buffer.loadedObservable.notifyObservers(buffer);
  54576. buffer.loadedObservable = null;
  54577. }, function (event) {
  54578. if (!_this._disposed) {
  54579. _this._onProgress(event);
  54580. }
  54581. }, this._babylonScene.database, true, function (request) {
  54582. if (!_this._disposed) {
  54583. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  54584. _this.removePendingData(buffer);
  54585. }
  54586. });
  54587. }
  54588. };
  54589. GLTFLoader.prototype._buildInt8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54590. if (!byteStride) {
  54591. return new Int8Array(buffer, byteOffset, byteLength);
  54592. }
  54593. var sourceBuffer = new Int8Array(buffer, byteOffset);
  54594. var targetBuffer = new Int8Array(byteLength);
  54595. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  54596. return targetBuffer;
  54597. };
  54598. GLTFLoader.prototype._buildUint8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54599. if (!byteStride) {
  54600. return new Uint8Array(buffer, byteOffset, byteLength);
  54601. }
  54602. var sourceBuffer = new Uint8Array(buffer, byteOffset);
  54603. var targetBuffer = new Uint8Array(byteLength);
  54604. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  54605. return targetBuffer;
  54606. };
  54607. GLTFLoader.prototype._buildInt16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54608. if (!byteStride) {
  54609. return new Int16Array(buffer, byteOffset, byteLength);
  54610. }
  54611. var sourceBuffer = new Int16Array(buffer, byteOffset);
  54612. var targetBuffer = new Int16Array(byteLength);
  54613. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  54614. return targetBuffer;
  54615. };
  54616. GLTFLoader.prototype._buildUint16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54617. if (!byteStride) {
  54618. return new Uint16Array(buffer, byteOffset, byteLength);
  54619. }
  54620. var sourceBuffer = new Uint16Array(buffer, byteOffset);
  54621. var targetBuffer = new Uint16Array(byteLength);
  54622. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  54623. return targetBuffer;
  54624. };
  54625. GLTFLoader.prototype._buildUint32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54626. if (!byteStride) {
  54627. return new Uint32Array(buffer, byteOffset, byteLength);
  54628. }
  54629. var sourceBuffer = new Uint32Array(buffer, byteOffset);
  54630. var targetBuffer = new Uint32Array(byteLength);
  54631. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  54632. return targetBuffer;
  54633. };
  54634. GLTFLoader.prototype._buildFloat32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54635. if (!byteStride) {
  54636. return new Float32Array(buffer, byteOffset, byteLength);
  54637. }
  54638. var sourceBuffer = new Float32Array(buffer, byteOffset);
  54639. var targetBuffer = new Float32Array(byteLength);
  54640. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  54641. return targetBuffer;
  54642. };
  54643. GLTFLoader.prototype._extractInterleavedData = function (sourceBuffer, targetBuffer, bytePerComponent, stride, length) {
  54644. var tempIndex = 0;
  54645. var sourceIndex = 0;
  54646. var storageSize = bytePerComponent;
  54647. while (tempIndex < length) {
  54648. for (var cursor = 0; cursor < storageSize; cursor++) {
  54649. targetBuffer[tempIndex] = sourceBuffer[sourceIndex + cursor];
  54650. tempIndex++;
  54651. }
  54652. sourceIndex += stride;
  54653. }
  54654. };
  54655. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, bytePerComponent, componentType, onSuccess) {
  54656. var _this = this;
  54657. byteOffset += (bufferView.byteOffset || 0);
  54658. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  54659. if (byteOffset + byteLength > bufferData.byteLength) {
  54660. _this._onError("Buffer access is out of range");
  54661. return;
  54662. }
  54663. var buffer = bufferData.buffer;
  54664. byteOffset += bufferData.byteOffset;
  54665. var bufferViewData;
  54666. switch (componentType) {
  54667. case GLTF2.EComponentType.BYTE:
  54668. bufferViewData = _this._buildInt8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54669. break;
  54670. case GLTF2.EComponentType.UNSIGNED_BYTE:
  54671. bufferViewData = _this._buildUint8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54672. break;
  54673. case GLTF2.EComponentType.SHORT:
  54674. bufferViewData = _this._buildInt16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54675. break;
  54676. case GLTF2.EComponentType.UNSIGNED_SHORT:
  54677. bufferViewData = _this._buildUint16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54678. break;
  54679. case GLTF2.EComponentType.UNSIGNED_INT:
  54680. bufferViewData = _this._buildUint32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54681. break;
  54682. case GLTF2.EComponentType.FLOAT:
  54683. bufferViewData = _this._buildFloat32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54684. break;
  54685. default:
  54686. _this._onError("Invalid component type (" + componentType + ")");
  54687. return;
  54688. }
  54689. onSuccess(bufferViewData);
  54690. });
  54691. };
  54692. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  54693. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  54694. var byteOffset = accessor.byteOffset || 0;
  54695. var bytePerComponent = this._getByteStrideFromType(accessor);
  54696. var byteLength = accessor.count * bytePerComponent;
  54697. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, bytePerComponent, accessor.componentType, onSuccess);
  54698. };
  54699. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  54700. switch (accessor.type) {
  54701. case "SCALAR": return 1;
  54702. case "VEC2": return 2;
  54703. case "VEC3": return 3;
  54704. case "VEC4": return 4;
  54705. case "MAT2": return 4;
  54706. case "MAT3": return 9;
  54707. case "MAT4": return 16;
  54708. default:
  54709. this._onError("Invalid accessor type (" + accessor.type + ")");
  54710. return 0;
  54711. }
  54712. };
  54713. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  54714. set: function (value) {
  54715. this._blockPendingTracking = value;
  54716. },
  54717. enumerable: true,
  54718. configurable: true
  54719. });
  54720. GLTFLoader.prototype.addPendingData = function (data) {
  54721. if (!this._renderReady) {
  54722. this._renderPendingCount++;
  54723. }
  54724. this.addLoaderPendingData(data);
  54725. };
  54726. GLTFLoader.prototype.removePendingData = function (data) {
  54727. if (!this._renderReady) {
  54728. if (--this._renderPendingCount === 0) {
  54729. this._renderReady = true;
  54730. this._onRenderReady();
  54731. }
  54732. }
  54733. this.removeLoaderPendingData(data);
  54734. };
  54735. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  54736. if (!this._nonBlockingData) {
  54737. this._nonBlockingData = new Array();
  54738. }
  54739. this._nonBlockingData.push(data);
  54740. };
  54741. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  54742. if (this._blockPendingTracking) {
  54743. this.addLoaderNonBlockingPendingData(data);
  54744. return;
  54745. }
  54746. this._loaderPendingCount++;
  54747. };
  54748. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  54749. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  54750. if (indexInPending !== -1) {
  54751. this._nonBlockingData.splice(indexInPending, 1);
  54752. }
  54753. else if (--this._loaderPendingCount === 0) {
  54754. this._onLoaderFirstLODComplete();
  54755. }
  54756. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  54757. this._onLoaderComplete();
  54758. this.dispose();
  54759. }
  54760. };
  54761. GLTFLoader.prototype._getDefaultMaterial = function () {
  54762. if (!this._defaultMaterial) {
  54763. var id = "__gltf_default";
  54764. var material = this._babylonScene.getMaterialByName(id);
  54765. if (!material) {
  54766. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  54767. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54768. material.metallic = 1;
  54769. material.roughness = 1;
  54770. }
  54771. this._defaultMaterial = material;
  54772. }
  54773. return this._defaultMaterial;
  54774. };
  54775. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  54776. var babylonMaterial = material.babylonMaterial;
  54777. // Ensure metallic workflow
  54778. babylonMaterial.metallic = 1;
  54779. babylonMaterial.roughness = 1;
  54780. var properties = material.pbrMetallicRoughness;
  54781. if (!properties) {
  54782. return;
  54783. }
  54784. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  54785. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  54786. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  54787. if (properties.baseColorTexture) {
  54788. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  54789. }
  54790. if (properties.metallicRoughnessTexture) {
  54791. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  54792. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  54793. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  54794. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  54795. }
  54796. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  54797. };
  54798. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  54799. if (material.babylonMaterial) {
  54800. assign(material.babylonMaterial, false);
  54801. return;
  54802. }
  54803. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  54804. return;
  54805. }
  54806. this.createPbrMaterial(material);
  54807. this.loadMaterialBaseProperties(material);
  54808. this._loadMaterialMetallicRoughnessProperties(material);
  54809. assign(material.babylonMaterial, true);
  54810. };
  54811. GLTFLoader.prototype.createPbrMaterial = function (material) {
  54812. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  54813. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54814. material.babylonMaterial = babylonMaterial;
  54815. };
  54816. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  54817. var babylonMaterial = material.babylonMaterial;
  54818. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  54819. if (material.doubleSided) {
  54820. babylonMaterial.backFaceCulling = false;
  54821. babylonMaterial.twoSidedLighting = true;
  54822. }
  54823. if (material.normalTexture) {
  54824. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  54825. babylonMaterial.invertNormalMapX = true;
  54826. babylonMaterial.invertNormalMapY = false;
  54827. if (material.normalTexture.scale !== undefined) {
  54828. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  54829. }
  54830. }
  54831. if (material.occlusionTexture) {
  54832. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  54833. babylonMaterial.useAmbientInGrayScale = true;
  54834. if (material.occlusionTexture.strength !== undefined) {
  54835. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  54836. }
  54837. }
  54838. if (material.emissiveTexture) {
  54839. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  54840. }
  54841. };
  54842. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  54843. var babylonMaterial = material.babylonMaterial;
  54844. var alphaMode = material.alphaMode || "OPAQUE";
  54845. switch (alphaMode) {
  54846. case "OPAQUE":
  54847. // default is opaque
  54848. break;
  54849. case "MASK":
  54850. case "BLEND":
  54851. if (colorFactor) {
  54852. babylonMaterial.alpha = colorFactor[3];
  54853. }
  54854. if (babylonMaterial.albedoTexture) {
  54855. babylonMaterial.albedoTexture.hasAlpha = true;
  54856. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  54857. }
  54858. break;
  54859. default:
  54860. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  54861. break;
  54862. }
  54863. };
  54864. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  54865. var _this = this;
  54866. var texture = this._gltf.textures[textureInfo.index];
  54867. var texCoord = textureInfo.texCoord || 0;
  54868. if (!texture || texture.source === undefined) {
  54869. return null;
  54870. }
  54871. // check the cache first
  54872. var babylonTexture;
  54873. if (texture.babylonTextures) {
  54874. babylonTexture = texture.babylonTextures[texCoord];
  54875. if (!babylonTexture) {
  54876. for (var i = 0; i < texture.babylonTextures.length; i++) {
  54877. babylonTexture = texture.babylonTextures[i];
  54878. if (babylonTexture) {
  54879. babylonTexture = babylonTexture.clone();
  54880. babylonTexture.coordinatesIndex = texCoord;
  54881. break;
  54882. }
  54883. }
  54884. }
  54885. return babylonTexture;
  54886. }
  54887. var source = this._gltf.images[texture.source];
  54888. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  54889. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  54890. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  54891. this.addPendingData(texture);
  54892. babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  54893. if (!_this._disposed) {
  54894. _this.removePendingData(texture);
  54895. }
  54896. }, function () {
  54897. if (!_this._disposed) {
  54898. _this._onError("Failed to load texture '" + source.uri + "'");
  54899. _this.removePendingData(texture);
  54900. }
  54901. });
  54902. var setTextureData = function (data) {
  54903. var url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  54904. _this._objectURLs.push(url);
  54905. babylonTexture.updateURL(url);
  54906. };
  54907. if (!source.uri) {
  54908. var bufferView = this._gltf.bufferViews[source.bufferView];
  54909. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, 1, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  54910. }
  54911. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  54912. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  54913. }
  54914. else {
  54915. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  54916. if (!_this._disposed) {
  54917. _this._onProgress(event);
  54918. }
  54919. }, this._babylonScene.database, true, function (request) {
  54920. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  54921. });
  54922. }
  54923. babylonTexture.coordinatesIndex = texCoord;
  54924. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  54925. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  54926. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  54927. // Cache the texture
  54928. texture.babylonTextures = texture.babylonTextures || [];
  54929. texture.babylonTextures[texCoord] = babylonTexture;
  54930. if (this._parent.onTextureLoaded) {
  54931. this._parent.onTextureLoaded(babylonTexture);
  54932. }
  54933. return babylonTexture;
  54934. };
  54935. GLTFLoader.Extensions = {};
  54936. return GLTFLoader;
  54937. }());
  54938. GLTF2.GLTFLoader = GLTFLoader;
  54939. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  54940. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54941. })(BABYLON || (BABYLON = {}));
  54942. //# sourceMappingURL=babylon.glTFLoader.js.map
  54943. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  54944. var BABYLON;
  54945. (function (BABYLON) {
  54946. var GLTF2;
  54947. (function (GLTF2) {
  54948. /**
  54949. * Utils functions for GLTF
  54950. */
  54951. var GLTFUtils = (function () {
  54952. function GLTFUtils() {
  54953. }
  54954. /**
  54955. * If the uri is a base64 string
  54956. * @param uri: the uri to test
  54957. */
  54958. GLTFUtils.IsBase64 = function (uri) {
  54959. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  54960. };
  54961. /**
  54962. * Decode the base64 uri
  54963. * @param uri: the uri to decode
  54964. */
  54965. GLTFUtils.DecodeBase64 = function (uri) {
  54966. var decodedString = atob(uri.split(",")[1]);
  54967. var bufferLength = decodedString.length;
  54968. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  54969. for (var i = 0; i < bufferLength; i++) {
  54970. bufferView[i] = decodedString.charCodeAt(i);
  54971. }
  54972. return bufferView.buffer;
  54973. };
  54974. GLTFUtils.ForEach = function (view, func) {
  54975. for (var index = 0; index < view.length; index++) {
  54976. func(view[index], index);
  54977. }
  54978. };
  54979. GLTFUtils.GetTextureWrapMode = function (mode) {
  54980. // Set defaults if undefined
  54981. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  54982. switch (mode) {
  54983. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  54984. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  54985. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  54986. default:
  54987. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  54988. return BABYLON.Texture.WRAP_ADDRESSMODE;
  54989. }
  54990. };
  54991. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  54992. // Set defaults if undefined
  54993. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  54994. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST : minFilter;
  54995. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  54996. switch (minFilter) {
  54997. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  54998. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  54999. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  55000. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  55001. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  55002. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  55003. default:
  55004. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  55005. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  55006. }
  55007. }
  55008. else {
  55009. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  55010. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  55011. }
  55012. switch (minFilter) {
  55013. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  55014. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  55015. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  55016. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  55017. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  55018. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  55019. default:
  55020. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  55021. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  55022. }
  55023. }
  55024. };
  55025. /**
  55026. * Decodes a buffer view into a string
  55027. * @param view: the buffer view
  55028. */
  55029. GLTFUtils.DecodeBufferToText = function (view) {
  55030. var result = "";
  55031. var length = view.byteLength;
  55032. for (var i = 0; i < length; ++i) {
  55033. result += String.fromCharCode(view[i]);
  55034. }
  55035. return result;
  55036. };
  55037. return GLTFUtils;
  55038. }());
  55039. GLTF2.GLTFUtils = GLTFUtils;
  55040. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55041. })(BABYLON || (BABYLON = {}));
  55042. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  55043. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  55044. var BABYLON;
  55045. (function (BABYLON) {
  55046. var GLTF2;
  55047. (function (GLTF2) {
  55048. var GLTFLoaderExtension = (function () {
  55049. function GLTFLoaderExtension() {
  55050. this.enabled = true;
  55051. }
  55052. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  55053. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  55054. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  55055. };
  55056. GLTFLoaderExtension._ApplyExtensions = function (action) {
  55057. var extensions = GLTFLoaderExtension._Extensions;
  55058. if (!extensions) {
  55059. return;
  55060. }
  55061. for (var i = 0; i < extensions.length; i++) {
  55062. var extension = extensions[i];
  55063. if (extension.enabled && action(extension)) {
  55064. return true;
  55065. }
  55066. }
  55067. return false;
  55068. };
  55069. //
  55070. // Utilities
  55071. //
  55072. GLTFLoaderExtension._Extensions = [];
  55073. return GLTFLoaderExtension;
  55074. }());
  55075. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  55076. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55077. })(BABYLON || (BABYLON = {}));
  55078. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  55079. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  55080. var BABYLON;
  55081. (function (BABYLON) {
  55082. var GLTF2;
  55083. (function (GLTF2) {
  55084. var Extensions;
  55085. (function (Extensions) {
  55086. var MSFTLOD = (function (_super) {
  55087. __extends(MSFTLOD, _super);
  55088. function MSFTLOD() {
  55089. return _super !== null && _super.apply(this, arguments) || this;
  55090. }
  55091. Object.defineProperty(MSFTLOD.prototype, "name", {
  55092. get: function () {
  55093. return "MSFT_lod";
  55094. },
  55095. enumerable: true,
  55096. configurable: true
  55097. });
  55098. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  55099. if (!material.extensions) {
  55100. return false;
  55101. }
  55102. var properties = material.extensions[this.name];
  55103. if (!properties) {
  55104. return false;
  55105. }
  55106. // Clear out the extension so that it won't get loaded again.
  55107. material.extensions[this.name] = undefined;
  55108. // Tell the loader not to clear its state until the highest LOD is loaded.
  55109. var materialLODs = [material.index].concat(properties.ids);
  55110. loader.addLoaderPendingData(material);
  55111. for (var index = 0; index < materialLODs.length; index++) {
  55112. loader.addLoaderNonBlockingPendingData(index);
  55113. }
  55114. // Start with the lowest quality LOD.
  55115. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  55116. return true;
  55117. };
  55118. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  55119. var _this = this;
  55120. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  55121. if (lod !== materialLODs.length - 1) {
  55122. loader.blockPendingTracking = true;
  55123. }
  55124. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  55125. assign(babylonMaterial, isNew);
  55126. loader.removeLoaderPendingData(lod);
  55127. // Loading is considered complete if this is the lowest quality LOD.
  55128. if (lod === materialLODs.length - 1) {
  55129. loader.removeLoaderPendingData(material);
  55130. }
  55131. if (lod === 0) {
  55132. loader.blockPendingTracking = false;
  55133. return;
  55134. }
  55135. // Load the next LOD when the loader is ready to render and
  55136. // all active material textures of the current LOD are loaded.
  55137. loader.executeWhenRenderReady(function () {
  55138. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  55139. setTimeout(function () {
  55140. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  55141. }, MSFTLOD.MinimalLODDelay);
  55142. });
  55143. });
  55144. });
  55145. };
  55146. /**
  55147. * Specify the minimal delay between LODs in ms (default = 250)
  55148. */
  55149. MSFTLOD.MinimalLODDelay = 250;
  55150. return MSFTLOD;
  55151. }(GLTF2.GLTFLoaderExtension));
  55152. Extensions.MSFTLOD = MSFTLOD;
  55153. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  55154. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  55155. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55156. })(BABYLON || (BABYLON = {}));
  55157. //# sourceMappingURL=MSFT_lod.js.map
  55158. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  55159. var BABYLON;
  55160. (function (BABYLON) {
  55161. var GLTF2;
  55162. (function (GLTF2) {
  55163. var Extensions;
  55164. (function (Extensions) {
  55165. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  55166. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  55167. function KHRMaterialsPbrSpecularGlossiness() {
  55168. return _super !== null && _super.apply(this, arguments) || this;
  55169. }
  55170. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  55171. get: function () {
  55172. return "KHR_materials_pbrSpecularGlossiness";
  55173. },
  55174. enumerable: true,
  55175. configurable: true
  55176. });
  55177. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  55178. if (!material.extensions) {
  55179. return false;
  55180. }
  55181. var properties = material.extensions[this.name];
  55182. if (!properties) {
  55183. return false;
  55184. }
  55185. loader.createPbrMaterial(material);
  55186. loader.loadMaterialBaseProperties(material);
  55187. this._loadSpecularGlossinessProperties(loader, material, properties);
  55188. assign(material.babylonMaterial, true);
  55189. return true;
  55190. };
  55191. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  55192. var babylonMaterial = material.babylonMaterial;
  55193. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  55194. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  55195. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  55196. if (properties.diffuseTexture) {
  55197. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  55198. loader.loadMaterialAlphaProperties(material);
  55199. }
  55200. if (properties.specularGlossinessTexture) {
  55201. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  55202. babylonMaterial.reflectivityTexture.hasAlpha = true;
  55203. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  55204. }
  55205. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  55206. };
  55207. return KHRMaterialsPbrSpecularGlossiness;
  55208. }(GLTF2.GLTFLoaderExtension));
  55209. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  55210. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  55211. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  55212. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55213. })(BABYLON || (BABYLON = {}));
  55214. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  55215. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  55216. module.exports = BABYLON;
  55217. };