babylon.max.js 2.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var Color3 = (function () {
  23. /**
  24. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  25. */
  26. function Color3(r, g, b) {
  27. if (r === void 0) { r = 0; }
  28. if (g === void 0) { g = 0; }
  29. if (b === void 0) { b = 0; }
  30. this.r = r;
  31. this.g = g;
  32. this.b = b;
  33. }
  34. /**
  35. * Returns a string with the Color3 current values.
  36. */
  37. Color3.prototype.toString = function () {
  38. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  39. };
  40. /**
  41. * Returns the string "Color3".
  42. */
  43. Color3.prototype.getClassName = function () {
  44. return "Color3";
  45. };
  46. /**
  47. * Returns the Color3 hash code.
  48. */
  49. Color3.prototype.getHashCode = function () {
  50. var hash = this.r || 0;
  51. hash = (hash * 397) ^ (this.g || 0);
  52. hash = (hash * 397) ^ (this.b || 0);
  53. return hash;
  54. };
  55. // Operators
  56. /**
  57. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  58. * Returns the Color3.
  59. */
  60. Color3.prototype.toArray = function (array, index) {
  61. if (index === undefined) {
  62. index = 0;
  63. }
  64. array[index] = this.r;
  65. array[index + 1] = this.g;
  66. array[index + 2] = this.b;
  67. return this;
  68. };
  69. /**
  70. * Returns a new Color4 object from the current Color3 and the passed alpha.
  71. */
  72. Color3.prototype.toColor4 = function (alpha) {
  73. if (alpha === void 0) { alpha = 1; }
  74. return new Color4(this.r, this.g, this.b, alpha);
  75. };
  76. /**
  77. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  78. */
  79. Color3.prototype.asArray = function () {
  80. var result = [];
  81. this.toArray(result, 0);
  82. return result;
  83. };
  84. /**
  85. * Returns the luminance value (float).
  86. */
  87. Color3.prototype.toLuminance = function () {
  88. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  89. };
  90. /**
  91. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  92. * Returns this new object.
  93. */
  94. Color3.prototype.multiply = function (otherColor) {
  95. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  96. };
  97. /**
  98. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  99. * Returns the current Color3.
  100. */
  101. Color3.prototype.multiplyToRef = function (otherColor, result) {
  102. result.r = this.r * otherColor.r;
  103. result.g = this.g * otherColor.g;
  104. result.b = this.b * otherColor.b;
  105. return this;
  106. };
  107. /**
  108. * Boolean : True if the rgb values are equal to the passed ones.
  109. */
  110. Color3.prototype.equals = function (otherColor) {
  111. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  112. };
  113. /**
  114. * Boolean : True if the rgb values are equal to the passed ones.
  115. */
  116. Color3.prototype.equalsFloats = function (r, g, b) {
  117. return this.r === r && this.g === g && this.b === b;
  118. };
  119. /**
  120. * Multiplies in place each rgb value by scale.
  121. * Returns the updated Color3.
  122. */
  123. Color3.prototype.scale = function (scale) {
  124. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  125. };
  126. /**
  127. * Multiplies the rgb values by scale and stores the result into "result".
  128. * Returns the unmodified current Color3.
  129. */
  130. Color3.prototype.scaleToRef = function (scale, result) {
  131. result.r = this.r * scale;
  132. result.g = this.g * scale;
  133. result.b = this.b * scale;
  134. return this;
  135. };
  136. /**
  137. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  138. */
  139. Color3.prototype.add = function (otherColor) {
  140. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  141. };
  142. /**
  143. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  144. * Returns the unmodified current Color3.
  145. */
  146. Color3.prototype.addToRef = function (otherColor, result) {
  147. result.r = this.r + otherColor.r;
  148. result.g = this.g + otherColor.g;
  149. result.b = this.b + otherColor.b;
  150. return this;
  151. };
  152. /**
  153. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  154. */
  155. Color3.prototype.subtract = function (otherColor) {
  156. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  157. };
  158. /**
  159. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  160. * Returns the unmodified current Color3.
  161. */
  162. Color3.prototype.subtractToRef = function (otherColor, result) {
  163. result.r = this.r - otherColor.r;
  164. result.g = this.g - otherColor.g;
  165. result.b = this.b - otherColor.b;
  166. return this;
  167. };
  168. /**
  169. * Returns a new Color3 copied the current one.
  170. */
  171. Color3.prototype.clone = function () {
  172. return new Color3(this.r, this.g, this.b);
  173. };
  174. /**
  175. * Copies the rgb values from the source in the current Color3.
  176. * Returns the updated Color3.
  177. */
  178. Color3.prototype.copyFrom = function (source) {
  179. this.r = source.r;
  180. this.g = source.g;
  181. this.b = source.b;
  182. return this;
  183. };
  184. /**
  185. * Updates the Color3 rgb values from the passed floats.
  186. * Returns the Color3.
  187. */
  188. Color3.prototype.copyFromFloats = function (r, g, b) {
  189. this.r = r;
  190. this.g = g;
  191. this.b = b;
  192. return this;
  193. };
  194. /**
  195. * Updates the Color3 rgb values from the passed floats.
  196. * Returns the Color3.
  197. */
  198. Color3.prototype.set = function (r, g, b) {
  199. return this.copyFromFloats(r, g, b);
  200. };
  201. /**
  202. * Returns the Color3 hexadecimal code as a string.
  203. */
  204. Color3.prototype.toHexString = function () {
  205. var intR = (this.r * 255) | 0;
  206. var intG = (this.g * 255) | 0;
  207. var intB = (this.b * 255) | 0;
  208. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  209. };
  210. /**
  211. * Returns a new Color3 converted to linear space.
  212. */
  213. Color3.prototype.toLinearSpace = function () {
  214. var convertedColor = new Color3();
  215. this.toLinearSpaceToRef(convertedColor);
  216. return convertedColor;
  217. };
  218. /**
  219. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  220. * Returns the unmodified Color3.
  221. */
  222. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  223. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  224. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  225. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  226. return this;
  227. };
  228. /**
  229. * Returns a new Color3 converted to gamma space.
  230. */
  231. Color3.prototype.toGammaSpace = function () {
  232. var convertedColor = new Color3();
  233. this.toGammaSpaceToRef(convertedColor);
  234. return convertedColor;
  235. };
  236. /**
  237. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  238. * Returns the unmodified Color3.
  239. */
  240. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  241. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  242. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  243. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  244. return this;
  245. };
  246. // Statics
  247. /**
  248. * Creates a new Color3 from the string containing valid hexadecimal values.
  249. */
  250. Color3.FromHexString = function (hex) {
  251. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  252. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  253. return new Color3(0, 0, 0);
  254. }
  255. var r = parseInt(hex.substring(1, 3), 16);
  256. var g = parseInt(hex.substring(3, 5), 16);
  257. var b = parseInt(hex.substring(5, 7), 16);
  258. return Color3.FromInts(r, g, b);
  259. };
  260. /**
  261. * Creates a new Vector3 from the startind index of the passed array.
  262. */
  263. Color3.FromArray = function (array, offset) {
  264. if (offset === void 0) { offset = 0; }
  265. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  266. };
  267. /**
  268. * Creates a new Color3 from integer values ( < 256).
  269. */
  270. Color3.FromInts = function (r, g, b) {
  271. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  272. };
  273. /**
  274. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  275. */
  276. Color3.Lerp = function (start, end, amount) {
  277. var r = start.r + ((end.r - start.r) * amount);
  278. var g = start.g + ((end.g - start.g) * amount);
  279. var b = start.b + ((end.b - start.b) * amount);
  280. return new Color3(r, g, b);
  281. };
  282. Color3.Red = function () { return new Color3(1, 0, 0); };
  283. Color3.Green = function () { return new Color3(0, 1, 0); };
  284. Color3.Blue = function () { return new Color3(0, 0, 1); };
  285. Color3.Black = function () { return new Color3(0, 0, 0); };
  286. Color3.White = function () { return new Color3(1, 1, 1); };
  287. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  288. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  289. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  290. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  291. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  292. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  293. return Color3;
  294. }());
  295. BABYLON.Color3 = Color3;
  296. var Color4 = (function () {
  297. /**
  298. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  299. */
  300. function Color4(r, g, b, a) {
  301. if (r === void 0) { r = 0; }
  302. if (g === void 0) { g = 0; }
  303. if (b === void 0) { b = 0; }
  304. if (a === void 0) { a = 1; }
  305. this.r = r;
  306. this.g = g;
  307. this.b = b;
  308. this.a = a;
  309. }
  310. // Operators
  311. /**
  312. * Adds in place the passed Color4 values to the current Color4.
  313. * Returns the updated Color4.
  314. */
  315. Color4.prototype.addInPlace = function (right) {
  316. this.r += right.r;
  317. this.g += right.g;
  318. this.b += right.b;
  319. this.a += right.a;
  320. return this;
  321. };
  322. /**
  323. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  324. */
  325. Color4.prototype.asArray = function () {
  326. var result = [];
  327. this.toArray(result, 0);
  328. return result;
  329. };
  330. /**
  331. * Stores from the starting index in the passed array the Color4 successive values.
  332. * Returns the Color4.
  333. */
  334. Color4.prototype.toArray = function (array, index) {
  335. if (index === undefined) {
  336. index = 0;
  337. }
  338. array[index] = this.r;
  339. array[index + 1] = this.g;
  340. array[index + 2] = this.b;
  341. array[index + 3] = this.a;
  342. return this;
  343. };
  344. /**
  345. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  346. */
  347. Color4.prototype.add = function (right) {
  348. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  349. };
  350. /**
  351. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  352. */
  353. Color4.prototype.subtract = function (right) {
  354. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  355. };
  356. /**
  357. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  358. * Returns the Color4.
  359. */
  360. Color4.prototype.subtractToRef = function (right, result) {
  361. result.r = this.r - right.r;
  362. result.g = this.g - right.g;
  363. result.b = this.b - right.b;
  364. result.a = this.a - right.a;
  365. return this;
  366. };
  367. /**
  368. * Creates a new Color4 with the current Color4 values multiplied by scale.
  369. */
  370. Color4.prototype.scale = function (scale) {
  371. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  372. };
  373. /**
  374. * Multiplies the current Color4 values by scale and stores the result in "result".
  375. * Returns the Color4.
  376. */
  377. Color4.prototype.scaleToRef = function (scale, result) {
  378. result.r = this.r * scale;
  379. result.g = this.g * scale;
  380. result.b = this.b * scale;
  381. result.a = this.a * scale;
  382. return this;
  383. };
  384. /**
  385. * Multipy an RGBA Color4 value by another and return a new Color4 object
  386. * @param color The Color4 (RGBA) value to multiply by
  387. * @returns A new Color4.
  388. */
  389. Color4.prototype.multiply = function (color) {
  390. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  391. };
  392. /**
  393. * Multipy an RGBA Color4 value by another and push the result in a reference value
  394. * @param color The Color4 (RGBA) value to multiply by
  395. * @param result The Color4 (RGBA) to fill the result in
  396. * @returns the result Color4.
  397. */
  398. Color4.prototype.multiplyToRef = function (color, result) {
  399. result.r = this.r * color.r;
  400. result.g = this.g * color.g;
  401. result.b = this.b * color.b;
  402. result.a = this.a * color.a;
  403. return result;
  404. };
  405. /**
  406. * Returns a string with the Color4 values.
  407. */
  408. Color4.prototype.toString = function () {
  409. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  410. };
  411. /**
  412. * Returns the string "Color4"
  413. */
  414. Color4.prototype.getClassName = function () {
  415. return "Color4";
  416. };
  417. /**
  418. * Return the Color4 hash code as a number.
  419. */
  420. Color4.prototype.getHashCode = function () {
  421. var hash = this.r || 0;
  422. hash = (hash * 397) ^ (this.g || 0);
  423. hash = (hash * 397) ^ (this.b || 0);
  424. hash = (hash * 397) ^ (this.a || 0);
  425. return hash;
  426. };
  427. /**
  428. * Creates a new Color4 copied from the current one.
  429. */
  430. Color4.prototype.clone = function () {
  431. return new Color4(this.r, this.g, this.b, this.a);
  432. };
  433. /**
  434. * Copies the passed Color4 values into the current one.
  435. * Returns the updated Color4.
  436. */
  437. Color4.prototype.copyFrom = function (source) {
  438. this.r = source.r;
  439. this.g = source.g;
  440. this.b = source.b;
  441. this.a = source.a;
  442. return this;
  443. };
  444. /**
  445. * Copies the passed float values into the current one.
  446. * Returns the updated Color4.
  447. */
  448. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  449. this.r = r;
  450. this.g = g;
  451. this.b = b;
  452. this.a = a;
  453. return this;
  454. };
  455. /**
  456. * Copies the passed float values into the current one.
  457. * Returns the updated Color4.
  458. */
  459. Color4.prototype.set = function (r, g, b, a) {
  460. return this.copyFromFloats(r, g, b, a);
  461. };
  462. /**
  463. * Returns a string containing the hexadecimal Color4 code.
  464. */
  465. Color4.prototype.toHexString = function () {
  466. var intR = (this.r * 255) | 0;
  467. var intG = (this.g * 255) | 0;
  468. var intB = (this.b * 255) | 0;
  469. var intA = (this.a * 255) | 0;
  470. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  471. };
  472. /**
  473. * Returns a new Color4 converted to linear space.
  474. */
  475. Color4.prototype.toLinearSpace = function () {
  476. var convertedColor = new Color4();
  477. this.toLinearSpaceToRef(convertedColor);
  478. return convertedColor;
  479. };
  480. /**
  481. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  482. * Returns the unmodified Color4.
  483. */
  484. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  485. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  486. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  487. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  488. convertedColor.a = this.a;
  489. return this;
  490. };
  491. /**
  492. * Returns a new Color4 converted to gamma space.
  493. */
  494. Color4.prototype.toGammaSpace = function () {
  495. var convertedColor = new Color4();
  496. this.toGammaSpaceToRef(convertedColor);
  497. return convertedColor;
  498. };
  499. /**
  500. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  501. * Returns the unmodified Color4.
  502. */
  503. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  504. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  505. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  506. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  507. convertedColor.a = this.a;
  508. return this;
  509. };
  510. // Statics
  511. /**
  512. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  513. */
  514. Color4.FromHexString = function (hex) {
  515. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  516. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  517. return new Color4(0.0, 0.0, 0.0, 0.0);
  518. }
  519. var r = parseInt(hex.substring(1, 3), 16);
  520. var g = parseInt(hex.substring(3, 5), 16);
  521. var b = parseInt(hex.substring(5, 7), 16);
  522. var a = parseInt(hex.substring(7, 9), 16);
  523. return Color4.FromInts(r, g, b, a);
  524. };
  525. /**
  526. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  527. */
  528. Color4.Lerp = function (left, right, amount) {
  529. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  530. Color4.LerpToRef(left, right, amount, result);
  531. return result;
  532. };
  533. /**
  534. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  535. */
  536. Color4.LerpToRef = function (left, right, amount, result) {
  537. result.r = left.r + (right.r - left.r) * amount;
  538. result.g = left.g + (right.g - left.g) * amount;
  539. result.b = left.b + (right.b - left.b) * amount;
  540. result.a = left.a + (right.a - left.a) * amount;
  541. };
  542. /**
  543. * Creates a new Color4 from the starting index element of the passed array.
  544. */
  545. Color4.FromArray = function (array, offset) {
  546. if (offset === void 0) { offset = 0; }
  547. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  548. };
  549. /**
  550. * Creates a new Color4 from the passed integers ( < 256 ).
  551. */
  552. Color4.FromInts = function (r, g, b, a) {
  553. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  554. };
  555. Color4.CheckColors4 = function (colors, count) {
  556. // Check if color3 was used
  557. if (colors.length === count * 3) {
  558. var colors4 = [];
  559. for (var index = 0; index < colors.length; index += 3) {
  560. var newIndex = (index / 3) * 4;
  561. colors4[newIndex] = colors[index];
  562. colors4[newIndex + 1] = colors[index + 1];
  563. colors4[newIndex + 2] = colors[index + 2];
  564. colors4[newIndex + 3] = 1.0;
  565. }
  566. return colors4;
  567. }
  568. return colors;
  569. };
  570. return Color4;
  571. }());
  572. BABYLON.Color4 = Color4;
  573. var Vector2 = (function () {
  574. /**
  575. * Creates a new Vector2 from the passed x and y coordinates.
  576. */
  577. function Vector2(x, y) {
  578. this.x = x;
  579. this.y = y;
  580. }
  581. /**
  582. * Returns a string with the Vector2 coordinates.
  583. */
  584. Vector2.prototype.toString = function () {
  585. return "{X: " + this.x + " Y:" + this.y + "}";
  586. };
  587. /**
  588. * Returns the string "Vector2"
  589. */
  590. Vector2.prototype.getClassName = function () {
  591. return "Vector2";
  592. };
  593. /**
  594. * Returns the Vector2 hash code as a number.
  595. */
  596. Vector2.prototype.getHashCode = function () {
  597. var hash = this.x || 0;
  598. hash = (hash * 397) ^ (this.y || 0);
  599. return hash;
  600. };
  601. // Operators
  602. /**
  603. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  604. * Returns the Vector2.
  605. */
  606. Vector2.prototype.toArray = function (array, index) {
  607. if (index === void 0) { index = 0; }
  608. array[index] = this.x;
  609. array[index + 1] = this.y;
  610. return this;
  611. };
  612. /**
  613. * Returns a new array with 2 elements : the Vector2 coordinates.
  614. */
  615. Vector2.prototype.asArray = function () {
  616. var result = [];
  617. this.toArray(result, 0);
  618. return result;
  619. };
  620. /**
  621. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  622. * Returns the updated Vector2.
  623. */
  624. Vector2.prototype.copyFrom = function (source) {
  625. this.x = source.x;
  626. this.y = source.y;
  627. return this;
  628. };
  629. /**
  630. * Sets the Vector2 coordinates with the passed floats.
  631. * Returns the updated Vector2.
  632. */
  633. Vector2.prototype.copyFromFloats = function (x, y) {
  634. this.x = x;
  635. this.y = y;
  636. return this;
  637. };
  638. /**
  639. * Sets the Vector2 coordinates with the passed floats.
  640. * Returns the updated Vector2.
  641. */
  642. Vector2.prototype.set = function (x, y) {
  643. return this.copyFromFloats(x, y);
  644. };
  645. /**
  646. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  647. */
  648. Vector2.prototype.add = function (otherVector) {
  649. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  650. };
  651. /**
  652. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  653. * Returns the Vector2.
  654. */
  655. Vector2.prototype.addToRef = function (otherVector, result) {
  656. result.x = this.x + otherVector.x;
  657. result.y = this.y + otherVector.y;
  658. return this;
  659. };
  660. /**
  661. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  662. * Returns the updated Vector2.
  663. */
  664. Vector2.prototype.addInPlace = function (otherVector) {
  665. this.x += otherVector.x;
  666. this.y += otherVector.y;
  667. return this;
  668. };
  669. /**
  670. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  671. */
  672. Vector2.prototype.addVector3 = function (otherVector) {
  673. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  674. };
  675. /**
  676. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  677. */
  678. Vector2.prototype.subtract = function (otherVector) {
  679. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  680. };
  681. /**
  682. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  683. * Returns the Vector2.
  684. */
  685. Vector2.prototype.subtractToRef = function (otherVector, result) {
  686. result.x = this.x - otherVector.x;
  687. result.y = this.y - otherVector.y;
  688. return this;
  689. };
  690. /**
  691. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  692. * Returns the updated Vector2.
  693. */
  694. Vector2.prototype.subtractInPlace = function (otherVector) {
  695. this.x -= otherVector.x;
  696. this.y -= otherVector.y;
  697. return this;
  698. };
  699. /**
  700. * Multiplies in place the current Vector2 coordinates by the passed ones.
  701. * Returns the updated Vector2.
  702. */
  703. Vector2.prototype.multiplyInPlace = function (otherVector) {
  704. this.x *= otherVector.x;
  705. this.y *= otherVector.y;
  706. return this;
  707. };
  708. /**
  709. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  710. */
  711. Vector2.prototype.multiply = function (otherVector) {
  712. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  713. };
  714. /**
  715. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  716. * Returns the Vector2.
  717. */
  718. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  719. result.x = this.x * otherVector.x;
  720. result.y = this.y * otherVector.y;
  721. return this;
  722. };
  723. /**
  724. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  725. */
  726. Vector2.prototype.multiplyByFloats = function (x, y) {
  727. return new Vector2(this.x * x, this.y * y);
  728. };
  729. /**
  730. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  731. */
  732. Vector2.prototype.divide = function (otherVector) {
  733. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  734. };
  735. /**
  736. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  737. * Returns the Vector2.
  738. */
  739. Vector2.prototype.divideToRef = function (otherVector, result) {
  740. result.x = this.x / otherVector.x;
  741. result.y = this.y / otherVector.y;
  742. return this;
  743. };
  744. /**
  745. * Returns a new Vector2 with current Vector2 negated coordinates.
  746. */
  747. Vector2.prototype.negate = function () {
  748. return new Vector2(-this.x, -this.y);
  749. };
  750. /**
  751. * Multiply the Vector2 coordinates by scale.
  752. * Returns the updated Vector2.
  753. */
  754. Vector2.prototype.scaleInPlace = function (scale) {
  755. this.x *= scale;
  756. this.y *= scale;
  757. return this;
  758. };
  759. /**
  760. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  761. */
  762. Vector2.prototype.scale = function (scale) {
  763. return new Vector2(this.x * scale, this.y * scale);
  764. };
  765. /**
  766. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  767. */
  768. Vector2.prototype.equals = function (otherVector) {
  769. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  770. };
  771. /**
  772. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  773. */
  774. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  775. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  776. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  777. };
  778. // Properties
  779. /**
  780. * Returns the vector length (float).
  781. */
  782. Vector2.prototype.length = function () {
  783. return Math.sqrt(this.x * this.x + this.y * this.y);
  784. };
  785. /**
  786. * Returns the vector squared length (float);
  787. */
  788. Vector2.prototype.lengthSquared = function () {
  789. return (this.x * this.x + this.y * this.y);
  790. };
  791. // Methods
  792. /**
  793. * Normalize the vector.
  794. * Returns the updated Vector2.
  795. */
  796. Vector2.prototype.normalize = function () {
  797. var len = this.length();
  798. if (len === 0)
  799. return this;
  800. var num = 1.0 / len;
  801. this.x *= num;
  802. this.y *= num;
  803. return this;
  804. };
  805. /**
  806. * Returns a new Vector2 copied from the Vector2.
  807. */
  808. Vector2.prototype.clone = function () {
  809. return new Vector2(this.x, this.y);
  810. };
  811. // Statics
  812. /**
  813. * Returns a new Vector2(0, 0)
  814. */
  815. Vector2.Zero = function () {
  816. return new Vector2(0, 0);
  817. };
  818. /**
  819. * Returns a new Vector2(1, 1)
  820. */
  821. Vector2.One = function () {
  822. return new Vector2(1, 1);
  823. };
  824. /**
  825. * Returns a new Vector2 set from the passed index element of the passed array.
  826. */
  827. Vector2.FromArray = function (array, offset) {
  828. if (offset === void 0) { offset = 0; }
  829. return new Vector2(array[offset], array[offset + 1]);
  830. };
  831. /**
  832. * Sets "result" from the passed index element of the passed array.
  833. */
  834. Vector2.FromArrayToRef = function (array, offset, result) {
  835. result.x = array[offset];
  836. result.y = array[offset + 1];
  837. };
  838. /**
  839. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  840. */
  841. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  842. var squared = amount * amount;
  843. var cubed = amount * squared;
  844. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  845. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  846. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  847. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  848. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  849. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  850. return new Vector2(x, y);
  851. };
  852. /**
  853. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  854. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  855. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  856. */
  857. Vector2.Clamp = function (value, min, max) {
  858. var x = value.x;
  859. x = (x > max.x) ? max.x : x;
  860. x = (x < min.x) ? min.x : x;
  861. var y = value.y;
  862. y = (y > max.y) ? max.y : y;
  863. y = (y < min.y) ? min.y : y;
  864. return new Vector2(x, y);
  865. };
  866. /**
  867. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  868. */
  869. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  870. var squared = amount * amount;
  871. var cubed = amount * squared;
  872. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  873. var part2 = (-2.0 * cubed) + (3.0 * squared);
  874. var part3 = (cubed - (2.0 * squared)) + amount;
  875. var part4 = cubed - squared;
  876. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  877. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  878. return new Vector2(x, y);
  879. };
  880. /**
  881. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  882. */
  883. Vector2.Lerp = function (start, end, amount) {
  884. var x = start.x + ((end.x - start.x) * amount);
  885. var y = start.y + ((end.y - start.y) * amount);
  886. return new Vector2(x, y);
  887. };
  888. /**
  889. * Returns the dot product (float) of the vector "left" and the vector "right".
  890. */
  891. Vector2.Dot = function (left, right) {
  892. return left.x * right.x + left.y * right.y;
  893. };
  894. /**
  895. * Returns a new Vector2 equal to the normalized passed vector.
  896. */
  897. Vector2.Normalize = function (vector) {
  898. var newVector = vector.clone();
  899. newVector.normalize();
  900. return newVector;
  901. };
  902. /**
  903. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  904. */
  905. Vector2.Minimize = function (left, right) {
  906. var x = (left.x < right.x) ? left.x : right.x;
  907. var y = (left.y < right.y) ? left.y : right.y;
  908. return new Vector2(x, y);
  909. };
  910. /**
  911. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  912. */
  913. Vector2.Maximize = function (left, right) {
  914. var x = (left.x > right.x) ? left.x : right.x;
  915. var y = (left.y > right.y) ? left.y : right.y;
  916. return new Vector2(x, y);
  917. };
  918. /**
  919. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  920. */
  921. Vector2.Transform = function (vector, transformation) {
  922. var r = Vector2.Zero();
  923. Vector2.TransformToRef(vector, transformation, r);
  924. return r;
  925. };
  926. /**
  927. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  928. */
  929. Vector2.TransformToRef = function (vector, transformation, result) {
  930. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  931. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  932. result.x = x;
  933. result.y = y;
  934. };
  935. /**
  936. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  937. */
  938. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  939. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  940. var sign = a < 0 ? -1 : 1;
  941. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  942. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  943. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  944. };
  945. /**
  946. * Returns the distance (float) between the vectors "value1" and "value2".
  947. */
  948. Vector2.Distance = function (value1, value2) {
  949. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  950. };
  951. /**
  952. * Returns the squared distance (float) between the vectors "value1" and "value2".
  953. */
  954. Vector2.DistanceSquared = function (value1, value2) {
  955. var x = value1.x - value2.x;
  956. var y = value1.y - value2.y;
  957. return (x * x) + (y * y);
  958. };
  959. /**
  960. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  961. */
  962. Vector2.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. /**
  968. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  969. */
  970. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  971. var l2 = Vector2.DistanceSquared(segA, segB);
  972. if (l2 === 0.0) {
  973. return Vector2.Distance(p, segA);
  974. }
  975. var v = segB.subtract(segA);
  976. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  977. var proj = segA.add(v.multiplyByFloats(t, t));
  978. return Vector2.Distance(p, proj);
  979. };
  980. return Vector2;
  981. }());
  982. BABYLON.Vector2 = Vector2;
  983. var Vector3 = (function () {
  984. /**
  985. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  986. * A Vector3 is the main object used in 3D geometry.
  987. * It can represent etiher the coordinates of a point the space, either a direction.
  988. */
  989. function Vector3(x, y, z) {
  990. this.x = x;
  991. this.y = y;
  992. this.z = z;
  993. }
  994. /**
  995. * Returns a string with the Vector3 coordinates.
  996. */
  997. Vector3.prototype.toString = function () {
  998. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  999. };
  1000. /**
  1001. * Returns the string "Vector3"
  1002. */
  1003. Vector3.prototype.getClassName = function () {
  1004. return "Vector3";
  1005. };
  1006. /**
  1007. * Returns the Vector hash code.
  1008. */
  1009. Vector3.prototype.getHashCode = function () {
  1010. var hash = this.x || 0;
  1011. hash = (hash * 397) ^ (this.y || 0);
  1012. hash = (hash * 397) ^ (this.z || 0);
  1013. return hash;
  1014. };
  1015. // Operators
  1016. /**
  1017. * Returns a new array with three elements : the coordinates the Vector3.
  1018. */
  1019. Vector3.prototype.asArray = function () {
  1020. var result = [];
  1021. this.toArray(result, 0);
  1022. return result;
  1023. };
  1024. /**
  1025. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1026. * Returns the Vector3.
  1027. */
  1028. Vector3.prototype.toArray = function (array, index) {
  1029. if (index === void 0) { index = 0; }
  1030. array[index] = this.x;
  1031. array[index + 1] = this.y;
  1032. array[index + 2] = this.z;
  1033. return this;
  1034. };
  1035. /**
  1036. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1037. */
  1038. Vector3.prototype.toQuaternion = function () {
  1039. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1040. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1041. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1042. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1043. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1044. var cosy = Math.cos(this.y * 0.5);
  1045. var siny = Math.sin(this.y * 0.5);
  1046. result.x = coszMinusx * siny;
  1047. result.y = -sinzMinusx * siny;
  1048. result.z = sinxPlusz * cosy;
  1049. result.w = cosxPlusz * cosy;
  1050. return result;
  1051. };
  1052. /**
  1053. * Adds the passed vector to the current Vector3.
  1054. * Returns the updated Vector3.
  1055. */
  1056. Vector3.prototype.addInPlace = function (otherVector) {
  1057. this.x += otherVector.x;
  1058. this.y += otherVector.y;
  1059. this.z += otherVector.z;
  1060. return this;
  1061. };
  1062. /**
  1063. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1064. */
  1065. Vector3.prototype.add = function (otherVector) {
  1066. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1067. };
  1068. /**
  1069. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1070. * Returns the current Vector3.
  1071. */
  1072. Vector3.prototype.addToRef = function (otherVector, result) {
  1073. result.x = this.x + otherVector.x;
  1074. result.y = this.y + otherVector.y;
  1075. result.z = this.z + otherVector.z;
  1076. return this;
  1077. };
  1078. /**
  1079. * Subtract the passed vector from the current Vector3.
  1080. * Returns the updated Vector3.
  1081. */
  1082. Vector3.prototype.subtractInPlace = function (otherVector) {
  1083. this.x -= otherVector.x;
  1084. this.y -= otherVector.y;
  1085. this.z -= otherVector.z;
  1086. return this;
  1087. };
  1088. /**
  1089. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1090. */
  1091. Vector3.prototype.subtract = function (otherVector) {
  1092. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1093. };
  1094. /**
  1095. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1096. * Returns the current Vector3.
  1097. */
  1098. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1099. result.x = this.x - otherVector.x;
  1100. result.y = this.y - otherVector.y;
  1101. result.z = this.z - otherVector.z;
  1102. return this;
  1103. };
  1104. /**
  1105. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1106. */
  1107. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1108. return new Vector3(this.x - x, this.y - y, this.z - z);
  1109. };
  1110. /**
  1111. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1112. * Returns the current Vector3.
  1113. */
  1114. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1115. result.x = this.x - x;
  1116. result.y = this.y - y;
  1117. result.z = this.z - z;
  1118. return this;
  1119. };
  1120. /**
  1121. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1122. */
  1123. Vector3.prototype.negate = function () {
  1124. return new Vector3(-this.x, -this.y, -this.z);
  1125. };
  1126. /**
  1127. * Multiplies the Vector3 coordinates by the float "scale".
  1128. * Returns the updated Vector3.
  1129. */
  1130. Vector3.prototype.scaleInPlace = function (scale) {
  1131. this.x *= scale;
  1132. this.y *= scale;
  1133. this.z *= scale;
  1134. return this;
  1135. };
  1136. /**
  1137. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1138. */
  1139. Vector3.prototype.scale = function (scale) {
  1140. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1141. };
  1142. /**
  1143. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1144. * Returns the current Vector3.
  1145. */
  1146. Vector3.prototype.scaleToRef = function (scale, result) {
  1147. result.x = this.x * scale;
  1148. result.y = this.y * scale;
  1149. result.z = this.z * scale;
  1150. return this;
  1151. };
  1152. /**
  1153. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1154. */
  1155. Vector3.prototype.equals = function (otherVector) {
  1156. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1157. };
  1158. /**
  1159. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1160. */
  1161. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1162. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1163. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1164. };
  1165. /**
  1166. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1167. */
  1168. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1169. return this.x === x && this.y === y && this.z === z;
  1170. };
  1171. /**
  1172. * Muliplies the current Vector3 coordinates by the passed ones.
  1173. * Returns the updated Vector3.
  1174. */
  1175. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1176. this.x *= otherVector.x;
  1177. this.y *= otherVector.y;
  1178. this.z *= otherVector.z;
  1179. return this;
  1180. };
  1181. /**
  1182. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1183. */
  1184. Vector3.prototype.multiply = function (otherVector) {
  1185. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1186. };
  1187. /**
  1188. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1189. * Returns the current Vector3.
  1190. */
  1191. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1192. result.x = this.x * otherVector.x;
  1193. result.y = this.y * otherVector.y;
  1194. result.z = this.z * otherVector.z;
  1195. return this;
  1196. };
  1197. /**
  1198. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1199. */
  1200. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1201. return new Vector3(this.x * x, this.y * y, this.z * z);
  1202. };
  1203. /**
  1204. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1205. */
  1206. Vector3.prototype.divide = function (otherVector) {
  1207. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1208. };
  1209. /**
  1210. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1211. * Returns the current Vector3.
  1212. */
  1213. Vector3.prototype.divideToRef = function (otherVector, result) {
  1214. result.x = this.x / otherVector.x;
  1215. result.y = this.y / otherVector.y;
  1216. result.z = this.z / otherVector.z;
  1217. return this;
  1218. };
  1219. /**
  1220. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1221. * Returns the updated Vector3.
  1222. */
  1223. Vector3.prototype.MinimizeInPlace = function (other) {
  1224. if (other.x < this.x)
  1225. this.x = other.x;
  1226. if (other.y < this.y)
  1227. this.y = other.y;
  1228. if (other.z < this.z)
  1229. this.z = other.z;
  1230. return this;
  1231. };
  1232. /**
  1233. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1234. * Returns the updated Vector3.
  1235. */
  1236. Vector3.prototype.MaximizeInPlace = function (other) {
  1237. if (other.x > this.x)
  1238. this.x = other.x;
  1239. if (other.y > this.y)
  1240. this.y = other.y;
  1241. if (other.z > this.z)
  1242. this.z = other.z;
  1243. return this;
  1244. };
  1245. // Properties
  1246. /**
  1247. * Returns the length of the Vector3 (float).
  1248. */
  1249. Vector3.prototype.length = function () {
  1250. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1251. };
  1252. /**
  1253. * Returns the squared length of the Vector3 (float).
  1254. */
  1255. Vector3.prototype.lengthSquared = function () {
  1256. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1257. };
  1258. // Methods
  1259. /**
  1260. * Normalize the current Vector3.
  1261. * Returns the updated Vector3.
  1262. */
  1263. Vector3.prototype.normalize = function () {
  1264. var len = this.length();
  1265. if (len === 0 || len === 1.0)
  1266. return this;
  1267. var num = 1.0 / len;
  1268. this.x *= num;
  1269. this.y *= num;
  1270. this.z *= num;
  1271. return this;
  1272. };
  1273. /**
  1274. * Returns a new Vector3 copied from the current Vector3.
  1275. */
  1276. Vector3.prototype.clone = function () {
  1277. return new Vector3(this.x, this.y, this.z);
  1278. };
  1279. /**
  1280. * Copies the passed vector coordinates to the current Vector3 ones.
  1281. * Returns the updated Vector3.
  1282. */
  1283. Vector3.prototype.copyFrom = function (source) {
  1284. this.x = source.x;
  1285. this.y = source.y;
  1286. this.z = source.z;
  1287. return this;
  1288. };
  1289. /**
  1290. * Copies the passed floats to the current Vector3 coordinates.
  1291. * Returns the updated Vector3.
  1292. */
  1293. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1294. this.x = x;
  1295. this.y = y;
  1296. this.z = z;
  1297. return this;
  1298. };
  1299. /**
  1300. * Copies the passed floats to the current Vector3 coordinates.
  1301. * Returns the updated Vector3.
  1302. */
  1303. Vector3.prototype.set = function (x, y, z) {
  1304. return this.copyFromFloats(x, y, z);
  1305. };
  1306. // Statics
  1307. /**
  1308. *
  1309. */
  1310. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1311. var d0 = Vector3.Dot(vector0, axis) - size;
  1312. var d1 = Vector3.Dot(vector1, axis) - size;
  1313. var s = d0 / (d0 - d1);
  1314. return s;
  1315. };
  1316. /**
  1317. * Returns a new Vector3 set from the index "offset" of the passed array.
  1318. */
  1319. Vector3.FromArray = function (array, offset) {
  1320. if (!offset) {
  1321. offset = 0;
  1322. }
  1323. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1324. };
  1325. /**
  1326. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1327. * This function is deprecated. Use FromArray instead.
  1328. */
  1329. Vector3.FromFloatArray = function (array, offset) {
  1330. return Vector3.FromArray(array, offset);
  1331. };
  1332. /**
  1333. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1334. */
  1335. Vector3.FromArrayToRef = function (array, offset, result) {
  1336. result.x = array[offset];
  1337. result.y = array[offset + 1];
  1338. result.z = array[offset + 2];
  1339. };
  1340. /**
  1341. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1342. * This function is deprecated. Use FromArrayToRef instead.
  1343. */
  1344. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1345. return Vector3.FromArrayToRef(array, offset, result);
  1346. };
  1347. /**
  1348. * Sets the passed vector "result" with the passed floats.
  1349. */
  1350. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1351. result.x = x;
  1352. result.y = y;
  1353. result.z = z;
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1357. */
  1358. Vector3.Zero = function () {
  1359. return new Vector3(0.0, 0.0, 0.0);
  1360. };
  1361. /**
  1362. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1363. */
  1364. Vector3.One = function () {
  1365. return new Vector3(1.0, 1.0, 1.0);
  1366. };
  1367. /**
  1368. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1369. */
  1370. Vector3.Up = function () {
  1371. return new Vector3(0.0, 1.0, 0.0);
  1372. };
  1373. /**
  1374. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1375. */
  1376. Vector3.Forward = function () {
  1377. return new Vector3(0.0, 0.0, 1.0);
  1378. };
  1379. /**
  1380. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1381. */
  1382. Vector3.Right = function () {
  1383. return new Vector3(1.0, 0.0, 0.0);
  1384. };
  1385. /**
  1386. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1387. */
  1388. Vector3.Left = function () {
  1389. return new Vector3(-1.0, 0.0, 0.0);
  1390. };
  1391. /**
  1392. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1393. * This method computes tranformed coordinates only, not transformed direction vectors.
  1394. */
  1395. Vector3.TransformCoordinates = function (vector, transformation) {
  1396. var result = Vector3.Zero();
  1397. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1398. return result;
  1399. };
  1400. /**
  1401. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1402. * This method computes tranformed coordinates only, not transformed direction vectors.
  1403. */
  1404. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1408. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1409. result.x = x / w;
  1410. result.y = y / w;
  1411. result.z = z / w;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1418. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1419. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1420. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1421. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1422. result.x = rx / rw;
  1423. result.y = ry / rw;
  1424. result.z = rz / rw;
  1425. };
  1426. /**
  1427. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1428. * This methods computes transformed normalized direction vectors only.
  1429. */
  1430. Vector3.TransformNormal = function (vector, transformation) {
  1431. var result = Vector3.Zero();
  1432. Vector3.TransformNormalToRef(vector, transformation, result);
  1433. return result;
  1434. };
  1435. /**
  1436. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1437. * This methods computes transformed normalized direction vectors only.
  1438. */
  1439. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1443. result.x = x;
  1444. result.y = y;
  1445. result.z = z;
  1446. };
  1447. /**
  1448. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1449. * This methods computes transformed normalized direction vectors only.
  1450. */
  1451. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1452. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1453. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1454. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1455. };
  1456. /**
  1457. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1458. */
  1459. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1460. var squared = amount * amount;
  1461. var cubed = amount * squared;
  1462. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1463. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1464. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1465. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1466. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1467. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1468. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1469. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1470. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1471. return new Vector3(x, y, z);
  1472. };
  1473. /**
  1474. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1475. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1476. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1477. */
  1478. Vector3.Clamp = function (value, min, max) {
  1479. var x = value.x;
  1480. x = (x > max.x) ? max.x : x;
  1481. x = (x < min.x) ? min.x : x;
  1482. var y = value.y;
  1483. y = (y > max.y) ? max.y : y;
  1484. y = (y < min.y) ? min.y : y;
  1485. var z = value.z;
  1486. z = (z > max.z) ? max.z : z;
  1487. z = (z < min.z) ? min.z : z;
  1488. return new Vector3(x, y, z);
  1489. };
  1490. /**
  1491. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1492. */
  1493. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1494. var squared = amount * amount;
  1495. var cubed = amount * squared;
  1496. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1497. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1498. var part3 = (cubed - (2.0 * squared)) + amount;
  1499. var part4 = cubed - squared;
  1500. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1501. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1502. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1503. return new Vector3(x, y, z);
  1504. };
  1505. /**
  1506. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1507. */
  1508. Vector3.Lerp = function (start, end, amount) {
  1509. var result = new Vector3(0, 0, 0);
  1510. Vector3.LerpToRef(start, end, amount, result);
  1511. return result;
  1512. };
  1513. /**
  1514. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1515. */
  1516. Vector3.LerpToRef = function (start, end, amount, result) {
  1517. result.x = start.x + ((end.x - start.x) * amount);
  1518. result.y = start.y + ((end.y - start.y) * amount);
  1519. result.z = start.z + ((end.z - start.z) * amount);
  1520. };
  1521. /**
  1522. * Returns the dot product (float) between the vectors "left" and "right".
  1523. */
  1524. Vector3.Dot = function (left, right) {
  1525. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1526. };
  1527. /**
  1528. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1529. * The cross product is then orthogonal to both "left" and "right".
  1530. */
  1531. Vector3.Cross = function (left, right) {
  1532. var result = Vector3.Zero();
  1533. Vector3.CrossToRef(left, right, result);
  1534. return result;
  1535. };
  1536. /**
  1537. * Sets the passed vector "result" with the cross product of "left" and "right".
  1538. * The cross product is then orthogonal to both "left" and "right".
  1539. */
  1540. Vector3.CrossToRef = function (left, right, result) {
  1541. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1542. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1543. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1544. result.copyFrom(MathTmp.Vector3[0]);
  1545. };
  1546. /**
  1547. * Returns a new Vector3 as the normalization of the passed vector.
  1548. */
  1549. Vector3.Normalize = function (vector) {
  1550. var result = Vector3.Zero();
  1551. Vector3.NormalizeToRef(vector, result);
  1552. return result;
  1553. };
  1554. /**
  1555. * Sets the passed vector "result" with the normalization of the passed first vector.
  1556. */
  1557. Vector3.NormalizeToRef = function (vector, result) {
  1558. result.copyFrom(vector);
  1559. result.normalize();
  1560. };
  1561. Vector3.Project = function (vector, world, transform, viewport) {
  1562. var cw = viewport.width;
  1563. var ch = viewport.height;
  1564. var cx = viewport.x;
  1565. var cy = viewport.y;
  1566. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1567. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1568. var matrix = MathTmp.Matrix[0];
  1569. world.multiplyToRef(transform, matrix);
  1570. matrix.multiplyToRef(viewportMatrix, matrix);
  1571. return Vector3.TransformCoordinates(vector, matrix);
  1572. };
  1573. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1574. var matrix = MathTmp.Matrix[0];
  1575. world.multiplyToRef(transform, matrix);
  1576. matrix.invert();
  1577. source.x = source.x / viewportWidth * 2 - 1;
  1578. source.y = -(source.y / viewportHeight * 2 - 1);
  1579. var vector = Vector3.TransformCoordinates(source, matrix);
  1580. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1581. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1582. vector = vector.scale(1.0 / num);
  1583. }
  1584. return vector;
  1585. };
  1586. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1587. var matrix = MathTmp.Matrix[0];
  1588. world.multiplyToRef(view, matrix);
  1589. matrix.multiplyToRef(projection, matrix);
  1590. matrix.invert();
  1591. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1592. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1593. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1594. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Minimize = function (left, right) {
  1600. var min = left.clone();
  1601. min.MinimizeInPlace(right);
  1602. return min;
  1603. };
  1604. Vector3.Maximize = function (left, right) {
  1605. var max = left.clone();
  1606. max.MaximizeInPlace(right);
  1607. return max;
  1608. };
  1609. /**
  1610. * Returns the distance (float) between the vectors "value1" and "value2".
  1611. */
  1612. Vector3.Distance = function (value1, value2) {
  1613. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1614. };
  1615. /**
  1616. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1617. */
  1618. Vector3.DistanceSquared = function (value1, value2) {
  1619. var x = value1.x - value2.x;
  1620. var y = value1.y - value2.y;
  1621. var z = value1.z - value2.z;
  1622. return (x * x) + (y * y) + (z * z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 located at the center between "value1" and "value2".
  1626. */
  1627. Vector3.Center = function (value1, value2) {
  1628. var center = value1.add(value2);
  1629. center.scaleInPlace(0.5);
  1630. return center;
  1631. };
  1632. /**
  1633. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1634. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1635. * to something in order to rotate it from its local system to the given target system.
  1636. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1637. * Returns a new Vector3.
  1638. */
  1639. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1640. var rotation = Vector3.Zero();
  1641. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1642. return rotation;
  1643. };
  1644. /**
  1645. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1646. */
  1647. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1648. var quat = MathTmp.Quaternion[0];
  1649. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1650. quat.toEulerAnglesToRef(ref);
  1651. };
  1652. return Vector3;
  1653. }());
  1654. BABYLON.Vector3 = Vector3;
  1655. //Vector4 class created for EulerAngle class conversion to Quaternion
  1656. var Vector4 = (function () {
  1657. /**
  1658. * Creates a Vector4 object from the passed floats.
  1659. */
  1660. function Vector4(x, y, z, w) {
  1661. this.x = x;
  1662. this.y = y;
  1663. this.z = z;
  1664. this.w = w;
  1665. }
  1666. /**
  1667. * Returns the string with the Vector4 coordinates.
  1668. */
  1669. Vector4.prototype.toString = function () {
  1670. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1671. };
  1672. /**
  1673. * Returns the string "Vector4".
  1674. */
  1675. Vector4.prototype.getClassName = function () {
  1676. return "Vector4";
  1677. };
  1678. /**
  1679. * Returns the Vector4 hash code.
  1680. */
  1681. Vector4.prototype.getHashCode = function () {
  1682. var hash = this.x || 0;
  1683. hash = (hash * 397) ^ (this.y || 0);
  1684. hash = (hash * 397) ^ (this.z || 0);
  1685. hash = (hash * 397) ^ (this.w || 0);
  1686. return hash;
  1687. };
  1688. // Operators
  1689. /**
  1690. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1691. */
  1692. Vector4.prototype.asArray = function () {
  1693. var result = [];
  1694. this.toArray(result, 0);
  1695. return result;
  1696. };
  1697. /**
  1698. * Populates the passed array from the passed index with the Vector4 coordinates.
  1699. * Returns the Vector4.
  1700. */
  1701. Vector4.prototype.toArray = function (array, index) {
  1702. if (index === undefined) {
  1703. index = 0;
  1704. }
  1705. array[index] = this.x;
  1706. array[index + 1] = this.y;
  1707. array[index + 2] = this.z;
  1708. array[index + 3] = this.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Adds the passed vector to the current Vector4.
  1713. * Returns the updated Vector4.
  1714. */
  1715. Vector4.prototype.addInPlace = function (otherVector) {
  1716. this.x += otherVector.x;
  1717. this.y += otherVector.y;
  1718. this.z += otherVector.z;
  1719. this.w += otherVector.w;
  1720. return this;
  1721. };
  1722. /**
  1723. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1724. */
  1725. Vector4.prototype.add = function (otherVector) {
  1726. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1727. };
  1728. /**
  1729. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1730. * Returns the current Vector4.
  1731. */
  1732. Vector4.prototype.addToRef = function (otherVector, result) {
  1733. result.x = this.x + otherVector.x;
  1734. result.y = this.y + otherVector.y;
  1735. result.z = this.z + otherVector.z;
  1736. result.w = this.w + otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Subtract in place the passed vector from the current Vector4.
  1741. * Returns the updated Vector4.
  1742. */
  1743. Vector4.prototype.subtractInPlace = function (otherVector) {
  1744. this.x -= otherVector.x;
  1745. this.y -= otherVector.y;
  1746. this.z -= otherVector.z;
  1747. this.w -= otherVector.w;
  1748. return this;
  1749. };
  1750. /**
  1751. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1752. */
  1753. Vector4.prototype.subtract = function (otherVector) {
  1754. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1755. };
  1756. /**
  1757. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1758. * Returns the current Vector4.
  1759. */
  1760. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1761. result.x = this.x - otherVector.x;
  1762. result.y = this.y - otherVector.y;
  1763. result.z = this.z - otherVector.z;
  1764. result.w = this.w - otherVector.w;
  1765. return this;
  1766. };
  1767. /**
  1768. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1769. */
  1770. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1771. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1772. };
  1773. /**
  1774. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1775. * Returns the current Vector4.
  1776. */
  1777. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1778. result.x = this.x - x;
  1779. result.y = this.y - y;
  1780. result.z = this.z - z;
  1781. result.w = this.w - w;
  1782. return this;
  1783. };
  1784. /**
  1785. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1786. */
  1787. Vector4.prototype.negate = function () {
  1788. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1789. };
  1790. /**
  1791. * Multiplies the current Vector4 coordinates by scale (float).
  1792. * Returns the updated Vector4.
  1793. */
  1794. Vector4.prototype.scaleInPlace = function (scale) {
  1795. this.x *= scale;
  1796. this.y *= scale;
  1797. this.z *= scale;
  1798. this.w *= scale;
  1799. return this;
  1800. };
  1801. /**
  1802. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1803. */
  1804. Vector4.prototype.scale = function (scale) {
  1805. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1806. };
  1807. /**
  1808. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1809. * Returns the current Vector4.
  1810. */
  1811. Vector4.prototype.scaleToRef = function (scale, result) {
  1812. result.x = this.x * scale;
  1813. result.y = this.y * scale;
  1814. result.z = this.z * scale;
  1815. result.w = this.w * scale;
  1816. return this;
  1817. };
  1818. /**
  1819. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1820. */
  1821. Vector4.prototype.equals = function (otherVector) {
  1822. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1823. };
  1824. /**
  1825. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1826. */
  1827. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1828. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1829. return otherVector
  1830. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1831. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1832. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1833. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1834. };
  1835. /**
  1836. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1837. */
  1838. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1839. return this.x === x && this.y === y && this.z === z && this.w === w;
  1840. };
  1841. /**
  1842. * Multiplies in place the current Vector4 by the passed one.
  1843. * Returns the updated Vector4.
  1844. */
  1845. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1846. this.x *= otherVector.x;
  1847. this.y *= otherVector.y;
  1848. this.z *= otherVector.z;
  1849. this.w *= otherVector.w;
  1850. return this;
  1851. };
  1852. /**
  1853. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1854. */
  1855. Vector4.prototype.multiply = function (otherVector) {
  1856. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1857. };
  1858. /**
  1859. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1860. * Returns the current Vector4.
  1861. */
  1862. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1863. result.x = this.x * otherVector.x;
  1864. result.y = this.y * otherVector.y;
  1865. result.z = this.z * otherVector.z;
  1866. result.w = this.w * otherVector.w;
  1867. return this;
  1868. };
  1869. /**
  1870. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1871. */
  1872. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1873. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1874. };
  1875. /**
  1876. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1877. */
  1878. Vector4.prototype.divide = function (otherVector) {
  1879. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1880. };
  1881. /**
  1882. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1883. * Returns the current Vector4.
  1884. */
  1885. Vector4.prototype.divideToRef = function (otherVector, result) {
  1886. result.x = this.x / otherVector.x;
  1887. result.y = this.y / otherVector.y;
  1888. result.z = this.z / otherVector.z;
  1889. result.w = this.w / otherVector.w;
  1890. return this;
  1891. };
  1892. /**
  1893. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1894. */
  1895. Vector4.prototype.MinimizeInPlace = function (other) {
  1896. if (other.x < this.x)
  1897. this.x = other.x;
  1898. if (other.y < this.y)
  1899. this.y = other.y;
  1900. if (other.z < this.z)
  1901. this.z = other.z;
  1902. if (other.w < this.w)
  1903. this.w = other.w;
  1904. return this;
  1905. };
  1906. /**
  1907. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1908. */
  1909. Vector4.prototype.MaximizeInPlace = function (other) {
  1910. if (other.x > this.x)
  1911. this.x = other.x;
  1912. if (other.y > this.y)
  1913. this.y = other.y;
  1914. if (other.z > this.z)
  1915. this.z = other.z;
  1916. if (other.w > this.w)
  1917. this.w = other.w;
  1918. return this;
  1919. };
  1920. // Properties
  1921. /**
  1922. * Returns the Vector4 length (float).
  1923. */
  1924. Vector4.prototype.length = function () {
  1925. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1926. };
  1927. /**
  1928. * Returns the Vector4 squared length (float).
  1929. */
  1930. Vector4.prototype.lengthSquared = function () {
  1931. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1932. };
  1933. // Methods
  1934. /**
  1935. * Normalizes in place the Vector4.
  1936. * Returns the updated Vector4.
  1937. */
  1938. Vector4.prototype.normalize = function () {
  1939. var len = this.length();
  1940. if (len === 0)
  1941. return this;
  1942. var num = 1.0 / len;
  1943. this.x *= num;
  1944. this.y *= num;
  1945. this.z *= num;
  1946. this.w *= num;
  1947. return this;
  1948. };
  1949. /**
  1950. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1951. */
  1952. Vector4.prototype.toVector3 = function () {
  1953. return new Vector3(this.x, this.y, this.z);
  1954. };
  1955. /**
  1956. * Returns a new Vector4 copied from the current one.
  1957. */
  1958. Vector4.prototype.clone = function () {
  1959. return new Vector4(this.x, this.y, this.z, this.w);
  1960. };
  1961. /**
  1962. * Updates the current Vector4 with the passed one coordinates.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFrom = function (source) {
  1966. this.x = source.x;
  1967. this.y = source.y;
  1968. this.z = source.z;
  1969. this.w = source.w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1977. this.x = x;
  1978. this.y = y;
  1979. this.z = z;
  1980. this.w = w;
  1981. return this;
  1982. };
  1983. /**
  1984. * Updates the current Vector4 coordinates with the passed floats.
  1985. * Returns the updated Vector4.
  1986. */
  1987. Vector4.prototype.set = function (x, y, z, w) {
  1988. return this.copyFromFloats(x, y, z, w);
  1989. };
  1990. // Statics
  1991. /**
  1992. * Returns a new Vector4 set from the starting index of the passed array.
  1993. */
  1994. Vector4.FromArray = function (array, offset) {
  1995. if (!offset) {
  1996. offset = 0;
  1997. }
  1998. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1999. };
  2000. /**
  2001. * Updates the passed vector "result" from the starting index of the passed array.
  2002. */
  2003. Vector4.FromArrayToRef = function (array, offset, result) {
  2004. result.x = array[offset];
  2005. result.y = array[offset + 1];
  2006. result.z = array[offset + 2];
  2007. result.w = array[offset + 3];
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2011. */
  2012. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2013. Vector4.FromArrayToRef(array, offset, result);
  2014. };
  2015. /**
  2016. * Updates the passed vector "result" coordinates from the passed floats.
  2017. */
  2018. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2019. result.x = x;
  2020. result.y = y;
  2021. result.z = z;
  2022. result.w = w;
  2023. };
  2024. /**
  2025. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2026. */
  2027. Vector4.Zero = function () {
  2028. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2029. };
  2030. /**
  2031. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2032. */
  2033. Vector4.One = function () {
  2034. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2035. };
  2036. /**
  2037. * Returns a new normalized Vector4 from the passed one.
  2038. */
  2039. Vector4.Normalize = function (vector) {
  2040. var result = Vector4.Zero();
  2041. Vector4.NormalizeToRef(vector, result);
  2042. return result;
  2043. };
  2044. /**
  2045. * Updates the passed vector "result" from the normalization of the passed one.
  2046. */
  2047. Vector4.NormalizeToRef = function (vector, result) {
  2048. result.copyFrom(vector);
  2049. result.normalize();
  2050. };
  2051. Vector4.Minimize = function (left, right) {
  2052. var min = left.clone();
  2053. min.MinimizeInPlace(right);
  2054. return min;
  2055. };
  2056. Vector4.Maximize = function (left, right) {
  2057. var max = left.clone();
  2058. max.MaximizeInPlace(right);
  2059. return max;
  2060. };
  2061. /**
  2062. * Returns the distance (float) between the vectors "value1" and "value2".
  2063. */
  2064. Vector4.Distance = function (value1, value2) {
  2065. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2066. };
  2067. /**
  2068. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.DistanceSquared = function (value1, value2) {
  2071. var x = value1.x - value2.x;
  2072. var y = value1.y - value2.y;
  2073. var z = value1.z - value2.z;
  2074. var w = value1.w - value2.w;
  2075. return (x * x) + (y * y) + (z * z) + (w * w);
  2076. };
  2077. /**
  2078. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2079. */
  2080. Vector4.Center = function (value1, value2) {
  2081. var center = value1.add(value2);
  2082. center.scaleInPlace(0.5);
  2083. return center;
  2084. };
  2085. /**
  2086. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2087. * This methods computes transformed normalized direction vectors only.
  2088. */
  2089. Vector4.TransformNormal = function (vector, transformation) {
  2090. var result = Vector4.Zero();
  2091. Vector4.TransformNormalToRef(vector, transformation, result);
  2092. return result;
  2093. };
  2094. /**
  2095. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2096. * This methods computes transformed normalized direction vectors only.
  2097. */
  2098. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2099. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2100. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2101. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2102. result.x = x;
  2103. result.y = y;
  2104. result.z = z;
  2105. result.w = vector.w;
  2106. };
  2107. /**
  2108. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2109. * This methods computes transformed normalized direction vectors only.
  2110. */
  2111. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2112. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2113. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2114. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2115. result.w = w;
  2116. };
  2117. return Vector4;
  2118. }());
  2119. BABYLON.Vector4 = Vector4;
  2120. var Size = (function () {
  2121. /**
  2122. * Creates a Size object from the passed width and height (floats).
  2123. */
  2124. function Size(width, height) {
  2125. this.width = width;
  2126. this.height = height;
  2127. }
  2128. // Returns a string with the Size width and height.
  2129. Size.prototype.toString = function () {
  2130. return "{W: " + this.width + ", H: " + this.height + "}";
  2131. };
  2132. /**
  2133. * Returns the string "Size"
  2134. */
  2135. Size.prototype.getClassName = function () {
  2136. return "Size";
  2137. };
  2138. /**
  2139. * Returns the Size hash code.
  2140. */
  2141. Size.prototype.getHashCode = function () {
  2142. var hash = this.width || 0;
  2143. hash = (hash * 397) ^ (this.height || 0);
  2144. return hash;
  2145. };
  2146. /**
  2147. * Updates the current size from the passed one.
  2148. * Returns the updated Size.
  2149. */
  2150. Size.prototype.copyFrom = function (src) {
  2151. this.width = src.width;
  2152. this.height = src.height;
  2153. };
  2154. /**
  2155. * Updates in place the current Size from the passed floats.
  2156. * Returns the updated Size.
  2157. */
  2158. Size.prototype.copyFromFloats = function (width, height) {
  2159. this.width = width;
  2160. this.height = height;
  2161. return this;
  2162. };
  2163. /**
  2164. * Updates in place the current Size from the passed floats.
  2165. * Returns the updated Size.
  2166. */
  2167. Size.prototype.set = function (width, height) {
  2168. return this.copyFromFloats(width, height);
  2169. };
  2170. /**
  2171. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2172. */
  2173. Size.prototype.multiplyByFloats = function (w, h) {
  2174. return new Size(this.width * w, this.height * h);
  2175. };
  2176. /**
  2177. * Returns a new Size copied from the passed one.
  2178. */
  2179. Size.prototype.clone = function () {
  2180. return new Size(this.width, this.height);
  2181. };
  2182. /**
  2183. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2184. */
  2185. Size.prototype.equals = function (other) {
  2186. if (!other) {
  2187. return false;
  2188. }
  2189. return (this.width === other.width) && (this.height === other.height);
  2190. };
  2191. Object.defineProperty(Size.prototype, "surface", {
  2192. /**
  2193. * Returns the surface of the Size : width * height (float).
  2194. */
  2195. get: function () {
  2196. return this.width * this.height;
  2197. },
  2198. enumerable: true,
  2199. configurable: true
  2200. });
  2201. /**
  2202. * Returns a new Size set to (0.0, 0.0)
  2203. */
  2204. Size.Zero = function () {
  2205. return new Size(0.0, 0.0);
  2206. };
  2207. /**
  2208. * Returns a new Size set as the addition result of the current Size and the passed one.
  2209. */
  2210. Size.prototype.add = function (otherSize) {
  2211. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2212. return r;
  2213. };
  2214. /**
  2215. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2216. */
  2217. Size.prototype.subtract = function (otherSize) {
  2218. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2223. */
  2224. Size.Lerp = function (start, end, amount) {
  2225. var w = start.width + ((end.width - start.width) * amount);
  2226. var h = start.height + ((end.height - start.height) * amount);
  2227. return new Size(w, h);
  2228. };
  2229. return Size;
  2230. }());
  2231. BABYLON.Size = Size;
  2232. var Quaternion = (function () {
  2233. /**
  2234. * Creates a new Quaternion from the passed floats.
  2235. */
  2236. function Quaternion(x, y, z, w) {
  2237. if (x === void 0) { x = 0.0; }
  2238. if (y === void 0) { y = 0.0; }
  2239. if (z === void 0) { z = 0.0; }
  2240. if (w === void 0) { w = 1.0; }
  2241. this.x = x;
  2242. this.y = y;
  2243. this.z = z;
  2244. this.w = w;
  2245. }
  2246. /**
  2247. * Returns a string with the Quaternion coordinates.
  2248. */
  2249. Quaternion.prototype.toString = function () {
  2250. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2251. };
  2252. /**
  2253. * Returns the string "Quaternion".
  2254. */
  2255. Quaternion.prototype.getClassName = function () {
  2256. return "Quaternion";
  2257. };
  2258. /**
  2259. * Returns the Quaternion hash code.
  2260. */
  2261. Quaternion.prototype.getHashCode = function () {
  2262. var hash = this.x || 0;
  2263. hash = (hash * 397) ^ (this.y || 0);
  2264. hash = (hash * 397) ^ (this.z || 0);
  2265. hash = (hash * 397) ^ (this.w || 0);
  2266. return hash;
  2267. };
  2268. /**
  2269. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2270. */
  2271. Quaternion.prototype.asArray = function () {
  2272. return [this.x, this.y, this.z, this.w];
  2273. };
  2274. /**
  2275. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2276. */
  2277. Quaternion.prototype.equals = function (otherQuaternion) {
  2278. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2279. };
  2280. /**
  2281. * Returns a new Quaternion copied from the current one.
  2282. */
  2283. Quaternion.prototype.clone = function () {
  2284. return new Quaternion(this.x, this.y, this.z, this.w);
  2285. };
  2286. /**
  2287. * Updates the current Quaternion from the passed one coordinates.
  2288. * Returns the updated Quaterion.
  2289. */
  2290. Quaternion.prototype.copyFrom = function (other) {
  2291. this.x = other.x;
  2292. this.y = other.y;
  2293. this.z = other.z;
  2294. this.w = other.w;
  2295. return this;
  2296. };
  2297. /**
  2298. * Updates the current Quaternion from the passed float coordinates.
  2299. * Returns the updated Quaterion.
  2300. */
  2301. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2302. this.x = x;
  2303. this.y = y;
  2304. this.z = z;
  2305. this.w = w;
  2306. return this;
  2307. };
  2308. /**
  2309. * Updates the current Quaternion from the passed float coordinates.
  2310. * Returns the updated Quaterion.
  2311. */
  2312. Quaternion.prototype.set = function (x, y, z, w) {
  2313. return this.copyFromFloats(x, y, z, w);
  2314. };
  2315. /**
  2316. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2317. */
  2318. Quaternion.prototype.add = function (other) {
  2319. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2320. };
  2321. /**
  2322. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2323. */
  2324. Quaternion.prototype.subtract = function (other) {
  2325. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2326. };
  2327. /**
  2328. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2329. */
  2330. Quaternion.prototype.scale = function (value) {
  2331. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2332. };
  2333. /**
  2334. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2335. */
  2336. Quaternion.prototype.multiply = function (q1) {
  2337. var result = new Quaternion(0, 0, 0, 1.0);
  2338. this.multiplyToRef(q1, result);
  2339. return result;
  2340. };
  2341. /**
  2342. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2343. * Returns the current Quaternion.
  2344. */
  2345. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2346. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2347. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2348. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2349. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2350. result.copyFromFloats(x, y, z, w);
  2351. return this;
  2352. };
  2353. /**
  2354. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2355. * Returns the updated Quaternion.
  2356. */
  2357. Quaternion.prototype.multiplyInPlace = function (q1) {
  2358. this.multiplyToRef(q1, this);
  2359. return this;
  2360. };
  2361. /**
  2362. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2363. * Returns the current Quaternion.
  2364. */
  2365. Quaternion.prototype.conjugateToRef = function (ref) {
  2366. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2367. return this;
  2368. };
  2369. /**
  2370. * Conjugates in place the current Quaternion.
  2371. * Returns the updated Quaternion.
  2372. */
  2373. Quaternion.prototype.conjugateInPlace = function () {
  2374. this.x *= -1;
  2375. this.y *= -1;
  2376. this.z *= -1;
  2377. return this;
  2378. };
  2379. /**
  2380. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2381. */
  2382. Quaternion.prototype.conjugate = function () {
  2383. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2384. return result;
  2385. };
  2386. /**
  2387. * Returns the Quaternion length (float).
  2388. */
  2389. Quaternion.prototype.length = function () {
  2390. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2391. };
  2392. /**
  2393. * Normalize in place the current Quaternion.
  2394. * Returns the updated Quaternion.
  2395. */
  2396. Quaternion.prototype.normalize = function () {
  2397. var length = 1.0 / this.length();
  2398. this.x *= length;
  2399. this.y *= length;
  2400. this.z *= length;
  2401. this.w *= length;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAngles = function (order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var result = Vector3.Zero();
  2410. this.toEulerAnglesToRef(result, order);
  2411. return result;
  2412. };
  2413. /**
  2414. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2415. * Returns the current Quaternion.
  2416. */
  2417. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2418. if (order === void 0) { order = "YZX"; }
  2419. var qz = this.z;
  2420. var qx = this.x;
  2421. var qy = this.y;
  2422. var qw = this.w;
  2423. var sqw = qw * qw;
  2424. var sqz = qz * qz;
  2425. var sqx = qx * qx;
  2426. var sqy = qy * qy;
  2427. var zAxisY = qy * qz - qx * qw;
  2428. var limit = .4999999;
  2429. if (zAxisY < -limit) {
  2430. result.y = 2 * Math.atan2(qy, qw);
  2431. result.x = Math.PI / 2;
  2432. result.z = 0;
  2433. }
  2434. else if (zAxisY > limit) {
  2435. result.y = 2 * Math.atan2(qy, qw);
  2436. result.x = -Math.PI / 2;
  2437. result.z = 0;
  2438. }
  2439. else {
  2440. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2441. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2442. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2443. }
  2444. return this;
  2445. };
  2446. /**
  2447. * Updates the passed rotation matrix with the current Quaternion values.
  2448. * Returns the current Quaternion.
  2449. */
  2450. Quaternion.prototype.toRotationMatrix = function (result) {
  2451. var xx = this.x * this.x;
  2452. var yy = this.y * this.y;
  2453. var zz = this.z * this.z;
  2454. var xy = this.x * this.y;
  2455. var zw = this.z * this.w;
  2456. var zx = this.z * this.x;
  2457. var yw = this.y * this.w;
  2458. var yz = this.y * this.z;
  2459. var xw = this.x * this.w;
  2460. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2461. result.m[1] = 2.0 * (xy + zw);
  2462. result.m[2] = 2.0 * (zx - yw);
  2463. result.m[3] = 0;
  2464. result.m[4] = 2.0 * (xy - zw);
  2465. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2466. result.m[6] = 2.0 * (yz + xw);
  2467. result.m[7] = 0;
  2468. result.m[8] = 2.0 * (zx + yw);
  2469. result.m[9] = 2.0 * (yz - xw);
  2470. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2471. result.m[11] = 0;
  2472. result.m[12] = 0;
  2473. result.m[13] = 0;
  2474. result.m[14] = 0;
  2475. result.m[15] = 1.0;
  2476. result._markAsUpdated();
  2477. return this;
  2478. };
  2479. /**
  2480. * Updates the current Quaternion from the passed rotation matrix values.
  2481. * Returns the updated Quaternion.
  2482. */
  2483. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2484. Quaternion.FromRotationMatrixToRef(matrix, this);
  2485. return this;
  2486. };
  2487. // Statics
  2488. /**
  2489. * Returns a new Quaternion set from the passed rotation matrix values.
  2490. */
  2491. Quaternion.FromRotationMatrix = function (matrix) {
  2492. var result = new Quaternion();
  2493. Quaternion.FromRotationMatrixToRef(matrix, result);
  2494. return result;
  2495. };
  2496. /**
  2497. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2498. */
  2499. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2500. var data = matrix.m;
  2501. var m11 = data[0], m12 = data[4], m13 = data[8];
  2502. var m21 = data[1], m22 = data[5], m23 = data[9];
  2503. var m31 = data[2], m32 = data[6], m33 = data[10];
  2504. var trace = m11 + m22 + m33;
  2505. var s;
  2506. if (trace > 0) {
  2507. s = 0.5 / Math.sqrt(trace + 1.0);
  2508. result.w = 0.25 / s;
  2509. result.x = (m32 - m23) * s;
  2510. result.y = (m13 - m31) * s;
  2511. result.z = (m21 - m12) * s;
  2512. }
  2513. else if (m11 > m22 && m11 > m33) {
  2514. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2515. result.w = (m32 - m23) / s;
  2516. result.x = 0.25 * s;
  2517. result.y = (m12 + m21) / s;
  2518. result.z = (m13 + m31) / s;
  2519. }
  2520. else if (m22 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2522. result.w = (m13 - m31) / s;
  2523. result.x = (m12 + m21) / s;
  2524. result.y = 0.25 * s;
  2525. result.z = (m23 + m32) / s;
  2526. }
  2527. else {
  2528. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2529. result.w = (m21 - m12) / s;
  2530. result.x = (m13 + m31) / s;
  2531. result.y = (m23 + m32) / s;
  2532. result.z = 0.25 * s;
  2533. }
  2534. };
  2535. /**
  2536. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2537. */
  2538. Quaternion.Zero = function () {
  2539. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2540. };
  2541. /**
  2542. * Returns a new Quaternion as the inverted current Quaternion.
  2543. */
  2544. Quaternion.Inverse = function (q) {
  2545. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2546. };
  2547. /**
  2548. * Returns the identity Quaternion.
  2549. */
  2550. Quaternion.Identity = function () {
  2551. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2552. };
  2553. Quaternion.IsIdentity = function (quaternion) {
  2554. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2555. };
  2556. /**
  2557. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2558. */
  2559. Quaternion.RotationAxis = function (axis, angle) {
  2560. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2561. };
  2562. /**
  2563. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2564. */
  2565. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2566. var sin = Math.sin(angle / 2);
  2567. axis.normalize();
  2568. result.w = Math.cos(angle / 2);
  2569. result.x = axis.x * sin;
  2570. result.y = axis.y * sin;
  2571. result.z = axis.z * sin;
  2572. return result;
  2573. };
  2574. /**
  2575. * Retuns a new Quaternion set from the starting index of the passed array.
  2576. */
  2577. Quaternion.FromArray = function (array, offset) {
  2578. if (!offset) {
  2579. offset = 0;
  2580. }
  2581. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2582. };
  2583. /**
  2584. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2585. */
  2586. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2587. var q = new Quaternion();
  2588. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2589. return q;
  2590. };
  2591. /**
  2592. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2593. */
  2594. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2595. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2596. var halfRoll = roll * 0.5;
  2597. var halfPitch = pitch * 0.5;
  2598. var halfYaw = yaw * 0.5;
  2599. var sinRoll = Math.sin(halfRoll);
  2600. var cosRoll = Math.cos(halfRoll);
  2601. var sinPitch = Math.sin(halfPitch);
  2602. var cosPitch = Math.cos(halfPitch);
  2603. var sinYaw = Math.sin(halfYaw);
  2604. var cosYaw = Math.cos(halfYaw);
  2605. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2606. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2607. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2608. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2609. };
  2610. /**
  2611. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2612. */
  2613. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2614. var result = new Quaternion();
  2615. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2616. return result;
  2617. };
  2618. /**
  2619. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2620. */
  2621. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2622. // Produces a quaternion from Euler angles in the z-x-z orientation
  2623. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2624. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2625. var halfBeta = beta * 0.5;
  2626. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2627. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2628. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2629. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2630. };
  2631. /**
  2632. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2633. * cf to Vector3.RotationFromAxis() documentation.
  2634. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2635. */
  2636. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2637. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2639. return quat;
  2640. };
  2641. /**
  2642. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2643. * cf to Vector3.RotationFromAxis() documentation.
  2644. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2645. */
  2646. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2647. var rotMat = MathTmp.Matrix[0];
  2648. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2649. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2650. };
  2651. Quaternion.Slerp = function (left, right, amount) {
  2652. var result = Quaternion.Identity();
  2653. Quaternion.SlerpToRef(left, right, amount, result);
  2654. return result;
  2655. };
  2656. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2657. var num2;
  2658. var num3;
  2659. var num = amount;
  2660. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2661. var flag = false;
  2662. if (num4 < 0) {
  2663. flag = true;
  2664. num4 = -num4;
  2665. }
  2666. if (num4 > 0.999999) {
  2667. num3 = 1 - num;
  2668. num2 = flag ? -num : num;
  2669. }
  2670. else {
  2671. var num5 = Math.acos(num4);
  2672. var num6 = (1.0 / Math.sin(num5));
  2673. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2674. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2675. }
  2676. result.x = (num3 * left.x) + (num2 * right.x);
  2677. result.y = (num3 * left.y) + (num2 * right.y);
  2678. result.z = (num3 * left.z) + (num2 * right.z);
  2679. result.w = (num3 * left.w) + (num2 * right.w);
  2680. };
  2681. /**
  2682. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2683. */
  2684. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2685. var squared = amount * amount;
  2686. var cubed = amount * squared;
  2687. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2688. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2689. var part3 = (cubed - (2.0 * squared)) + amount;
  2690. var part4 = cubed - squared;
  2691. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2692. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2693. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2694. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2695. return new Quaternion(x, y, z, w);
  2696. };
  2697. return Quaternion;
  2698. }());
  2699. BABYLON.Quaternion = Quaternion;
  2700. var Matrix = (function () {
  2701. function Matrix() {
  2702. this._isIdentity = false;
  2703. this._isIdentityDirty = true;
  2704. this.m = new Float32Array(16);
  2705. this._markAsUpdated();
  2706. }
  2707. Matrix.prototype._markAsUpdated = function () {
  2708. this.updateFlag = Matrix._updateFlagSeed++;
  2709. this._isIdentityDirty = true;
  2710. };
  2711. // Properties
  2712. /**
  2713. * Boolean : True is the matrix is the identity matrix
  2714. */
  2715. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2716. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2717. if (this._isIdentityDirty) {
  2718. this._isIdentityDirty = false;
  2719. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2720. this._isIdentity = false;
  2721. }
  2722. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2726. this._isIdentity = false;
  2727. }
  2728. else {
  2729. this._isIdentity = true;
  2730. }
  2731. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2732. this._isIdentity = false;
  2733. }
  2734. }
  2735. return this._isIdentity;
  2736. };
  2737. /**
  2738. * Returns the matrix determinant (float).
  2739. */
  2740. Matrix.prototype.determinant = function () {
  2741. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2742. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2743. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2744. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2745. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2746. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2747. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2748. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2749. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2750. };
  2751. // Methods
  2752. /**
  2753. * Returns the matrix underlying array.
  2754. */
  2755. Matrix.prototype.toArray = function () {
  2756. return this.m;
  2757. };
  2758. /**
  2759. * Returns the matrix underlying array.
  2760. */
  2761. Matrix.prototype.asArray = function () {
  2762. return this.toArray();
  2763. };
  2764. /**
  2765. * Inverts in place the Matrix.
  2766. * Returns the Matrix inverted.
  2767. */
  2768. Matrix.prototype.invert = function () {
  2769. this.invertToRef(this);
  2770. return this;
  2771. };
  2772. /**
  2773. * Sets all the matrix elements to zero.
  2774. * Returns the Matrix.
  2775. */
  2776. Matrix.prototype.reset = function () {
  2777. for (var index = 0; index < 16; index++) {
  2778. this.m[index] = 0.0;
  2779. }
  2780. this._markAsUpdated();
  2781. return this;
  2782. };
  2783. /**
  2784. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2785. */
  2786. Matrix.prototype.add = function (other) {
  2787. var result = new Matrix();
  2788. this.addToRef(other, result);
  2789. return result;
  2790. };
  2791. /**
  2792. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2793. * Returns the Matrix.
  2794. */
  2795. Matrix.prototype.addToRef = function (other, result) {
  2796. for (var index = 0; index < 16; index++) {
  2797. result.m[index] = this.m[index] + other.m[index];
  2798. }
  2799. result._markAsUpdated();
  2800. return this;
  2801. };
  2802. /**
  2803. * Adds in place the passed matrix to the current Matrix.
  2804. * Returns the updated Matrix.
  2805. */
  2806. Matrix.prototype.addToSelf = function (other) {
  2807. for (var index = 0; index < 16; index++) {
  2808. this.m[index] += other.m[index];
  2809. }
  2810. this._markAsUpdated();
  2811. return this;
  2812. };
  2813. /**
  2814. * Sets the passed matrix with the current inverted Matrix.
  2815. * Returns the unmodified current Matrix.
  2816. */
  2817. Matrix.prototype.invertToRef = function (other) {
  2818. var l1 = this.m[0];
  2819. var l2 = this.m[1];
  2820. var l3 = this.m[2];
  2821. var l4 = this.m[3];
  2822. var l5 = this.m[4];
  2823. var l6 = this.m[5];
  2824. var l7 = this.m[6];
  2825. var l8 = this.m[7];
  2826. var l9 = this.m[8];
  2827. var l10 = this.m[9];
  2828. var l11 = this.m[10];
  2829. var l12 = this.m[11];
  2830. var l13 = this.m[12];
  2831. var l14 = this.m[13];
  2832. var l15 = this.m[14];
  2833. var l16 = this.m[15];
  2834. var l17 = (l11 * l16) - (l12 * l15);
  2835. var l18 = (l10 * l16) - (l12 * l14);
  2836. var l19 = (l10 * l15) - (l11 * l14);
  2837. var l20 = (l9 * l16) - (l12 * l13);
  2838. var l21 = (l9 * l15) - (l11 * l13);
  2839. var l22 = (l9 * l14) - (l10 * l13);
  2840. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2841. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2842. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2843. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2844. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2845. var l28 = (l7 * l16) - (l8 * l15);
  2846. var l29 = (l6 * l16) - (l8 * l14);
  2847. var l30 = (l6 * l15) - (l7 * l14);
  2848. var l31 = (l5 * l16) - (l8 * l13);
  2849. var l32 = (l5 * l15) - (l7 * l13);
  2850. var l33 = (l5 * l14) - (l6 * l13);
  2851. var l34 = (l7 * l12) - (l8 * l11);
  2852. var l35 = (l6 * l12) - (l8 * l10);
  2853. var l36 = (l6 * l11) - (l7 * l10);
  2854. var l37 = (l5 * l12) - (l8 * l9);
  2855. var l38 = (l5 * l11) - (l7 * l9);
  2856. var l39 = (l5 * l10) - (l6 * l9);
  2857. other.m[0] = l23 * l27;
  2858. other.m[4] = l24 * l27;
  2859. other.m[8] = l25 * l27;
  2860. other.m[12] = l26 * l27;
  2861. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2862. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2863. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2864. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2865. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2866. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2867. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2868. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2869. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2870. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2871. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2872. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2873. other._markAsUpdated();
  2874. return this;
  2875. };
  2876. /**
  2877. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2878. * Returns the updated Matrix.
  2879. */
  2880. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2881. this.m[12] = x;
  2882. this.m[13] = y;
  2883. this.m[14] = z;
  2884. this._markAsUpdated();
  2885. return this;
  2886. };
  2887. /**
  2888. * Inserts the translation vector in the current Matrix.
  2889. * Returns the updated Matrix.
  2890. */
  2891. Matrix.prototype.setTranslation = function (vector3) {
  2892. this.m[12] = vector3.x;
  2893. this.m[13] = vector3.y;
  2894. this.m[14] = vector3.z;
  2895. this._markAsUpdated();
  2896. return this;
  2897. };
  2898. /**
  2899. * Returns a new Vector3 as the extracted translation from the Matrix.
  2900. */
  2901. Matrix.prototype.getTranslation = function () {
  2902. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2903. };
  2904. /**
  2905. * Fill a Vector3 with the extracted translation from the Matrix.
  2906. */
  2907. Matrix.prototype.getTranslationToRef = function (result) {
  2908. result.x = this.m[12];
  2909. result.y = this.m[13];
  2910. result.z = this.m[14];
  2911. return this;
  2912. };
  2913. /**
  2914. * Remove rotation and scaling part from the Matrix.
  2915. * Returns the updated Matrix.
  2916. */
  2917. Matrix.prototype.removeRotationAndScaling = function () {
  2918. this.setRowFromFloats(0, 1, 0, 0, 0);
  2919. this.setRowFromFloats(1, 0, 1, 0, 0);
  2920. this.setRowFromFloats(2, 0, 0, 1, 0);
  2921. return this;
  2922. };
  2923. /**
  2924. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2925. */
  2926. Matrix.prototype.multiply = function (other) {
  2927. var result = new Matrix();
  2928. this.multiplyToRef(other, result);
  2929. return result;
  2930. };
  2931. /**
  2932. * Updates the current Matrix from the passed one values.
  2933. * Returns the updated Matrix.
  2934. */
  2935. Matrix.prototype.copyFrom = function (other) {
  2936. for (var index = 0; index < 16; index++) {
  2937. this.m[index] = other.m[index];
  2938. }
  2939. this._markAsUpdated();
  2940. return this;
  2941. };
  2942. /**
  2943. * Populates the passed array from the starting index with the Matrix values.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.copyToArray = function (array, offset) {
  2947. if (offset === void 0) { offset = 0; }
  2948. for (var index = 0; index < 16; index++) {
  2949. array[offset + index] = this.m[index];
  2950. }
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToRef = function (other, result) {
  2957. this.multiplyToArray(other, result.m, 0);
  2958. result._markAsUpdated();
  2959. return this;
  2960. };
  2961. /**
  2962. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2963. */
  2964. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2965. var tm0 = this.m[0];
  2966. var tm1 = this.m[1];
  2967. var tm2 = this.m[2];
  2968. var tm3 = this.m[3];
  2969. var tm4 = this.m[4];
  2970. var tm5 = this.m[5];
  2971. var tm6 = this.m[6];
  2972. var tm7 = this.m[7];
  2973. var tm8 = this.m[8];
  2974. var tm9 = this.m[9];
  2975. var tm10 = this.m[10];
  2976. var tm11 = this.m[11];
  2977. var tm12 = this.m[12];
  2978. var tm13 = this.m[13];
  2979. var tm14 = this.m[14];
  2980. var tm15 = this.m[15];
  2981. var om0 = other.m[0];
  2982. var om1 = other.m[1];
  2983. var om2 = other.m[2];
  2984. var om3 = other.m[3];
  2985. var om4 = other.m[4];
  2986. var om5 = other.m[5];
  2987. var om6 = other.m[6];
  2988. var om7 = other.m[7];
  2989. var om8 = other.m[8];
  2990. var om9 = other.m[9];
  2991. var om10 = other.m[10];
  2992. var om11 = other.m[11];
  2993. var om12 = other.m[12];
  2994. var om13 = other.m[13];
  2995. var om14 = other.m[14];
  2996. var om15 = other.m[15];
  2997. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2998. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2999. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3000. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3001. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3002. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3003. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3004. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3005. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3006. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3007. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3008. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3009. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3010. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3011. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3012. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3013. return this;
  3014. };
  3015. /**
  3016. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3017. */
  3018. Matrix.prototype.equals = function (value) {
  3019. return value &&
  3020. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3021. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3022. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3023. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3024. };
  3025. /**
  3026. * Returns a new Matrix from the current Matrix.
  3027. */
  3028. Matrix.prototype.clone = function () {
  3029. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3030. };
  3031. /**
  3032. * Returns the string "Matrix"
  3033. */
  3034. Matrix.prototype.getClassName = function () {
  3035. return "Matrix";
  3036. };
  3037. /**
  3038. * Returns the Matrix hash code.
  3039. */
  3040. Matrix.prototype.getHashCode = function () {
  3041. var hash = this.m[0] || 0;
  3042. for (var i = 1; i < 16; i++) {
  3043. hash = (hash * 397) ^ (this.m[i] || 0);
  3044. }
  3045. return hash;
  3046. };
  3047. /**
  3048. * Decomposes the current Matrix into :
  3049. * - a scale vector3 passed as a reference to update,
  3050. * - a rotation quaternion passed as a reference to update,
  3051. * - a translation vector3 passed as a reference to update.
  3052. * Returns the boolean `true`.
  3053. */
  3054. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3055. translation.x = this.m[12];
  3056. translation.y = this.m[13];
  3057. translation.z = this.m[14];
  3058. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3059. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3060. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3061. if (this.determinant() <= 0) {
  3062. scale.y *= -1;
  3063. }
  3064. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3065. rotation.x = 0;
  3066. rotation.y = 0;
  3067. rotation.z = 0;
  3068. rotation.w = 1;
  3069. return false;
  3070. }
  3071. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3072. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3073. return true;
  3074. };
  3075. /**
  3076. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3077. */
  3078. Matrix.prototype.getRotationMatrix = function () {
  3079. var result = Matrix.Identity();
  3080. this.getRotationMatrixToRef(result);
  3081. return result;
  3082. };
  3083. /**
  3084. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3085. * Returns the current Matrix.
  3086. */
  3087. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3088. var m = this.m;
  3089. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3090. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3091. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3092. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3093. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3094. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3095. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3096. return this;
  3097. };
  3098. // Statics
  3099. /**
  3100. * Returns a new Matrix set from the starting index of the passed array.
  3101. */
  3102. Matrix.FromArray = function (array, offset) {
  3103. var result = new Matrix();
  3104. if (!offset) {
  3105. offset = 0;
  3106. }
  3107. Matrix.FromArrayToRef(array, offset, result);
  3108. return result;
  3109. };
  3110. /**
  3111. * Sets the passed "result" matrix from the starting index of the passed array.
  3112. */
  3113. Matrix.FromArrayToRef = function (array, offset, result) {
  3114. for (var index = 0; index < 16; index++) {
  3115. result.m[index] = array[index + offset];
  3116. }
  3117. result._markAsUpdated();
  3118. };
  3119. /**
  3120. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3121. */
  3122. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3123. for (var index = 0; index < 16; index++) {
  3124. result.m[index] = array[index + offset] * scale;
  3125. }
  3126. result._markAsUpdated();
  3127. };
  3128. /**
  3129. * Sets the passed matrix "result" with the 16 passed floats.
  3130. */
  3131. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3132. result.m[0] = initialM11;
  3133. result.m[1] = initialM12;
  3134. result.m[2] = initialM13;
  3135. result.m[3] = initialM14;
  3136. result.m[4] = initialM21;
  3137. result.m[5] = initialM22;
  3138. result.m[6] = initialM23;
  3139. result.m[7] = initialM24;
  3140. result.m[8] = initialM31;
  3141. result.m[9] = initialM32;
  3142. result.m[10] = initialM33;
  3143. result.m[11] = initialM34;
  3144. result.m[12] = initialM41;
  3145. result.m[13] = initialM42;
  3146. result.m[14] = initialM43;
  3147. result.m[15] = initialM44;
  3148. result._markAsUpdated();
  3149. };
  3150. /**
  3151. * Returns the index-th row of the current matrix as a new Vector4.
  3152. */
  3153. Matrix.prototype.getRow = function (index) {
  3154. if (index < 0 || index > 3) {
  3155. return null;
  3156. }
  3157. var i = index * 4;
  3158. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3159. };
  3160. /**
  3161. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3162. * Returns the updated Matrix.
  3163. */
  3164. Matrix.prototype.setRow = function (index, row) {
  3165. if (index < 0 || index > 3) {
  3166. return this;
  3167. }
  3168. var i = index * 4;
  3169. this.m[i + 0] = row.x;
  3170. this.m[i + 1] = row.y;
  3171. this.m[i + 2] = row.z;
  3172. this.m[i + 3] = row.w;
  3173. this._markAsUpdated();
  3174. return this;
  3175. };
  3176. /**
  3177. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3178. * Returns the updated Matrix.
  3179. */
  3180. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3181. if (index < 0 || index > 3) {
  3182. return this;
  3183. }
  3184. var i = index * 4;
  3185. this.m[i + 0] = x;
  3186. this.m[i + 1] = y;
  3187. this.m[i + 2] = z;
  3188. this.m[i + 3] = w;
  3189. this._markAsUpdated();
  3190. return this;
  3191. };
  3192. /**
  3193. * Returns a new Matrix set from the 16 passed floats.
  3194. */
  3195. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3196. var result = new Matrix();
  3197. result.m[0] = initialM11;
  3198. result.m[1] = initialM12;
  3199. result.m[2] = initialM13;
  3200. result.m[3] = initialM14;
  3201. result.m[4] = initialM21;
  3202. result.m[5] = initialM22;
  3203. result.m[6] = initialM23;
  3204. result.m[7] = initialM24;
  3205. result.m[8] = initialM31;
  3206. result.m[9] = initialM32;
  3207. result.m[10] = initialM33;
  3208. result.m[11] = initialM34;
  3209. result.m[12] = initialM41;
  3210. result.m[13] = initialM42;
  3211. result.m[14] = initialM43;
  3212. result.m[15] = initialM44;
  3213. return result;
  3214. };
  3215. /**
  3216. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.Compose = function (scale, rotation, translation) {
  3219. var result = Matrix.Identity();
  3220. Matrix.ComposeToRef(scale, rotation, translation, result);
  3221. return result;
  3222. };
  3223. /**
  3224. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3225. */
  3226. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3227. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3228. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3229. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3230. result.setTranslation(translation);
  3231. };
  3232. /**
  3233. * Returns a new indentity Matrix.
  3234. */
  3235. Matrix.Identity = function () {
  3236. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3237. };
  3238. /**
  3239. * Sets the passed "result" as an identity matrix.
  3240. */
  3241. Matrix.IdentityToRef = function (result) {
  3242. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3243. };
  3244. /**
  3245. * Returns a new zero Matrix.
  3246. */
  3247. Matrix.Zero = function () {
  3248. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3249. };
  3250. /**
  3251. * Returns a new rotation matrix for "angle" radians around the X axis.
  3252. */
  3253. Matrix.RotationX = function (angle) {
  3254. var result = new Matrix();
  3255. Matrix.RotationXToRef(angle, result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Returns a new Matrix as the passed inverted one.
  3260. */
  3261. Matrix.Invert = function (source) {
  3262. var result = new Matrix();
  3263. source.invertToRef(result);
  3264. return result;
  3265. };
  3266. /**
  3267. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3268. */
  3269. Matrix.RotationXToRef = function (angle, result) {
  3270. var s = Math.sin(angle);
  3271. var c = Math.cos(angle);
  3272. result.m[0] = 1.0;
  3273. result.m[15] = 1.0;
  3274. result.m[5] = c;
  3275. result.m[10] = c;
  3276. result.m[9] = -s;
  3277. result.m[6] = s;
  3278. result.m[1] = 0.0;
  3279. result.m[2] = 0.0;
  3280. result.m[3] = 0.0;
  3281. result.m[4] = 0.0;
  3282. result.m[7] = 0.0;
  3283. result.m[8] = 0.0;
  3284. result.m[11] = 0.0;
  3285. result.m[12] = 0.0;
  3286. result.m[13] = 0.0;
  3287. result.m[14] = 0.0;
  3288. result._markAsUpdated();
  3289. };
  3290. /**
  3291. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationY = function (angle) {
  3294. var result = new Matrix();
  3295. Matrix.RotationYToRef(angle, result);
  3296. return result;
  3297. };
  3298. /**
  3299. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3300. */
  3301. Matrix.RotationYToRef = function (angle, result) {
  3302. var s = Math.sin(angle);
  3303. var c = Math.cos(angle);
  3304. result.m[5] = 1.0;
  3305. result.m[15] = 1.0;
  3306. result.m[0] = c;
  3307. result.m[2] = -s;
  3308. result.m[8] = s;
  3309. result.m[10] = c;
  3310. result.m[1] = 0.0;
  3311. result.m[3] = 0.0;
  3312. result.m[4] = 0.0;
  3313. result.m[6] = 0.0;
  3314. result.m[7] = 0.0;
  3315. result.m[9] = 0.0;
  3316. result.m[11] = 0.0;
  3317. result.m[12] = 0.0;
  3318. result.m[13] = 0.0;
  3319. result.m[14] = 0.0;
  3320. result._markAsUpdated();
  3321. };
  3322. /**
  3323. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZ = function (angle) {
  3326. var result = new Matrix();
  3327. Matrix.RotationZToRef(angle, result);
  3328. return result;
  3329. };
  3330. /**
  3331. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3332. */
  3333. Matrix.RotationZToRef = function (angle, result) {
  3334. var s = Math.sin(angle);
  3335. var c = Math.cos(angle);
  3336. result.m[10] = 1.0;
  3337. result.m[15] = 1.0;
  3338. result.m[0] = c;
  3339. result.m[1] = s;
  3340. result.m[4] = -s;
  3341. result.m[5] = c;
  3342. result.m[2] = 0.0;
  3343. result.m[3] = 0.0;
  3344. result.m[6] = 0.0;
  3345. result.m[7] = 0.0;
  3346. result.m[8] = 0.0;
  3347. result.m[9] = 0.0;
  3348. result.m[11] = 0.0;
  3349. result.m[12] = 0.0;
  3350. result.m[13] = 0.0;
  3351. result.m[14] = 0.0;
  3352. result._markAsUpdated();
  3353. };
  3354. /**
  3355. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxis = function (axis, angle) {
  3358. var result = Matrix.Zero();
  3359. Matrix.RotationAxisToRef(axis, angle, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3364. */
  3365. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3366. var s = Math.sin(-angle);
  3367. var c = Math.cos(-angle);
  3368. var c1 = 1 - c;
  3369. axis.normalize();
  3370. result.m[0] = (axis.x * axis.x) * c1 + c;
  3371. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3372. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3373. result.m[3] = 0.0;
  3374. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3375. result.m[5] = (axis.y * axis.y) * c1 + c;
  3376. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3377. result.m[7] = 0.0;
  3378. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3379. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3380. result.m[10] = (axis.z * axis.z) * c1 + c;
  3381. result.m[11] = 0.0;
  3382. result.m[15] = 1.0;
  3383. result._markAsUpdated();
  3384. };
  3385. /**
  3386. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3389. var result = new Matrix();
  3390. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3391. return result;
  3392. };
  3393. /**
  3394. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3395. */
  3396. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3397. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3398. this._tempQuaternion.toRotationMatrix(result);
  3399. };
  3400. /**
  3401. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.Scaling = function (x, y, z) {
  3404. var result = Matrix.Zero();
  3405. Matrix.ScalingToRef(x, y, z, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3410. */
  3411. Matrix.ScalingToRef = function (x, y, z, result) {
  3412. result.m[0] = x;
  3413. result.m[1] = 0.0;
  3414. result.m[2] = 0.0;
  3415. result.m[3] = 0.0;
  3416. result.m[4] = 0.0;
  3417. result.m[5] = y;
  3418. result.m[6] = 0.0;
  3419. result.m[7] = 0.0;
  3420. result.m[8] = 0.0;
  3421. result.m[9] = 0.0;
  3422. result.m[10] = z;
  3423. result.m[11] = 0.0;
  3424. result.m[12] = 0.0;
  3425. result.m[13] = 0.0;
  3426. result.m[14] = 0.0;
  3427. result.m[15] = 1.0;
  3428. result._markAsUpdated();
  3429. };
  3430. /**
  3431. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.Translation = function (x, y, z) {
  3434. var result = Matrix.Identity();
  3435. Matrix.TranslationToRef(x, y, z, result);
  3436. return result;
  3437. };
  3438. /**
  3439. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3440. */
  3441. Matrix.TranslationToRef = function (x, y, z, result) {
  3442. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3443. };
  3444. /**
  3445. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3446. */
  3447. Matrix.Lerp = function (startValue, endValue, gradient) {
  3448. var result = Matrix.Zero();
  3449. for (var index = 0; index < 16; index++) {
  3450. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3451. }
  3452. result._markAsUpdated();
  3453. return result;
  3454. };
  3455. /**
  3456. * Returns a new Matrix whose values are computed by :
  3457. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3458. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3459. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3460. */
  3461. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3462. var startScale = new Vector3(0, 0, 0);
  3463. var startRotation = new Quaternion();
  3464. var startTranslation = new Vector3(0, 0, 0);
  3465. startValue.decompose(startScale, startRotation, startTranslation);
  3466. var endScale = new Vector3(0, 0, 0);
  3467. var endRotation = new Quaternion();
  3468. var endTranslation = new Vector3(0, 0, 0);
  3469. endValue.decompose(endScale, endRotation, endTranslation);
  3470. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3471. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3472. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3473. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3474. };
  3475. /**
  3476. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3477. * This methods works for a Left-Handed system.
  3478. */
  3479. Matrix.LookAtLH = function (eye, target, up) {
  3480. var result = Matrix.Zero();
  3481. Matrix.LookAtLHToRef(eye, target, up, result);
  3482. return result;
  3483. };
  3484. /**
  3485. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3486. * This methods works for a Left-Handed system.
  3487. */
  3488. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3489. // Z axis
  3490. target.subtractToRef(eye, this._zAxis);
  3491. this._zAxis.normalize();
  3492. // X axis
  3493. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3494. if (this._xAxis.lengthSquared() === 0) {
  3495. this._xAxis.x = 1.0;
  3496. }
  3497. else {
  3498. this._xAxis.normalize();
  3499. }
  3500. // Y axis
  3501. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3502. this._yAxis.normalize();
  3503. // Eye angles
  3504. var ex = -Vector3.Dot(this._xAxis, eye);
  3505. var ey = -Vector3.Dot(this._yAxis, eye);
  3506. var ez = -Vector3.Dot(this._zAxis, eye);
  3507. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3508. };
  3509. /**
  3510. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3511. * This methods works for a Right-Handed system.
  3512. */
  3513. Matrix.LookAtRH = function (eye, target, up) {
  3514. var result = Matrix.Zero();
  3515. Matrix.LookAtRHToRef(eye, target, up, result);
  3516. return result;
  3517. };
  3518. /**
  3519. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3520. * This methods works for a Left-Handed system.
  3521. */
  3522. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3523. // Z axis
  3524. eye.subtractToRef(target, this._zAxis);
  3525. this._zAxis.normalize();
  3526. // X axis
  3527. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3528. if (this._xAxis.lengthSquared() === 0) {
  3529. this._xAxis.x = 1.0;
  3530. }
  3531. else {
  3532. this._xAxis.normalize();
  3533. }
  3534. // Y axis
  3535. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3536. this._yAxis.normalize();
  3537. // Eye angles
  3538. var ex = -Vector3.Dot(this._xAxis, eye);
  3539. var ey = -Vector3.Dot(this._yAxis, eye);
  3540. var ez = -Vector3.Dot(this._zAxis, eye);
  3541. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3542. };
  3543. /**
  3544. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3545. */
  3546. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3547. var matrix = Matrix.Zero();
  3548. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3549. return matrix;
  3550. };
  3551. /**
  3552. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3553. */
  3554. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3555. var n = znear;
  3556. var f = zfar;
  3557. var a = 2.0 / width;
  3558. var b = 2.0 / height;
  3559. var c = 2.0 / (f - n);
  3560. var d = -(f + n) / (f - n);
  3561. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3562. };
  3563. /**
  3564. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3565. */
  3566. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3567. var matrix = Matrix.Zero();
  3568. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3569. return matrix;
  3570. };
  3571. /**
  3572. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3573. */
  3574. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3575. var n = znear;
  3576. var f = zfar;
  3577. var a = 2.0 / (right - left);
  3578. var b = 2.0 / (top - bottom);
  3579. var c = 2.0 / (f - n);
  3580. var d = -(f + n) / (f - n);
  3581. var i0 = (left + right) / (left - right);
  3582. var i1 = (top + bottom) / (bottom - top);
  3583. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3584. };
  3585. /**
  3586. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3587. */
  3588. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3589. var matrix = Matrix.Zero();
  3590. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3591. return matrix;
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3595. */
  3596. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3597. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3598. result.m[10] *= -1.0;
  3599. };
  3600. /**
  3601. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3602. */
  3603. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3604. var matrix = Matrix.Zero();
  3605. var n = znear;
  3606. var f = zfar;
  3607. var a = 2.0 * n / width;
  3608. var b = 2.0 * n / height;
  3609. var c = (f + n) / (f - n);
  3610. var d = -2.0 * f * n / (f - n);
  3611. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3616. */
  3617. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3618. var matrix = Matrix.Zero();
  3619. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3620. return matrix;
  3621. };
  3622. /**
  3623. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3624. */
  3625. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3626. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3627. var n = znear;
  3628. var f = zfar;
  3629. var t = 1.0 / (Math.tan(fov * 0.5));
  3630. var a = isVerticalFovFixed ? (t / aspect) : t;
  3631. var b = isVerticalFovFixed ? t : (t * aspect);
  3632. var c = (f + n) / (f - n);
  3633. var d = -2.0 * f * n / (f - n);
  3634. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3635. };
  3636. /**
  3637. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3638. */
  3639. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3640. var matrix = Matrix.Zero();
  3641. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3642. return matrix;
  3643. };
  3644. /**
  3645. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3646. */
  3647. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3648. //alternatively this could be expressed as:
  3649. // m = PerspectiveFovLHToRef
  3650. // m[10] *= -1.0;
  3651. // m[11] *= -1.0;
  3652. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3653. var n = znear;
  3654. var f = zfar;
  3655. var t = 1.0 / (Math.tan(fov * 0.5));
  3656. var a = isVerticalFovFixed ? (t / aspect) : t;
  3657. var b = isVerticalFovFixed ? t : (t * aspect);
  3658. var c = -(f + n) / (f - n);
  3659. var d = -2 * f * n / (f - n);
  3660. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3661. };
  3662. /**
  3663. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3664. */
  3665. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3666. if (rightHanded === void 0) { rightHanded = false; }
  3667. var rightHandedFactor = rightHanded ? -1 : 1;
  3668. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3669. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3670. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3671. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3672. var xScale = 2.0 / (leftTan + rightTan);
  3673. var yScale = 2.0 / (upTan + downTan);
  3674. result.m[0] = xScale;
  3675. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3676. result.m[5] = yScale;
  3677. result.m[6] = result.m[7] = 0.0;
  3678. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3679. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3680. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3681. result.m[10] = -zfar / (znear - zfar);
  3682. result.m[11] = 1.0 * rightHandedFactor;
  3683. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3684. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3685. // result.m[14] = (znear * zfar) / (znear - zfar);
  3686. result._markAsUpdated();
  3687. };
  3688. /**
  3689. * Returns the final transformation matrix : world * view * projection * viewport
  3690. */
  3691. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3692. var cw = viewport.width;
  3693. var ch = viewport.height;
  3694. var cx = viewport.x;
  3695. var cy = viewport.y;
  3696. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3697. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3698. };
  3699. /**
  3700. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3701. */
  3702. Matrix.GetAsMatrix2x2 = function (matrix) {
  3703. return new Float32Array([
  3704. matrix.m[0], matrix.m[1],
  3705. matrix.m[4], matrix.m[5]
  3706. ]);
  3707. };
  3708. /**
  3709. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3710. */
  3711. Matrix.GetAsMatrix3x3 = function (matrix) {
  3712. return new Float32Array([
  3713. matrix.m[0], matrix.m[1], matrix.m[2],
  3714. matrix.m[4], matrix.m[5], matrix.m[6],
  3715. matrix.m[8], matrix.m[9], matrix.m[10]
  3716. ]);
  3717. };
  3718. /**
  3719. * Compute the transpose of the passed Matrix.
  3720. * Returns a new Matrix.
  3721. */
  3722. Matrix.Transpose = function (matrix) {
  3723. var result = new Matrix();
  3724. result.m[0] = matrix.m[0];
  3725. result.m[1] = matrix.m[4];
  3726. result.m[2] = matrix.m[8];
  3727. result.m[3] = matrix.m[12];
  3728. result.m[4] = matrix.m[1];
  3729. result.m[5] = matrix.m[5];
  3730. result.m[6] = matrix.m[9];
  3731. result.m[7] = matrix.m[13];
  3732. result.m[8] = matrix.m[2];
  3733. result.m[9] = matrix.m[6];
  3734. result.m[10] = matrix.m[10];
  3735. result.m[11] = matrix.m[14];
  3736. result.m[12] = matrix.m[3];
  3737. result.m[13] = matrix.m[7];
  3738. result.m[14] = matrix.m[11];
  3739. result.m[15] = matrix.m[15];
  3740. return result;
  3741. };
  3742. /**
  3743. * Returns a new Matrix as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.Reflection = function (plane) {
  3746. var matrix = new Matrix();
  3747. Matrix.ReflectionToRef(plane, matrix);
  3748. return matrix;
  3749. };
  3750. /**
  3751. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3752. */
  3753. Matrix.ReflectionToRef = function (plane, result) {
  3754. plane.normalize();
  3755. var x = plane.normal.x;
  3756. var y = plane.normal.y;
  3757. var z = plane.normal.z;
  3758. var temp = -2 * x;
  3759. var temp2 = -2 * y;
  3760. var temp3 = -2 * z;
  3761. result.m[0] = (temp * x) + 1;
  3762. result.m[1] = temp2 * x;
  3763. result.m[2] = temp3 * x;
  3764. result.m[3] = 0.0;
  3765. result.m[4] = temp * y;
  3766. result.m[5] = (temp2 * y) + 1;
  3767. result.m[6] = temp3 * y;
  3768. result.m[7] = 0.0;
  3769. result.m[8] = temp * z;
  3770. result.m[9] = temp2 * z;
  3771. result.m[10] = (temp3 * z) + 1;
  3772. result.m[11] = 0.0;
  3773. result.m[12] = temp * plane.d;
  3774. result.m[13] = temp2 * plane.d;
  3775. result.m[14] = temp3 * plane.d;
  3776. result.m[15] = 1.0;
  3777. result._markAsUpdated();
  3778. };
  3779. /**
  3780. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3781. */
  3782. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3783. result.m[0] = xaxis.x;
  3784. result.m[1] = xaxis.y;
  3785. result.m[2] = xaxis.z;
  3786. result.m[3] = 0.0;
  3787. result.m[4] = yaxis.x;
  3788. result.m[5] = yaxis.y;
  3789. result.m[6] = yaxis.z;
  3790. result.m[7] = 0.0;
  3791. result.m[8] = zaxis.x;
  3792. result.m[9] = zaxis.y;
  3793. result.m[10] = zaxis.z;
  3794. result.m[11] = 0.0;
  3795. result.m[12] = 0.0;
  3796. result.m[13] = 0.0;
  3797. result.m[14] = 0.0;
  3798. result.m[15] = 1.0;
  3799. result._markAsUpdated();
  3800. };
  3801. /**
  3802. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3803. */
  3804. Matrix.FromQuaternionToRef = function (quat, result) {
  3805. var xx = quat.x * quat.x;
  3806. var yy = quat.y * quat.y;
  3807. var zz = quat.z * quat.z;
  3808. var xy = quat.x * quat.y;
  3809. var zw = quat.z * quat.w;
  3810. var zx = quat.z * quat.x;
  3811. var yw = quat.y * quat.w;
  3812. var yz = quat.y * quat.z;
  3813. var xw = quat.x * quat.w;
  3814. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3815. result.m[1] = 2.0 * (xy + zw);
  3816. result.m[2] = 2.0 * (zx - yw);
  3817. result.m[3] = 0.0;
  3818. result.m[4] = 2.0 * (xy - zw);
  3819. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3820. result.m[6] = 2.0 * (yz + xw);
  3821. result.m[7] = 0.0;
  3822. result.m[8] = 2.0 * (zx + yw);
  3823. result.m[9] = 2.0 * (yz - xw);
  3824. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3825. result.m[11] = 0.0;
  3826. result.m[12] = 0.0;
  3827. result.m[13] = 0.0;
  3828. result.m[14] = 0.0;
  3829. result.m[15] = 1.0;
  3830. result._markAsUpdated();
  3831. };
  3832. Matrix._tempQuaternion = new Quaternion();
  3833. Matrix._xAxis = Vector3.Zero();
  3834. Matrix._yAxis = Vector3.Zero();
  3835. Matrix._zAxis = Vector3.Zero();
  3836. Matrix._updateFlagSeed = 0;
  3837. return Matrix;
  3838. }());
  3839. BABYLON.Matrix = Matrix;
  3840. var Plane = (function () {
  3841. /**
  3842. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3843. */
  3844. function Plane(a, b, c, d) {
  3845. this.normal = new Vector3(a, b, c);
  3846. this.d = d;
  3847. }
  3848. /**
  3849. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3850. */
  3851. Plane.prototype.asArray = function () {
  3852. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3853. };
  3854. // Methods
  3855. /**
  3856. * Returns a new plane copied from the current Plane.
  3857. */
  3858. Plane.prototype.clone = function () {
  3859. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3860. };
  3861. /**
  3862. * Returns the string "Plane".
  3863. */
  3864. Plane.prototype.getClassName = function () {
  3865. return "Plane";
  3866. };
  3867. /**
  3868. * Returns the Plane hash code.
  3869. */
  3870. Plane.prototype.getHashCode = function () {
  3871. var hash = this.normal.getHashCode();
  3872. hash = (hash * 397) ^ (this.d || 0);
  3873. return hash;
  3874. };
  3875. /**
  3876. * Normalize the current Plane in place.
  3877. * Returns the updated Plane.
  3878. */
  3879. Plane.prototype.normalize = function () {
  3880. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3881. var magnitude = 0.0;
  3882. if (norm !== 0) {
  3883. magnitude = 1.0 / norm;
  3884. }
  3885. this.normal.x *= magnitude;
  3886. this.normal.y *= magnitude;
  3887. this.normal.z *= magnitude;
  3888. this.d *= magnitude;
  3889. return this;
  3890. };
  3891. /**
  3892. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3893. */
  3894. Plane.prototype.transform = function (transformation) {
  3895. var transposedMatrix = Matrix.Transpose(transformation);
  3896. var x = this.normal.x;
  3897. var y = this.normal.y;
  3898. var z = this.normal.z;
  3899. var d = this.d;
  3900. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3901. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3902. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3903. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3904. return new Plane(normalX, normalY, normalZ, finalD);
  3905. };
  3906. /**
  3907. * Returns the dot product (float) of the point coordinates and the plane normal.
  3908. */
  3909. Plane.prototype.dotCoordinate = function (point) {
  3910. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3911. };
  3912. /**
  3913. * Updates the current Plane from the plane defined by the three passed points.
  3914. * Returns the updated Plane.
  3915. */
  3916. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3917. var x1 = point2.x - point1.x;
  3918. var y1 = point2.y - point1.y;
  3919. var z1 = point2.z - point1.z;
  3920. var x2 = point3.x - point1.x;
  3921. var y2 = point3.y - point1.y;
  3922. var z2 = point3.z - point1.z;
  3923. var yz = (y1 * z2) - (z1 * y2);
  3924. var xz = (z1 * x2) - (x1 * z2);
  3925. var xy = (x1 * y2) - (y1 * x2);
  3926. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3927. var invPyth;
  3928. if (pyth !== 0) {
  3929. invPyth = 1.0 / pyth;
  3930. }
  3931. else {
  3932. invPyth = 0.0;
  3933. }
  3934. this.normal.x = yz * invPyth;
  3935. this.normal.y = xz * invPyth;
  3936. this.normal.z = xy * invPyth;
  3937. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3938. return this;
  3939. };
  3940. /**
  3941. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3942. */
  3943. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3944. var dot = Vector3.Dot(this.normal, direction);
  3945. return (dot <= epsilon);
  3946. };
  3947. /**
  3948. * Returns the signed distance (float) from the passed point to the Plane.
  3949. */
  3950. Plane.prototype.signedDistanceTo = function (point) {
  3951. return Vector3.Dot(point, this.normal) + this.d;
  3952. };
  3953. // Statics
  3954. /**
  3955. * Returns a new Plane from the passed array.
  3956. */
  3957. Plane.FromArray = function (array) {
  3958. return new Plane(array[0], array[1], array[2], array[3]);
  3959. };
  3960. /**
  3961. * Returns a new Plane defined by the three passed points.
  3962. */
  3963. Plane.FromPoints = function (point1, point2, point3) {
  3964. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3965. result.copyFromPoints(point1, point2, point3);
  3966. return result;
  3967. };
  3968. /**
  3969. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3970. * Note : the vector "normal" is updated because normalized.
  3971. */
  3972. Plane.FromPositionAndNormal = function (origin, normal) {
  3973. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3974. normal.normalize();
  3975. result.normal = normal;
  3976. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3977. return result;
  3978. };
  3979. /**
  3980. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3981. */
  3982. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3983. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3984. return Vector3.Dot(point, normal) + d;
  3985. };
  3986. return Plane;
  3987. }());
  3988. BABYLON.Plane = Plane;
  3989. var Viewport = (function () {
  3990. /**
  3991. * Creates a Viewport object located at (x, y) and sized (width, height).
  3992. */
  3993. function Viewport(x, y, width, height) {
  3994. this.x = x;
  3995. this.y = y;
  3996. this.width = width;
  3997. this.height = height;
  3998. }
  3999. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4000. if (renderWidthOrEngine.getRenderWidth) {
  4001. var engine = renderWidthOrEngine;
  4002. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4003. }
  4004. var renderWidth = renderWidthOrEngine;
  4005. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4006. };
  4007. /**
  4008. * Returns a new Viewport copied from the current one.
  4009. */
  4010. Viewport.prototype.clone = function () {
  4011. return new Viewport(this.x, this.y, this.width, this.height);
  4012. };
  4013. return Viewport;
  4014. }());
  4015. BABYLON.Viewport = Viewport;
  4016. var Frustum = (function () {
  4017. function Frustum() {
  4018. }
  4019. /**
  4020. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4021. */
  4022. Frustum.GetPlanes = function (transform) {
  4023. var frustumPlanes = [];
  4024. for (var index = 0; index < 6; index++) {
  4025. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4026. }
  4027. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4028. return frustumPlanes;
  4029. };
  4030. /**
  4031. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4032. */
  4033. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4034. // Near
  4035. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4036. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4037. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4038. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4039. frustumPlanes[0].normalize();
  4040. // Far
  4041. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4042. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4043. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4044. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4045. frustumPlanes[1].normalize();
  4046. // Left
  4047. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4048. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4049. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4050. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4051. frustumPlanes[2].normalize();
  4052. // Right
  4053. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4054. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4055. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4056. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4057. frustumPlanes[3].normalize();
  4058. // Top
  4059. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4060. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4061. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4062. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4063. frustumPlanes[4].normalize();
  4064. // Bottom
  4065. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4066. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4067. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4068. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4069. frustumPlanes[5].normalize();
  4070. };
  4071. return Frustum;
  4072. }());
  4073. BABYLON.Frustum = Frustum;
  4074. var Space;
  4075. (function (Space) {
  4076. Space[Space["LOCAL"] = 0] = "LOCAL";
  4077. Space[Space["WORLD"] = 1] = "WORLD";
  4078. Space[Space["BONE"] = 2] = "BONE";
  4079. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4080. var Axis = (function () {
  4081. function Axis() {
  4082. }
  4083. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4084. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4085. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4086. return Axis;
  4087. }());
  4088. BABYLON.Axis = Axis;
  4089. ;
  4090. var BezierCurve = (function () {
  4091. function BezierCurve() {
  4092. }
  4093. /**
  4094. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4095. */
  4096. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4097. // Extract X (which is equal to time here)
  4098. var f0 = 1 - 3 * x2 + 3 * x1;
  4099. var f1 = 3 * x2 - 6 * x1;
  4100. var f2 = 3 * x1;
  4101. var refinedT = t;
  4102. for (var i = 0; i < 5; i++) {
  4103. var refinedT2 = refinedT * refinedT;
  4104. var refinedT3 = refinedT2 * refinedT;
  4105. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4106. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4107. refinedT -= (x - t) * slope;
  4108. refinedT = Math.min(1, Math.max(0, refinedT));
  4109. }
  4110. // Resolve cubic bezier for the given x
  4111. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4112. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4113. Math.pow(refinedT, 3);
  4114. };
  4115. return BezierCurve;
  4116. }());
  4117. BABYLON.BezierCurve = BezierCurve;
  4118. var Orientation;
  4119. (function (Orientation) {
  4120. Orientation[Orientation["CW"] = 0] = "CW";
  4121. Orientation[Orientation["CCW"] = 1] = "CCW";
  4122. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4123. var Angle = (function () {
  4124. /**
  4125. * Creates an Angle object of "radians" radians (float).
  4126. */
  4127. function Angle(radians) {
  4128. var _this = this;
  4129. /**
  4130. * Returns the Angle value in degrees (float).
  4131. */
  4132. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4133. /**
  4134. * Returns the Angle value in radians (float).
  4135. */
  4136. this.radians = function () { return _this._radians; };
  4137. this._radians = radians;
  4138. if (this._radians < 0.0)
  4139. this._radians += (2.0 * Math.PI);
  4140. }
  4141. /**
  4142. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4143. */
  4144. Angle.BetweenTwoPoints = function (a, b) {
  4145. var delta = b.subtract(a);
  4146. var theta = Math.atan2(delta.y, delta.x);
  4147. return new Angle(theta);
  4148. };
  4149. /**
  4150. * Returns a new Angle object from the passed float in radians.
  4151. */
  4152. Angle.FromRadians = function (radians) {
  4153. return new Angle(radians);
  4154. };
  4155. /**
  4156. * Returns a new Angle object from the passed float in degrees.
  4157. */
  4158. Angle.FromDegrees = function (degrees) {
  4159. return new Angle(degrees * Math.PI / 180.0);
  4160. };
  4161. return Angle;
  4162. }());
  4163. BABYLON.Angle = Angle;
  4164. var Arc2 = (function () {
  4165. /**
  4166. * Creates an Arc object from the three passed points : start, middle and end.
  4167. */
  4168. function Arc2(startPoint, midPoint, endPoint) {
  4169. this.startPoint = startPoint;
  4170. this.midPoint = midPoint;
  4171. this.endPoint = endPoint;
  4172. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4173. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4174. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4175. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4176. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4177. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4178. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4179. var a1 = this.startAngle.degrees();
  4180. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4181. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4182. // angles correction
  4183. if (a2 - a1 > +180.0)
  4184. a2 -= 360.0;
  4185. if (a2 - a1 < -180.0)
  4186. a2 += 360.0;
  4187. if (a3 - a2 > +180.0)
  4188. a3 -= 360.0;
  4189. if (a3 - a2 < -180.0)
  4190. a3 += 360.0;
  4191. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4192. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4193. }
  4194. return Arc2;
  4195. }());
  4196. BABYLON.Arc2 = Arc2;
  4197. var Path2 = (function () {
  4198. /**
  4199. * Creates a Path2 object from the starting 2D coordinates x and y.
  4200. */
  4201. function Path2(x, y) {
  4202. this._points = new Array();
  4203. this._length = 0.0;
  4204. this.closed = false;
  4205. this._points.push(new Vector2(x, y));
  4206. }
  4207. /**
  4208. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4209. * Returns the updated Path2.
  4210. */
  4211. Path2.prototype.addLineTo = function (x, y) {
  4212. if (closed) {
  4213. //Tools.Error("cannot add lines to closed paths");
  4214. return this;
  4215. }
  4216. var newPoint = new Vector2(x, y);
  4217. var previousPoint = this._points[this._points.length - 1];
  4218. this._points.push(newPoint);
  4219. this._length += newPoint.subtract(previousPoint).length();
  4220. return this;
  4221. };
  4222. /**
  4223. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4224. * Returns the updated Path2.
  4225. */
  4226. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4227. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4228. if (closed) {
  4229. //Tools.Error("cannot add arcs to closed paths");
  4230. return this;
  4231. }
  4232. var startPoint = this._points[this._points.length - 1];
  4233. var midPoint = new Vector2(midX, midY);
  4234. var endPoint = new Vector2(endX, endY);
  4235. var arc = new Arc2(startPoint, midPoint, endPoint);
  4236. var increment = arc.angle.radians() / numberOfSegments;
  4237. if (arc.orientation === Orientation.CW)
  4238. increment *= -1;
  4239. var currentAngle = arc.startAngle.radians() + increment;
  4240. for (var i = 0; i < numberOfSegments; i++) {
  4241. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4242. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4243. this.addLineTo(x, y);
  4244. currentAngle += increment;
  4245. }
  4246. return this;
  4247. };
  4248. /**
  4249. * Closes the Path2.
  4250. * Returns the Path2.
  4251. */
  4252. Path2.prototype.close = function () {
  4253. this.closed = true;
  4254. return this;
  4255. };
  4256. /**
  4257. * Returns the Path2 total length (float).
  4258. */
  4259. Path2.prototype.length = function () {
  4260. var result = this._length;
  4261. if (!this.closed) {
  4262. var lastPoint = this._points[this._points.length - 1];
  4263. var firstPoint = this._points[0];
  4264. result += (firstPoint.subtract(lastPoint).length());
  4265. }
  4266. return result;
  4267. };
  4268. /**
  4269. * Returns the Path2 internal array of points.
  4270. */
  4271. Path2.prototype.getPoints = function () {
  4272. return this._points;
  4273. };
  4274. /**
  4275. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4276. */
  4277. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4278. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4279. //Tools.Error("normalized length position should be between 0 and 1.");
  4280. return Vector2.Zero();
  4281. }
  4282. var lengthPosition = normalizedLengthPosition * this.length();
  4283. var previousOffset = 0;
  4284. for (var i = 0; i < this._points.length; i++) {
  4285. var j = (i + 1) % this._points.length;
  4286. var a = this._points[i];
  4287. var b = this._points[j];
  4288. var bToA = b.subtract(a);
  4289. var nextOffset = (bToA.length() + previousOffset);
  4290. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4291. var dir = bToA.normalize();
  4292. var localOffset = lengthPosition - previousOffset;
  4293. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4294. }
  4295. previousOffset = nextOffset;
  4296. }
  4297. //Tools.Error("internal error");
  4298. return Vector2.Zero();
  4299. };
  4300. /**
  4301. * Returns a new Path2 starting at the coordinates (x, y).
  4302. */
  4303. Path2.StartingAt = function (x, y) {
  4304. return new Path2(x, y);
  4305. };
  4306. return Path2;
  4307. }());
  4308. BABYLON.Path2 = Path2;
  4309. var Path3D = (function () {
  4310. /**
  4311. * new Path3D(path, normal, raw)
  4312. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4313. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4314. * path : an array of Vector3, the curve axis of the Path3D
  4315. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4316. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4317. */
  4318. function Path3D(path, firstNormal, raw) {
  4319. this.path = path;
  4320. this._curve = new Array();
  4321. this._distances = new Array();
  4322. this._tangents = new Array();
  4323. this._normals = new Array();
  4324. this._binormals = new Array();
  4325. for (var p = 0; p < path.length; p++) {
  4326. this._curve[p] = path[p].clone(); // hard copy
  4327. }
  4328. this._raw = raw || false;
  4329. this._compute(firstNormal);
  4330. }
  4331. /**
  4332. * Returns the Path3D array of successive Vector3 designing its curve.
  4333. */
  4334. Path3D.prototype.getCurve = function () {
  4335. return this._curve;
  4336. };
  4337. /**
  4338. * Returns an array populated with tangent vectors on each Path3D curve point.
  4339. */
  4340. Path3D.prototype.getTangents = function () {
  4341. return this._tangents;
  4342. };
  4343. /**
  4344. * Returns an array populated with normal vectors on each Path3D curve point.
  4345. */
  4346. Path3D.prototype.getNormals = function () {
  4347. return this._normals;
  4348. };
  4349. /**
  4350. * Returns an array populated with binormal vectors on each Path3D curve point.
  4351. */
  4352. Path3D.prototype.getBinormals = function () {
  4353. return this._binormals;
  4354. };
  4355. /**
  4356. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4357. */
  4358. Path3D.prototype.getDistances = function () {
  4359. return this._distances;
  4360. };
  4361. /**
  4362. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4363. * Returns the same object updated.
  4364. */
  4365. Path3D.prototype.update = function (path, firstNormal) {
  4366. for (var p = 0; p < path.length; p++) {
  4367. this._curve[p].x = path[p].x;
  4368. this._curve[p].y = path[p].y;
  4369. this._curve[p].z = path[p].z;
  4370. }
  4371. this._compute(firstNormal);
  4372. return this;
  4373. };
  4374. // private function compute() : computes tangents, normals and binormals
  4375. Path3D.prototype._compute = function (firstNormal) {
  4376. var l = this._curve.length;
  4377. // first and last tangents
  4378. this._tangents[0] = this._getFirstNonNullVector(0);
  4379. if (!this._raw) {
  4380. this._tangents[0].normalize();
  4381. }
  4382. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4383. if (!this._raw) {
  4384. this._tangents[l - 1].normalize();
  4385. }
  4386. // normals and binormals at first point : arbitrary vector with _normalVector()
  4387. var tg0 = this._tangents[0];
  4388. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4389. this._normals[0] = pp0;
  4390. if (!this._raw) {
  4391. this._normals[0].normalize();
  4392. }
  4393. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4394. if (!this._raw) {
  4395. this._binormals[0].normalize();
  4396. }
  4397. this._distances[0] = 0.0;
  4398. // normals and binormals : next points
  4399. var prev; // previous vector (segment)
  4400. var cur; // current vector (segment)
  4401. var curTang; // current tangent
  4402. // previous normal
  4403. var prevBinor; // previous binormal
  4404. for (var i = 1; i < l; i++) {
  4405. // tangents
  4406. prev = this._getLastNonNullVector(i);
  4407. if (i < l - 1) {
  4408. cur = this._getFirstNonNullVector(i);
  4409. this._tangents[i] = prev.add(cur);
  4410. this._tangents[i].normalize();
  4411. }
  4412. this._distances[i] = this._distances[i - 1] + prev.length();
  4413. // normals and binormals
  4414. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4415. curTang = this._tangents[i];
  4416. prevBinor = this._binormals[i - 1];
  4417. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4418. if (!this._raw) {
  4419. this._normals[i].normalize();
  4420. }
  4421. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4422. if (!this._raw) {
  4423. this._binormals[i].normalize();
  4424. }
  4425. }
  4426. };
  4427. // private function getFirstNonNullVector(index)
  4428. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4429. Path3D.prototype._getFirstNonNullVector = function (index) {
  4430. var i = 1;
  4431. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4432. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4433. i++;
  4434. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4435. }
  4436. return nNVector;
  4437. };
  4438. // private function getLastNonNullVector(index)
  4439. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4440. Path3D.prototype._getLastNonNullVector = function (index) {
  4441. var i = 1;
  4442. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4443. while (nLVector.length() === 0 && index > i + 1) {
  4444. i++;
  4445. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4446. }
  4447. return nLVector;
  4448. };
  4449. // private function normalVector(v0, vt, va) :
  4450. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4451. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4452. Path3D.prototype._normalVector = function (v0, vt, va) {
  4453. var normal0;
  4454. var tgl = vt.length();
  4455. if (tgl === 0.0) {
  4456. tgl = 1.0;
  4457. }
  4458. if (va === undefined || va === null) {
  4459. var point;
  4460. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4461. point = new Vector3(0.0, -1.0, 0.0);
  4462. }
  4463. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4464. point = new Vector3(1.0, 0.0, 0.0);
  4465. }
  4466. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4467. point = new Vector3(0.0, 0.0, 1.0);
  4468. }
  4469. normal0 = Vector3.Cross(vt, point);
  4470. }
  4471. else {
  4472. normal0 = Vector3.Cross(vt, va);
  4473. Vector3.CrossToRef(normal0, vt, normal0);
  4474. }
  4475. normal0.normalize();
  4476. return normal0;
  4477. };
  4478. return Path3D;
  4479. }());
  4480. BABYLON.Path3D = Path3D;
  4481. var Curve3 = (function () {
  4482. /**
  4483. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4484. * A Curve3 is designed from a series of successive Vector3.
  4485. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4486. */
  4487. function Curve3(points) {
  4488. this._length = 0.0;
  4489. this._points = points;
  4490. this._length = this._computeLength(points);
  4491. }
  4492. /**
  4493. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4494. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4495. * @param v1 (Vector3) the control point
  4496. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4497. * @param nbPoints (integer) the wanted number of points in the curve
  4498. */
  4499. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4500. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4501. var bez = new Array();
  4502. var equation = function (t, val0, val1, val2) {
  4503. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4504. return res;
  4505. };
  4506. for (var i = 0; i <= nbPoints; i++) {
  4507. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4508. }
  4509. return new Curve3(bez);
  4510. };
  4511. /**
  4512. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4513. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4514. * @param v1 (Vector3) the first control point
  4515. * @param v2 (Vector3) the second control point
  4516. * @param v3 (Vector3) the end point of the Cubic Bezier
  4517. * @param nbPoints (integer) the wanted number of points in the curve
  4518. */
  4519. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4520. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4521. var bez = new Array();
  4522. var equation = function (t, val0, val1, val2, val3) {
  4523. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4524. return res;
  4525. };
  4526. for (var i = 0; i <= nbPoints; i++) {
  4527. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4528. }
  4529. return new Curve3(bez);
  4530. };
  4531. /**
  4532. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4533. * @param p1 (Vector3) the origin point of the Hermite Spline
  4534. * @param t1 (Vector3) the tangent vector at the origin point
  4535. * @param p2 (Vector3) the end point of the Hermite Spline
  4536. * @param t2 (Vector3) the tangent vector at the end point
  4537. * @param nbPoints (integer) the wanted number of points in the curve
  4538. */
  4539. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4540. var hermite = new Array();
  4541. var step = 1.0 / nbPoints;
  4542. for (var i = 0; i <= nbPoints; i++) {
  4543. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4544. }
  4545. return new Curve3(hermite);
  4546. };
  4547. /**
  4548. * Returns a Curve3 object along a CatmullRom Spline curve :
  4549. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4550. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4551. */
  4552. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4553. var totalPoints = new Array();
  4554. totalPoints.push(points[0].clone());
  4555. Array.prototype.push.apply(totalPoints, points);
  4556. totalPoints.push(points[points.length - 1].clone());
  4557. var catmullRom = new Array();
  4558. var step = 1.0 / nbPoints;
  4559. for (var i = 0; i < totalPoints.length - 3; i++) {
  4560. var amount = 0.0;
  4561. for (var c = 0; c < nbPoints; c++) {
  4562. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4563. amount += step;
  4564. }
  4565. }
  4566. i--;
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. return new Curve3(catmullRom);
  4569. };
  4570. /**
  4571. * Returns the Curve3 stored array of successive Vector3
  4572. */
  4573. Curve3.prototype.getPoints = function () {
  4574. return this._points;
  4575. };
  4576. /**
  4577. * Returns the computed length (float) of the curve.
  4578. */
  4579. Curve3.prototype.length = function () {
  4580. return this._length;
  4581. };
  4582. /**
  4583. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4584. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4585. * curveA and curveB keep unchanged.
  4586. */
  4587. Curve3.prototype.continue = function (curve) {
  4588. var lastPoint = this._points[this._points.length - 1];
  4589. var continuedPoints = this._points.slice();
  4590. var curvePoints = curve.getPoints();
  4591. for (var i = 1; i < curvePoints.length; i++) {
  4592. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4593. }
  4594. var continuedCurve = new Curve3(continuedPoints);
  4595. return continuedCurve;
  4596. };
  4597. Curve3.prototype._computeLength = function (path) {
  4598. var l = 0;
  4599. for (var i = 1; i < path.length; i++) {
  4600. l += (path[i].subtract(path[i - 1])).length();
  4601. }
  4602. return l;
  4603. };
  4604. return Curve3;
  4605. }());
  4606. BABYLON.Curve3 = Curve3;
  4607. // Vertex formats
  4608. var PositionNormalVertex = (function () {
  4609. function PositionNormalVertex(position, normal) {
  4610. if (position === void 0) { position = Vector3.Zero(); }
  4611. if (normal === void 0) { normal = Vector3.Up(); }
  4612. this.position = position;
  4613. this.normal = normal;
  4614. }
  4615. PositionNormalVertex.prototype.clone = function () {
  4616. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4617. };
  4618. return PositionNormalVertex;
  4619. }());
  4620. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4621. var PositionNormalTextureVertex = (function () {
  4622. function PositionNormalTextureVertex(position, normal, uv) {
  4623. if (position === void 0) { position = Vector3.Zero(); }
  4624. if (normal === void 0) { normal = Vector3.Up(); }
  4625. if (uv === void 0) { uv = Vector2.Zero(); }
  4626. this.position = position;
  4627. this.normal = normal;
  4628. this.uv = uv;
  4629. }
  4630. PositionNormalTextureVertex.prototype.clone = function () {
  4631. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4632. };
  4633. return PositionNormalTextureVertex;
  4634. }());
  4635. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4636. // Temporary pre-allocated objects for engine internal use
  4637. // usage in any internal function :
  4638. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4639. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4640. var Tmp = (function () {
  4641. function Tmp() {
  4642. }
  4643. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4644. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4645. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4646. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4647. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4648. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4649. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4650. Matrix.Zero(), Matrix.Zero(),
  4651. Matrix.Zero(), Matrix.Zero(),
  4652. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4653. return Tmp;
  4654. }());
  4655. BABYLON.Tmp = Tmp;
  4656. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4657. var MathTmp = (function () {
  4658. function MathTmp() {
  4659. }
  4660. MathTmp.Vector3 = [Vector3.Zero()];
  4661. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4662. MathTmp.Quaternion = [Quaternion.Zero()];
  4663. return MathTmp;
  4664. }());
  4665. })(BABYLON || (BABYLON = {}));
  4666. //# sourceMappingURL=babylon.math.js.map
  4667. var BABYLON;
  4668. (function (BABYLON) {
  4669. var Scalar = (function () {
  4670. function Scalar() {
  4671. }
  4672. /**
  4673. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4674. */
  4675. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4676. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4677. var num = a - b;
  4678. return -epsilon <= num && num <= epsilon;
  4679. };
  4680. /**
  4681. * Returns a string : the upper case translation of the number i to hexadecimal.
  4682. */
  4683. Scalar.ToHex = function (i) {
  4684. var str = i.toString(16);
  4685. if (i <= 15) {
  4686. return ("0" + str).toUpperCase();
  4687. }
  4688. return str.toUpperCase();
  4689. };
  4690. /**
  4691. * Returns -1 if value is negative and +1 is value is positive.
  4692. * Returns the value itself if it's equal to zero.
  4693. */
  4694. Scalar.Sign = function (value) {
  4695. value = +value; // convert to a number
  4696. if (value === 0 || isNaN(value))
  4697. return value;
  4698. return value > 0 ? 1 : -1;
  4699. };
  4700. /**
  4701. * Returns the value itself if it's between min and max.
  4702. * Returns min if the value is lower than min.
  4703. * Returns max if the value is greater than max.
  4704. */
  4705. Scalar.Clamp = function (value, min, max) {
  4706. if (min === void 0) { min = 0; }
  4707. if (max === void 0) { max = 1; }
  4708. return Math.min(max, Math.max(min, value));
  4709. };
  4710. /**
  4711. * Returns the log2 of value.
  4712. */
  4713. Scalar.Log2 = function (value) {
  4714. return Math.log(value) * Math.LOG2E;
  4715. };
  4716. /**
  4717. * Loops the value, so that it is never larger than length and never smaller than 0.
  4718. *
  4719. * This is similar to the modulo operator but it works with floating point numbers.
  4720. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4721. * With t = 5 and length = 2.5, the result would be 0.0.
  4722. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4723. */
  4724. Scalar.Repeat = function (value, length) {
  4725. return value - Math.floor(value / length) * length;
  4726. };
  4727. /**
  4728. * Normalize the value between 0.0 and 1.0 using min and max values
  4729. */
  4730. Scalar.Normalize = function (value, min, max) {
  4731. return (value - min) / (max - min);
  4732. };
  4733. /**
  4734. * Denormalize the value from 0.0 and 1.0 using min and max values
  4735. */
  4736. Scalar.Denormalize = function (normalized, min, max) {
  4737. return (normalized * (max - min) + min);
  4738. };
  4739. /**
  4740. * Calculates the shortest difference between two given angles given in degrees.
  4741. */
  4742. Scalar.DeltaAngle = function (current, target) {
  4743. var num = Scalar.Repeat(target - current, 360.0);
  4744. if (num > 180.0) {
  4745. num -= 360.0;
  4746. }
  4747. return num;
  4748. };
  4749. /**
  4750. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4751. *
  4752. * The returned value will move back and forth between 0 and length
  4753. */
  4754. Scalar.PingPong = function (tx, length) {
  4755. var t = Scalar.Repeat(tx, length * 2.0);
  4756. return length - Math.abs(t - length);
  4757. };
  4758. /**
  4759. * Interpolates between min and max with smoothing at the limits.
  4760. *
  4761. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4762. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4763. */
  4764. Scalar.SmoothStep = function (from, to, tx) {
  4765. var t = Scalar.Clamp(tx);
  4766. t = -2.0 * t * t * t + 3.0 * t * t;
  4767. return to * t + from * (1.0 - t);
  4768. };
  4769. /**
  4770. * Moves a value current towards target.
  4771. *
  4772. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4773. * Negative values of maxDelta pushes the value away from target.
  4774. */
  4775. Scalar.MoveTowards = function (current, target, maxDelta) {
  4776. var result = 0;
  4777. if (Math.abs(target - current) <= maxDelta) {
  4778. result = target;
  4779. }
  4780. else {
  4781. result = current + Scalar.Sign(target - current) * maxDelta;
  4782. }
  4783. return result;
  4784. };
  4785. /**
  4786. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4787. *
  4788. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4789. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4790. */
  4791. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4792. var num = Scalar.DeltaAngle(current, target);
  4793. var result = 0;
  4794. if (-maxDelta < num && num < maxDelta) {
  4795. result = target;
  4796. }
  4797. else {
  4798. target = current + num;
  4799. result = Scalar.MoveTowards(current, target, maxDelta);
  4800. }
  4801. return result;
  4802. };
  4803. /**
  4804. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4805. */
  4806. Scalar.Lerp = function (start, end, amount) {
  4807. return start + ((end - start) * amount);
  4808. };
  4809. /**
  4810. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4811. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4812. */
  4813. Scalar.LerpAngle = function (start, end, amount) {
  4814. var num = Scalar.Repeat(end - start, 360.0);
  4815. if (num > 180.0) {
  4816. num -= 360.0;
  4817. }
  4818. return start + num * Scalar.Clamp(amount);
  4819. };
  4820. /**
  4821. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4822. */
  4823. Scalar.InverseLerp = function (a, b, value) {
  4824. var result = 0;
  4825. if (a != b) {
  4826. result = Scalar.Clamp((value - a) / (b - a));
  4827. }
  4828. else {
  4829. result = 0.0;
  4830. }
  4831. return result;
  4832. };
  4833. /**
  4834. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4835. */
  4836. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4837. var squared = amount * amount;
  4838. var cubed = amount * squared;
  4839. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4840. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4841. var part3 = (cubed - (2.0 * squared)) + amount;
  4842. var part4 = cubed - squared;
  4843. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4844. };
  4845. /**
  4846. * Returns a random float number between and min and max values
  4847. */
  4848. Scalar.RandomRange = function (min, max) {
  4849. if (min === max)
  4850. return min;
  4851. return ((Math.random() * (max - min)) + min);
  4852. };
  4853. /**
  4854. * This function returns percentage of a number in a given range.
  4855. *
  4856. * RangeToPercent(40,20,60) will return 0.5 (50%)
  4857. * RangeToPercent(34,0,100) will return 0.34 (34%)
  4858. */
  4859. Scalar.RangeToPercent = function (number, min, max) {
  4860. return ((number - min) / (max - min));
  4861. };
  4862. /**
  4863. * This function returns number that corresponds to the percentage in a given range.
  4864. *
  4865. * PercentToRange(0.34,0,100) will return 34.
  4866. */
  4867. Scalar.PercentToRange = function (percent, min, max) {
  4868. return ((max - min) * percent + min);
  4869. };
  4870. return Scalar;
  4871. }());
  4872. BABYLON.Scalar = Scalar;
  4873. })(BABYLON || (BABYLON = {}));
  4874. //# sourceMappingURL=babylon.math.scalar.js.map
  4875. //# sourceMappingURL=babylon.mixins.js.map
  4876. var BABYLON;
  4877. (function (BABYLON) {
  4878. var __decoratorInitialStore = {};
  4879. var __mergedStore = {};
  4880. var _copySource = function (creationFunction, source, instanciate) {
  4881. var destination = creationFunction();
  4882. // Tags
  4883. if (BABYLON.Tags) {
  4884. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4885. }
  4886. var classStore = getMergedStore(destination);
  4887. // Properties
  4888. for (var property in classStore) {
  4889. var propertyDescriptor = classStore[property];
  4890. var sourceProperty = source[property];
  4891. var propertyType = propertyDescriptor.type;
  4892. if (sourceProperty !== undefined && sourceProperty !== null) {
  4893. switch (propertyType) {
  4894. case 0: // Value
  4895. case 6:// Mesh reference
  4896. destination[property] = sourceProperty;
  4897. break;
  4898. case 1: // Texture
  4899. case 2: // Color3
  4900. case 3: // FresnelParameters
  4901. case 4: // Vector2
  4902. case 5: // Vector3
  4903. case 7:// Color Curves
  4904. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  4905. break;
  4906. }
  4907. }
  4908. }
  4909. return destination;
  4910. };
  4911. function getDirectStore(target) {
  4912. var classKey = target.getClassName();
  4913. if (!__decoratorInitialStore[classKey]) {
  4914. __decoratorInitialStore[classKey] = {};
  4915. }
  4916. return __decoratorInitialStore[classKey];
  4917. }
  4918. /**
  4919. * Return the list of properties flagged as serializable
  4920. * @param target: host object
  4921. */
  4922. function getMergedStore(target) {
  4923. var classKey = target.getClassName();
  4924. if (__mergedStore[classKey]) {
  4925. return __mergedStore[classKey];
  4926. }
  4927. __mergedStore[classKey] = {};
  4928. var store = __mergedStore[classKey];
  4929. var currentTarget = target;
  4930. var currentKey = classKey;
  4931. while (currentKey) {
  4932. var initialStore = __decoratorInitialStore[currentKey];
  4933. for (var property in initialStore) {
  4934. store[property] = initialStore[property];
  4935. }
  4936. var parent_1 = void 0;
  4937. var done = false;
  4938. do {
  4939. parent_1 = Object.getPrototypeOf(currentTarget);
  4940. if (!parent_1.getClassName) {
  4941. done = true;
  4942. break;
  4943. }
  4944. if (parent_1.getClassName() !== currentKey) {
  4945. break;
  4946. }
  4947. currentTarget = parent_1;
  4948. } while (parent_1);
  4949. if (done) {
  4950. break;
  4951. }
  4952. currentKey = parent_1.getClassName();
  4953. currentTarget = parent_1;
  4954. }
  4955. return store;
  4956. }
  4957. function generateSerializableMember(type, sourceName) {
  4958. return function (target, propertyKey) {
  4959. var classStore = getDirectStore(target);
  4960. if (!classStore[propertyKey]) {
  4961. classStore[propertyKey] = { type: type, sourceName: sourceName };
  4962. }
  4963. };
  4964. }
  4965. function generateExpandMember(setCallback, targetKey) {
  4966. return function (target, propertyKey) {
  4967. var key = targetKey || ("_" + propertyKey);
  4968. Object.defineProperty(target, propertyKey, {
  4969. get: function () {
  4970. return this[key];
  4971. },
  4972. set: function (value) {
  4973. if (this[key] === value) {
  4974. return;
  4975. }
  4976. this[key] = value;
  4977. target[setCallback].apply(this);
  4978. },
  4979. enumerable: true,
  4980. configurable: true
  4981. });
  4982. };
  4983. }
  4984. function expandToProperty(callback, targetKey) {
  4985. return generateExpandMember(callback, targetKey);
  4986. }
  4987. BABYLON.expandToProperty = expandToProperty;
  4988. function serialize(sourceName) {
  4989. return generateSerializableMember(0, sourceName); // value member
  4990. }
  4991. BABYLON.serialize = serialize;
  4992. function serializeAsTexture(sourceName) {
  4993. return generateSerializableMember(1, sourceName); // texture member
  4994. }
  4995. BABYLON.serializeAsTexture = serializeAsTexture;
  4996. function serializeAsColor3(sourceName) {
  4997. return generateSerializableMember(2, sourceName); // color3 member
  4998. }
  4999. BABYLON.serializeAsColor3 = serializeAsColor3;
  5000. function serializeAsFresnelParameters(sourceName) {
  5001. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5002. }
  5003. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5004. function serializeAsVector2(sourceName) {
  5005. return generateSerializableMember(4, sourceName); // vector2 member
  5006. }
  5007. BABYLON.serializeAsVector2 = serializeAsVector2;
  5008. function serializeAsVector3(sourceName) {
  5009. return generateSerializableMember(5, sourceName); // vector3 member
  5010. }
  5011. BABYLON.serializeAsVector3 = serializeAsVector3;
  5012. function serializeAsMeshReference(sourceName) {
  5013. return generateSerializableMember(6, sourceName); // mesh reference member
  5014. }
  5015. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5016. function serializeAsColorCurves(sourceName) {
  5017. return generateSerializableMember(7, sourceName); // color curves
  5018. }
  5019. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5020. function serializeAsColor4(sourceName) {
  5021. return generateSerializableMember(8, sourceName); // color 4
  5022. }
  5023. BABYLON.serializeAsColor4 = serializeAsColor4;
  5024. function serializeAsImageProcessingConfiguration(sourceName) {
  5025. return generateSerializableMember(9, sourceName); // image processing
  5026. }
  5027. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5028. var SerializationHelper = (function () {
  5029. function SerializationHelper() {
  5030. }
  5031. SerializationHelper.Serialize = function (entity, serializationObject) {
  5032. if (!serializationObject) {
  5033. serializationObject = {};
  5034. }
  5035. // Tags
  5036. if (BABYLON.Tags) {
  5037. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5038. }
  5039. var serializedProperties = getMergedStore(entity);
  5040. // Properties
  5041. for (var property in serializedProperties) {
  5042. var propertyDescriptor = serializedProperties[property];
  5043. var targetPropertyName = propertyDescriptor.sourceName || property;
  5044. var propertyType = propertyDescriptor.type;
  5045. var sourceProperty = entity[property];
  5046. if (sourceProperty !== undefined && sourceProperty !== null) {
  5047. switch (propertyType) {
  5048. case 0:// Value
  5049. serializationObject[targetPropertyName] = sourceProperty;
  5050. break;
  5051. case 1:// Texture
  5052. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5053. break;
  5054. case 2:// Color3
  5055. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5056. break;
  5057. case 3:// FresnelParameters
  5058. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5059. break;
  5060. case 4:// Vector2
  5061. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5062. break;
  5063. case 5:// Vector3
  5064. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5065. break;
  5066. case 6:// Mesh reference
  5067. serializationObject[targetPropertyName] = sourceProperty.id;
  5068. break;
  5069. case 7:// Color Curves
  5070. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5071. break;
  5072. case 8:// Color 4
  5073. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5074. break;
  5075. case 9:// Image Processing
  5076. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5077. break;
  5078. }
  5079. }
  5080. }
  5081. return serializationObject;
  5082. };
  5083. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5084. var destination = creationFunction();
  5085. // Tags
  5086. if (BABYLON.Tags) {
  5087. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5088. }
  5089. var classStore = getMergedStore(destination);
  5090. // Properties
  5091. for (var property in classStore) {
  5092. var propertyDescriptor = classStore[property];
  5093. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5094. var propertyType = propertyDescriptor.type;
  5095. if (sourceProperty !== undefined && sourceProperty !== null) {
  5096. switch (propertyType) {
  5097. case 0:// Value
  5098. destination[property] = sourceProperty;
  5099. break;
  5100. case 1:// Texture
  5101. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5102. break;
  5103. case 2:// Color3
  5104. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5105. break;
  5106. case 3:// FresnelParameters
  5107. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5108. break;
  5109. case 4:// Vector2
  5110. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5111. break;
  5112. case 5:// Vector3
  5113. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5114. break;
  5115. case 6:// Mesh reference
  5116. destination[property] = scene.getLastMeshByID(sourceProperty);
  5117. break;
  5118. case 7:// Color Curves
  5119. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5120. break;
  5121. case 8:// Color 4
  5122. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5123. break;
  5124. case 9:// Image Processing
  5125. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5126. break;
  5127. }
  5128. }
  5129. }
  5130. return destination;
  5131. };
  5132. SerializationHelper.Clone = function (creationFunction, source) {
  5133. return _copySource(creationFunction, source, false);
  5134. };
  5135. SerializationHelper.Instanciate = function (creationFunction, source) {
  5136. return _copySource(creationFunction, source, true);
  5137. };
  5138. return SerializationHelper;
  5139. }());
  5140. BABYLON.SerializationHelper = SerializationHelper;
  5141. })(BABYLON || (BABYLON = {}));
  5142. //# sourceMappingURL=babylon.decorators.js.map
  5143. var BABYLON;
  5144. (function (BABYLON) {
  5145. /**
  5146. * A class serves as a medium between the observable and its observers
  5147. */
  5148. var EventState = (function () {
  5149. /**
  5150. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5151. */
  5152. function EventState(mask, skipNextObservers) {
  5153. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5154. this.initalize(mask, skipNextObservers);
  5155. }
  5156. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5157. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5158. this.mask = mask;
  5159. this.skipNextObservers = skipNextObservers;
  5160. return this;
  5161. };
  5162. return EventState;
  5163. }());
  5164. BABYLON.EventState = EventState;
  5165. /**
  5166. * Represent an Observer registered to a given Observable object.
  5167. */
  5168. var Observer = (function () {
  5169. function Observer(callback, mask) {
  5170. this.callback = callback;
  5171. this.mask = mask;
  5172. }
  5173. return Observer;
  5174. }());
  5175. BABYLON.Observer = Observer;
  5176. /**
  5177. * The Observable class is a simple implementation of the Observable pattern.
  5178. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  5179. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5180. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  5181. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  5182. */
  5183. var Observable = (function () {
  5184. function Observable() {
  5185. this._observers = new Array();
  5186. this._eventState = new EventState(0);
  5187. }
  5188. /**
  5189. * Create a new Observer with the specified callback
  5190. * @param callback the callback that will be executed for that Observer
  5191. * @param mask the mask used to filter observers
  5192. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  5193. */
  5194. Observable.prototype.add = function (callback, mask, insertFirst) {
  5195. if (mask === void 0) { mask = -1; }
  5196. if (insertFirst === void 0) { insertFirst = false; }
  5197. if (!callback) {
  5198. return null;
  5199. }
  5200. var observer = new Observer(callback, mask);
  5201. if (insertFirst) {
  5202. this._observers.unshift(observer);
  5203. }
  5204. else {
  5205. this._observers.push(observer);
  5206. }
  5207. return observer;
  5208. };
  5209. /**
  5210. * Remove an Observer from the Observable object
  5211. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5212. */
  5213. Observable.prototype.remove = function (observer) {
  5214. var index = this._observers.indexOf(observer);
  5215. if (index !== -1) {
  5216. this._observers.splice(index, 1);
  5217. return true;
  5218. }
  5219. return false;
  5220. };
  5221. /**
  5222. * Remove a callback from the Observable object
  5223. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5224. */
  5225. Observable.prototype.removeCallback = function (callback) {
  5226. for (var index = 0; index < this._observers.length; index++) {
  5227. if (this._observers[index].callback === callback) {
  5228. this._observers.splice(index, 1);
  5229. return true;
  5230. }
  5231. }
  5232. return false;
  5233. };
  5234. /**
  5235. * Notify all Observers by calling their respective callback with the given data
  5236. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5237. * @param eventData
  5238. * @param mask
  5239. */
  5240. Observable.prototype.notifyObservers = function (eventData, mask) {
  5241. if (mask === void 0) { mask = -1; }
  5242. var state = this._eventState;
  5243. state.mask = mask;
  5244. state.skipNextObservers = false;
  5245. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5246. var obs = _a[_i];
  5247. if (obs.mask & mask) {
  5248. obs.callback(eventData, state);
  5249. }
  5250. if (state.skipNextObservers) {
  5251. return false;
  5252. }
  5253. }
  5254. return true;
  5255. };
  5256. /**
  5257. * return true is the Observable has at least one Observer registered
  5258. */
  5259. Observable.prototype.hasObservers = function () {
  5260. return this._observers.length > 0;
  5261. };
  5262. /**
  5263. * Clear the list of observers
  5264. */
  5265. Observable.prototype.clear = function () {
  5266. this._observers = new Array();
  5267. };
  5268. /**
  5269. * Clone the current observable
  5270. */
  5271. Observable.prototype.clone = function () {
  5272. var result = new Observable();
  5273. result._observers = this._observers.slice(0);
  5274. return result;
  5275. };
  5276. /**
  5277. * Does this observable handles observer registered with a given mask
  5278. * @param {number} trigger - the mask to be tested
  5279. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5280. **/
  5281. Observable.prototype.hasSpecificMask = function (mask) {
  5282. if (mask === void 0) { mask = -1; }
  5283. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5284. var obs = _a[_i];
  5285. if (obs.mask & mask && obs.mask === mask) {
  5286. return true;
  5287. }
  5288. }
  5289. return false;
  5290. };
  5291. return Observable;
  5292. }());
  5293. BABYLON.Observable = Observable;
  5294. })(BABYLON || (BABYLON = {}));
  5295. //# sourceMappingURL=babylon.observable.js.map
  5296. var BABYLON;
  5297. (function (BABYLON) {
  5298. var SmartArray = (function () {
  5299. function SmartArray(capacity) {
  5300. this.length = 0;
  5301. this._duplicateId = 0;
  5302. this.data = new Array(capacity);
  5303. this._id = SmartArray._GlobalId++;
  5304. }
  5305. SmartArray.prototype.push = function (value) {
  5306. this.data[this.length++] = value;
  5307. if (this.length > this.data.length) {
  5308. this.data.length *= 2;
  5309. }
  5310. if (!value.__smartArrayFlags) {
  5311. value.__smartArrayFlags = {};
  5312. }
  5313. value.__smartArrayFlags[this._id] = this._duplicateId;
  5314. };
  5315. SmartArray.prototype.forEach = function (func) {
  5316. for (var index = 0; index < this.length; index++) {
  5317. func(this.data[index]);
  5318. }
  5319. };
  5320. SmartArray.prototype.pushNoDuplicate = function (value) {
  5321. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5322. return false;
  5323. }
  5324. this.push(value);
  5325. return true;
  5326. };
  5327. SmartArray.prototype.sort = function (compareFn) {
  5328. this.data.sort(compareFn);
  5329. };
  5330. SmartArray.prototype.reset = function () {
  5331. this.length = 0;
  5332. this._duplicateId++;
  5333. };
  5334. SmartArray.prototype.dispose = function () {
  5335. this.reset();
  5336. if (this.data) {
  5337. this.data.length = 0;
  5338. this.data = null;
  5339. }
  5340. };
  5341. SmartArray.prototype.concat = function (array) {
  5342. if (array.length === 0) {
  5343. return;
  5344. }
  5345. if (this.length + array.length > this.data.length) {
  5346. this.data.length = (this.length + array.length) * 2;
  5347. }
  5348. for (var index = 0; index < array.length; index++) {
  5349. this.data[this.length++] = (array.data || array)[index];
  5350. }
  5351. };
  5352. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5353. if (array.length === 0) {
  5354. return;
  5355. }
  5356. if (this.length + array.length > this.data.length) {
  5357. this.data.length = (this.length + array.length) * 2;
  5358. }
  5359. for (var index = 0; index < array.length; index++) {
  5360. var item = (array.data || array)[index];
  5361. this.pushNoDuplicate(item);
  5362. }
  5363. };
  5364. SmartArray.prototype.indexOf = function (value) {
  5365. var position = this.data.indexOf(value);
  5366. if (position >= this.length) {
  5367. return -1;
  5368. }
  5369. return position;
  5370. };
  5371. SmartArray.prototype.contains = function (value) {
  5372. return this.data.indexOf(value) !== -1;
  5373. };
  5374. // Statics
  5375. SmartArray._GlobalId = 0;
  5376. return SmartArray;
  5377. }());
  5378. BABYLON.SmartArray = SmartArray;
  5379. })(BABYLON || (BABYLON = {}));
  5380. //# sourceMappingURL=babylon.smartArray.js.map
  5381. var BABYLON;
  5382. (function (BABYLON) {
  5383. // Screenshots
  5384. var screenshotCanvas;
  5385. var cloneValue = function (source, destinationObject) {
  5386. if (!source)
  5387. return null;
  5388. if (source instanceof BABYLON.Mesh) {
  5389. return null;
  5390. }
  5391. if (source instanceof BABYLON.SubMesh) {
  5392. return source.clone(destinationObject);
  5393. }
  5394. else if (source.clone) {
  5395. return source.clone();
  5396. }
  5397. return null;
  5398. };
  5399. var Tools = (function () {
  5400. function Tools() {
  5401. }
  5402. ;
  5403. /**
  5404. * Interpolates between a and b via alpha
  5405. * @param a The lower value (returned when alpha = 0)
  5406. * @param b The upper value (returned when alpha = 1)
  5407. * @param alpha The interpolation-factor
  5408. * @return The mixed value
  5409. */
  5410. Tools.Mix = function (a, b, alpha) {
  5411. return a * (1 - alpha) + b * alpha;
  5412. };
  5413. Tools.Instantiate = function (className) {
  5414. var arr = className.split(".");
  5415. var fn = (window || this);
  5416. for (var i = 0, len = arr.length; i < len; i++) {
  5417. fn = fn[arr[i]];
  5418. }
  5419. if (typeof fn !== "function") {
  5420. return null;
  5421. }
  5422. return fn;
  5423. };
  5424. Tools.SetImmediate = function (action) {
  5425. if (window.setImmediate) {
  5426. window.setImmediate(action);
  5427. }
  5428. else {
  5429. setTimeout(action, 1);
  5430. }
  5431. };
  5432. Tools.IsExponentOfTwo = function (value) {
  5433. var count = 1;
  5434. do {
  5435. count *= 2;
  5436. } while (count < value);
  5437. return count === value;
  5438. };
  5439. /**
  5440. * Find the next highest power of two.
  5441. * @param x Number to start search from.
  5442. * @return Next highest power of two.
  5443. */
  5444. Tools.CeilingPOT = function (x) {
  5445. x--;
  5446. x |= x >> 1;
  5447. x |= x >> 2;
  5448. x |= x >> 4;
  5449. x |= x >> 8;
  5450. x |= x >> 16;
  5451. x++;
  5452. return x;
  5453. };
  5454. /**
  5455. * Find the next lowest power of two.
  5456. * @param x Number to start search from.
  5457. * @return Next lowest power of two.
  5458. */
  5459. Tools.FloorPOT = function (x) {
  5460. x = x | (x >> 1);
  5461. x = x | (x >> 2);
  5462. x = x | (x >> 4);
  5463. x = x | (x >> 8);
  5464. x = x | (x >> 16);
  5465. return x - (x >> 1);
  5466. };
  5467. /**
  5468. * Find the nearest power of two.
  5469. * @param x Number to start search from.
  5470. * @return Next nearest power of two.
  5471. */
  5472. Tools.NearestPOT = function (x) {
  5473. var c = Tools.CeilingPOT(x);
  5474. var f = Tools.FloorPOT(x);
  5475. return (c - x) > (x - f) ? f : c;
  5476. };
  5477. Tools.GetExponentOfTwo = function (value, max, mode) {
  5478. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5479. var pot;
  5480. switch (mode) {
  5481. case BABYLON.Engine.SCALEMODE_FLOOR:
  5482. pot = Tools.FloorPOT(value);
  5483. break;
  5484. case BABYLON.Engine.SCALEMODE_NEAREST:
  5485. pot = Tools.NearestPOT(value);
  5486. break;
  5487. case BABYLON.Engine.SCALEMODE_CEILING:
  5488. pot = Tools.CeilingPOT(value);
  5489. break;
  5490. }
  5491. return Math.min(pot, max);
  5492. };
  5493. Tools.GetFilename = function (path) {
  5494. var index = path.lastIndexOf("/");
  5495. if (index < 0)
  5496. return path;
  5497. return path.substring(index + 1);
  5498. };
  5499. Tools.GetDOMTextContent = function (element) {
  5500. var result = "";
  5501. var child = element.firstChild;
  5502. while (child) {
  5503. if (child.nodeType === 3) {
  5504. result += child.textContent;
  5505. }
  5506. child = child.nextSibling;
  5507. }
  5508. return result;
  5509. };
  5510. Tools.ToDegrees = function (angle) {
  5511. return angle * 180 / Math.PI;
  5512. };
  5513. Tools.ToRadians = function (angle) {
  5514. return angle * Math.PI / 180;
  5515. };
  5516. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5517. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5518. var output = "";
  5519. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5520. var i = 0;
  5521. var bytes = new Uint8Array(buffer);
  5522. while (i < bytes.length) {
  5523. chr1 = bytes[i++];
  5524. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5525. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5526. enc1 = chr1 >> 2;
  5527. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5528. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5529. enc4 = chr3 & 63;
  5530. if (isNaN(chr2)) {
  5531. enc3 = enc4 = 64;
  5532. }
  5533. else if (isNaN(chr3)) {
  5534. enc4 = 64;
  5535. }
  5536. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5537. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5538. }
  5539. return "data:image/png;base64," + output;
  5540. };
  5541. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5542. if (bias === void 0) { bias = null; }
  5543. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5544. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5545. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5546. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5547. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5548. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5549. }
  5550. if (bias) {
  5551. minimum.x -= minimum.x * bias.x + bias.y;
  5552. minimum.y -= minimum.y * bias.x + bias.y;
  5553. minimum.z -= minimum.z * bias.x + bias.y;
  5554. maximum.x += maximum.x * bias.x + bias.y;
  5555. maximum.y += maximum.y * bias.x + bias.y;
  5556. maximum.z += maximum.z * bias.x + bias.y;
  5557. }
  5558. return {
  5559. minimum: minimum,
  5560. maximum: maximum
  5561. };
  5562. };
  5563. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5564. if (bias === void 0) { bias = null; }
  5565. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5566. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5567. if (!stride) {
  5568. stride = 3;
  5569. }
  5570. for (var index = start; index < start + count; index++) {
  5571. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5572. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5573. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5574. }
  5575. if (bias) {
  5576. minimum.x -= minimum.x * bias.x + bias.y;
  5577. minimum.y -= minimum.y * bias.x + bias.y;
  5578. minimum.z -= minimum.z * bias.x + bias.y;
  5579. maximum.x += maximum.x * bias.x + bias.y;
  5580. maximum.y += maximum.y * bias.x + bias.y;
  5581. maximum.z += maximum.z * bias.x + bias.y;
  5582. }
  5583. return {
  5584. minimum: minimum,
  5585. maximum: maximum
  5586. };
  5587. };
  5588. Tools.Vector2ArrayFeeder = function (array) {
  5589. return function (index) {
  5590. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5591. var length = isFloatArray ? array.length / 2 : array.length;
  5592. if (index >= length) {
  5593. return null;
  5594. }
  5595. if (isFloatArray) {
  5596. var fa = array;
  5597. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5598. }
  5599. var a = array;
  5600. return a[index];
  5601. };
  5602. };
  5603. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5604. if (bias === void 0) { bias = null; }
  5605. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5606. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5607. var i = 0;
  5608. var cur = feeder(i++);
  5609. while (cur) {
  5610. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5611. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5612. cur = feeder(i++);
  5613. }
  5614. if (bias) {
  5615. minimum.x -= minimum.x * bias.x + bias.y;
  5616. minimum.y -= minimum.y * bias.x + bias.y;
  5617. maximum.x += maximum.x * bias.x + bias.y;
  5618. maximum.y += maximum.y * bias.x + bias.y;
  5619. }
  5620. return {
  5621. minimum: minimum,
  5622. maximum: maximum
  5623. };
  5624. };
  5625. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5626. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5627. return undefined;
  5628. return Array.isArray(obj) ? obj : [obj];
  5629. };
  5630. // Misc.
  5631. Tools.GetPointerPrefix = function () {
  5632. var eventPrefix = "pointer";
  5633. // Check if pointer events are supported
  5634. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5635. eventPrefix = "mouse";
  5636. }
  5637. return eventPrefix;
  5638. };
  5639. /**
  5640. * @param func - the function to be called
  5641. * @param requester - the object that will request the next frame. Falls back to window.
  5642. */
  5643. Tools.QueueNewFrame = function (func, requester) {
  5644. if (requester === void 0) { requester = window; }
  5645. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5646. /*if(requester.isPresenting) {
  5647. return;
  5648. } else*/ if (requester.requestAnimationFrame)
  5649. requester.requestAnimationFrame(func);
  5650. else if (requester.msRequestAnimationFrame)
  5651. requester.msRequestAnimationFrame(func);
  5652. else if (requester.webkitRequestAnimationFrame)
  5653. requester.webkitRequestAnimationFrame(func);
  5654. else if (requester.mozRequestAnimationFrame)
  5655. requester.mozRequestAnimationFrame(func);
  5656. else if (requester.oRequestAnimationFrame)
  5657. requester.oRequestAnimationFrame(func);
  5658. else {
  5659. window.setTimeout(func, 16);
  5660. }
  5661. };
  5662. Tools.RequestFullscreen = function (element) {
  5663. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5664. if (!requestFunction)
  5665. return;
  5666. requestFunction.call(element);
  5667. };
  5668. Tools.ExitFullscreen = function () {
  5669. if (document.exitFullscreen) {
  5670. document.exitFullscreen();
  5671. }
  5672. else if (document.mozCancelFullScreen) {
  5673. document.mozCancelFullScreen();
  5674. }
  5675. else if (document.webkitCancelFullScreen) {
  5676. document.webkitCancelFullScreen();
  5677. }
  5678. else if (document.msCancelFullScreen) {
  5679. document.msCancelFullScreen();
  5680. }
  5681. };
  5682. Tools.SetCorsBehavior = function (url, img) {
  5683. if (Tools.CorsBehavior) {
  5684. switch (typeof (Tools.CorsBehavior)) {
  5685. case "function":
  5686. var result = Tools.CorsBehavior(url);
  5687. if (result) {
  5688. img.crossOrigin = result;
  5689. }
  5690. break;
  5691. case "string":
  5692. default:
  5693. img.crossOrigin = Tools.CorsBehavior;
  5694. break;
  5695. }
  5696. }
  5697. };
  5698. // External files
  5699. Tools.CleanUrl = function (url) {
  5700. url = url.replace(/#/mg, "%23");
  5701. return url;
  5702. };
  5703. Tools.LoadImage = function (url, onload, onerror, database) {
  5704. if (url instanceof ArrayBuffer) {
  5705. url = Tools.EncodeArrayBufferTobase64(url);
  5706. }
  5707. url = Tools.CleanUrl(url);
  5708. url = Tools.PreprocessUrl(url);
  5709. var img = new Image();
  5710. if (url.substr(0, 5) !== "data:") {
  5711. Tools.SetCorsBehavior(url, img);
  5712. }
  5713. img.onload = function () {
  5714. onload(img);
  5715. };
  5716. img.onerror = function (err) {
  5717. Tools.Error("Error while trying to load image: " + url);
  5718. if (Tools.UseFallbackTexture) {
  5719. img.src = Tools.fallbackTexture;
  5720. onload(img);
  5721. }
  5722. else {
  5723. onerror();
  5724. }
  5725. };
  5726. var noIndexedDB = function () {
  5727. img.src = url;
  5728. };
  5729. var loadFromIndexedDB = function () {
  5730. database.loadImageFromDB(url, img);
  5731. };
  5732. //ANY database to do!
  5733. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5734. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5735. }
  5736. else {
  5737. if (url.indexOf("file:") !== 0) {
  5738. noIndexedDB();
  5739. }
  5740. else {
  5741. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5742. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5743. try {
  5744. var blobURL;
  5745. try {
  5746. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5747. }
  5748. catch (ex) {
  5749. // Chrome doesn't support oneTimeOnly parameter
  5750. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5751. }
  5752. img.src = blobURL;
  5753. }
  5754. catch (e) {
  5755. img.src = null;
  5756. }
  5757. }
  5758. else {
  5759. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5760. img.src = Tools.fallbackTexture;
  5761. }
  5762. }
  5763. }
  5764. return img;
  5765. };
  5766. //ANY
  5767. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5768. url = Tools.CleanUrl(url);
  5769. url = Tools.PreprocessUrl(url);
  5770. var noIndexedDB = function () {
  5771. var request = new XMLHttpRequest();
  5772. var loadUrl = Tools.BaseUrl + url;
  5773. request.open('GET', loadUrl, true);
  5774. if (useArrayBuffer) {
  5775. request.responseType = "arraybuffer";
  5776. }
  5777. request.onprogress = progressCallBack;
  5778. request.onreadystatechange = function () {
  5779. // In case of undefined state in some browsers.
  5780. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5781. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5782. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5783. callback(!useArrayBuffer ? request.responseText : request.response);
  5784. }
  5785. else {
  5786. if (onError) {
  5787. onError(request);
  5788. }
  5789. else {
  5790. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5791. }
  5792. }
  5793. }
  5794. };
  5795. request.send(null);
  5796. };
  5797. var loadFromIndexedDB = function () {
  5798. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5799. };
  5800. if (url.indexOf("file:") !== -1) {
  5801. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5802. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5803. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5804. }
  5805. else {
  5806. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5807. }
  5808. }
  5809. else {
  5810. // Caching all files
  5811. if (database && database.enableSceneOffline) {
  5812. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5813. }
  5814. else {
  5815. noIndexedDB();
  5816. }
  5817. }
  5818. };
  5819. /**
  5820. * Load a script (identified by an url). When the url returns, the
  5821. * content of this file is added into a new script element, attached to the DOM (body element)
  5822. */
  5823. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5824. var head = document.getElementsByTagName('head')[0];
  5825. var script = document.createElement('script');
  5826. script.type = 'text/javascript';
  5827. script.src = scriptUrl;
  5828. var self = this;
  5829. script.onload = function () {
  5830. if (onSuccess) {
  5831. onSuccess();
  5832. }
  5833. };
  5834. script.onerror = function () {
  5835. if (onError) {
  5836. onError();
  5837. }
  5838. };
  5839. head.appendChild(script);
  5840. };
  5841. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5842. var reader = new FileReader();
  5843. reader.onload = function (e) {
  5844. //target doesn't have result from ts 1.3
  5845. callback(e.target['result']);
  5846. };
  5847. reader.onprogress = progressCallback;
  5848. reader.readAsDataURL(fileToLoad);
  5849. };
  5850. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5851. var reader = new FileReader();
  5852. reader.onerror = function (e) {
  5853. Tools.Log("Error while reading file: " + fileToLoad.name);
  5854. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5855. };
  5856. reader.onload = function (e) {
  5857. //target doesn't have result from ts 1.3
  5858. callback(e.target['result']);
  5859. };
  5860. reader.onprogress = progressCallBack;
  5861. if (!useArrayBuffer) {
  5862. // Asynchronous read
  5863. reader.readAsText(fileToLoad);
  5864. }
  5865. else {
  5866. reader.readAsArrayBuffer(fileToLoad);
  5867. }
  5868. };
  5869. //returns a downloadable url to a file content.
  5870. Tools.FileAsURL = function (content) {
  5871. var fileBlob = new Blob([content]);
  5872. var url = window.URL || window.webkitURL;
  5873. var link = url.createObjectURL(fileBlob);
  5874. return link;
  5875. };
  5876. // Misc.
  5877. Tools.Format = function (value, decimals) {
  5878. if (decimals === void 0) { decimals = 2; }
  5879. return value.toFixed(decimals);
  5880. };
  5881. Tools.CheckExtends = function (v, min, max) {
  5882. if (v.x < min.x)
  5883. min.x = v.x;
  5884. if (v.y < min.y)
  5885. min.y = v.y;
  5886. if (v.z < min.z)
  5887. min.z = v.z;
  5888. if (v.x > max.x)
  5889. max.x = v.x;
  5890. if (v.y > max.y)
  5891. max.y = v.y;
  5892. if (v.z > max.z)
  5893. max.z = v.z;
  5894. };
  5895. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5896. for (var prop in source) {
  5897. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5898. continue;
  5899. }
  5900. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5901. continue;
  5902. }
  5903. var sourceValue = source[prop];
  5904. var typeOfSourceValue = typeof sourceValue;
  5905. if (typeOfSourceValue === "function") {
  5906. continue;
  5907. }
  5908. if (typeOfSourceValue === "object") {
  5909. if (sourceValue instanceof Array) {
  5910. destination[prop] = [];
  5911. if (sourceValue.length > 0) {
  5912. if (typeof sourceValue[0] == "object") {
  5913. for (var index = 0; index < sourceValue.length; index++) {
  5914. var clonedValue = cloneValue(sourceValue[index], destination);
  5915. if (destination[prop].indexOf(clonedValue) === -1) {
  5916. destination[prop].push(clonedValue);
  5917. }
  5918. }
  5919. }
  5920. else {
  5921. destination[prop] = sourceValue.slice(0);
  5922. }
  5923. }
  5924. }
  5925. else {
  5926. destination[prop] = cloneValue(sourceValue, destination);
  5927. }
  5928. }
  5929. else {
  5930. destination[prop] = sourceValue;
  5931. }
  5932. }
  5933. };
  5934. Tools.IsEmpty = function (obj) {
  5935. for (var i in obj) {
  5936. return false;
  5937. }
  5938. return true;
  5939. };
  5940. Tools.RegisterTopRootEvents = function (events) {
  5941. for (var index = 0; index < events.length; index++) {
  5942. var event = events[index];
  5943. window.addEventListener(event.name, event.handler, false);
  5944. try {
  5945. if (window.parent) {
  5946. window.parent.addEventListener(event.name, event.handler, false);
  5947. }
  5948. }
  5949. catch (e) {
  5950. // Silently fails...
  5951. }
  5952. }
  5953. };
  5954. Tools.UnregisterTopRootEvents = function (events) {
  5955. for (var index = 0; index < events.length; index++) {
  5956. var event = events[index];
  5957. window.removeEventListener(event.name, event.handler);
  5958. try {
  5959. if (window.parent) {
  5960. window.parent.removeEventListener(event.name, event.handler);
  5961. }
  5962. }
  5963. catch (e) {
  5964. // Silently fails...
  5965. }
  5966. }
  5967. };
  5968. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5969. if (mimeType === void 0) { mimeType = "image/png"; }
  5970. // Read the contents of the framebuffer
  5971. var numberOfChannelsByLine = width * 4;
  5972. var halfHeight = height / 2;
  5973. //Reading datas from WebGL
  5974. var data = engine.readPixels(0, 0, width, height);
  5975. //To flip image on Y axis.
  5976. for (var i = 0; i < halfHeight; i++) {
  5977. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5978. var currentCell = j + i * numberOfChannelsByLine;
  5979. var targetLine = height - i - 1;
  5980. var targetCell = j + targetLine * numberOfChannelsByLine;
  5981. var temp = data[currentCell];
  5982. data[currentCell] = data[targetCell];
  5983. data[targetCell] = temp;
  5984. }
  5985. }
  5986. // Create a 2D canvas to store the result
  5987. if (!screenshotCanvas) {
  5988. screenshotCanvas = document.createElement('canvas');
  5989. }
  5990. screenshotCanvas.width = width;
  5991. screenshotCanvas.height = height;
  5992. var context = screenshotCanvas.getContext('2d');
  5993. // Copy the pixels to a 2D canvas
  5994. var imageData = context.createImageData(width, height);
  5995. var castData = (imageData.data);
  5996. castData.set(data);
  5997. context.putImageData(imageData, 0, 0);
  5998. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5999. };
  6000. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6001. if (mimeType === void 0) { mimeType = "image/png"; }
  6002. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6003. if (successCallback) {
  6004. successCallback(base64Image);
  6005. }
  6006. else {
  6007. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6008. if (("download" in document.createElement("a"))) {
  6009. var a = window.document.createElement("a");
  6010. a.href = base64Image;
  6011. var date = new Date();
  6012. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6013. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6014. window.document.body.appendChild(a);
  6015. a.addEventListener("click", function () {
  6016. a.parentElement.removeChild(a);
  6017. });
  6018. a.click();
  6019. //Or opening a new tab with the image if it is not possible to automatically start download.
  6020. }
  6021. else {
  6022. var newWindow = window.open("");
  6023. var img = newWindow.document.createElement("img");
  6024. img.src = base64Image;
  6025. newWindow.document.body.appendChild(img);
  6026. }
  6027. }
  6028. };
  6029. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6030. if (mimeType === void 0) { mimeType = "image/png"; }
  6031. var width;
  6032. var height;
  6033. // If a precision value is specified
  6034. if (size.precision) {
  6035. width = Math.round(engine.getRenderWidth() * size.precision);
  6036. height = Math.round(width / engine.getAspectRatio(camera));
  6037. }
  6038. else if (size.width && size.height) {
  6039. width = size.width;
  6040. height = size.height;
  6041. }
  6042. else if (size.width && !size.height) {
  6043. width = size.width;
  6044. height = Math.round(width / engine.getAspectRatio(camera));
  6045. }
  6046. else if (size.height && !size.width) {
  6047. height = size.height;
  6048. width = Math.round(height * engine.getAspectRatio(camera));
  6049. }
  6050. else if (!isNaN(size)) {
  6051. height = size;
  6052. width = size;
  6053. }
  6054. else {
  6055. Tools.Error("Invalid 'size' parameter !");
  6056. return;
  6057. }
  6058. if (!screenshotCanvas) {
  6059. screenshotCanvas = document.createElement('canvas');
  6060. }
  6061. screenshotCanvas.width = width;
  6062. screenshotCanvas.height = height;
  6063. var renderContext = screenshotCanvas.getContext("2d");
  6064. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6065. var newWidth = width;
  6066. var newHeight = newWidth / ratio;
  6067. if (newHeight > height) {
  6068. newHeight = height;
  6069. newWidth = newHeight * ratio;
  6070. }
  6071. var offsetX = Math.max(0, width - newWidth) / 2;
  6072. var offsetY = Math.max(0, height - newHeight) / 2;
  6073. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6074. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6075. };
  6076. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6077. if (mimeType === void 0) { mimeType = "image/png"; }
  6078. if (samples === void 0) { samples = 1; }
  6079. var width;
  6080. var height;
  6081. //If a precision value is specified
  6082. if (size.precision) {
  6083. width = Math.round(engine.getRenderWidth() * size.precision);
  6084. height = Math.round(width / engine.getAspectRatio(camera));
  6085. size = { width: width, height: height };
  6086. }
  6087. else if (size.width && size.height) {
  6088. width = size.width;
  6089. height = size.height;
  6090. }
  6091. else if (size.width && !size.height) {
  6092. width = size.width;
  6093. height = Math.round(width / engine.getAspectRatio(camera));
  6094. size = { width: width, height: height };
  6095. }
  6096. else if (size.height && !size.width) {
  6097. height = size.height;
  6098. width = Math.round(height * engine.getAspectRatio(camera));
  6099. size = { width: width, height: height };
  6100. }
  6101. else if (!isNaN(size)) {
  6102. height = size;
  6103. width = size;
  6104. }
  6105. else {
  6106. Tools.Error("Invalid 'size' parameter !");
  6107. return;
  6108. }
  6109. var scene = camera.getScene();
  6110. var previousCamera = null;
  6111. if (scene.activeCamera !== camera) {
  6112. previousCamera = scene.activeCamera;
  6113. scene.activeCamera = camera;
  6114. }
  6115. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6116. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6117. texture.renderList = null;
  6118. texture.samples = samples;
  6119. texture.onAfterRenderObservable.add(function () {
  6120. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6121. });
  6122. scene.incrementRenderId();
  6123. scene.resetCachedMaterial();
  6124. texture.render(true);
  6125. texture.dispose();
  6126. if (previousCamera) {
  6127. scene.activeCamera = previousCamera;
  6128. }
  6129. camera.getProjectionMatrix(true); // Force cache refresh;
  6130. };
  6131. // XHR response validator for local file scenario
  6132. Tools.ValidateXHRData = function (xhr, dataType) {
  6133. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6134. if (dataType === void 0) { dataType = 7; }
  6135. try {
  6136. if (dataType & 1) {
  6137. if (xhr.responseText && xhr.responseText.length > 0) {
  6138. return true;
  6139. }
  6140. else if (dataType === 1) {
  6141. return false;
  6142. }
  6143. }
  6144. if (dataType & 2) {
  6145. // Check header width and height since there is no "TGA" magic number
  6146. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6147. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6148. return true;
  6149. }
  6150. else if (dataType === 2) {
  6151. return false;
  6152. }
  6153. }
  6154. if (dataType & 4) {
  6155. // Check for the "DDS" magic number
  6156. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6157. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6158. return true;
  6159. }
  6160. else {
  6161. return false;
  6162. }
  6163. }
  6164. }
  6165. catch (e) {
  6166. // Global protection
  6167. }
  6168. return false;
  6169. };
  6170. /**
  6171. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6172. * Be aware Math.random() could cause collisions, but:
  6173. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  6174. */
  6175. Tools.RandomId = function () {
  6176. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6177. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6178. return v.toString(16);
  6179. });
  6180. };
  6181. Object.defineProperty(Tools, "NoneLogLevel", {
  6182. get: function () {
  6183. return Tools._NoneLogLevel;
  6184. },
  6185. enumerable: true,
  6186. configurable: true
  6187. });
  6188. Object.defineProperty(Tools, "MessageLogLevel", {
  6189. get: function () {
  6190. return Tools._MessageLogLevel;
  6191. },
  6192. enumerable: true,
  6193. configurable: true
  6194. });
  6195. Object.defineProperty(Tools, "WarningLogLevel", {
  6196. get: function () {
  6197. return Tools._WarningLogLevel;
  6198. },
  6199. enumerable: true,
  6200. configurable: true
  6201. });
  6202. Object.defineProperty(Tools, "ErrorLogLevel", {
  6203. get: function () {
  6204. return Tools._ErrorLogLevel;
  6205. },
  6206. enumerable: true,
  6207. configurable: true
  6208. });
  6209. Object.defineProperty(Tools, "AllLogLevel", {
  6210. get: function () {
  6211. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6212. },
  6213. enumerable: true,
  6214. configurable: true
  6215. });
  6216. Tools._AddLogEntry = function (entry) {
  6217. Tools._LogCache = entry + Tools._LogCache;
  6218. if (Tools.OnNewCacheEntry) {
  6219. Tools.OnNewCacheEntry(entry);
  6220. }
  6221. };
  6222. Tools._FormatMessage = function (message) {
  6223. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6224. var date = new Date();
  6225. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6226. };
  6227. Tools._LogDisabled = function (message) {
  6228. // nothing to do
  6229. };
  6230. Tools._LogEnabled = function (message) {
  6231. var formattedMessage = Tools._FormatMessage(message);
  6232. console.log("BJS - " + formattedMessage);
  6233. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6234. Tools._AddLogEntry(entry);
  6235. };
  6236. Tools._WarnDisabled = function (message) {
  6237. // nothing to do
  6238. };
  6239. Tools._WarnEnabled = function (message) {
  6240. var formattedMessage = Tools._FormatMessage(message);
  6241. console.warn("BJS - " + formattedMessage);
  6242. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6243. Tools._AddLogEntry(entry);
  6244. };
  6245. Tools._ErrorDisabled = function (message) {
  6246. // nothing to do
  6247. };
  6248. Tools._ErrorEnabled = function (message) {
  6249. Tools.errorsCount++;
  6250. var formattedMessage = Tools._FormatMessage(message);
  6251. console.error("BJS - " + formattedMessage);
  6252. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6253. Tools._AddLogEntry(entry);
  6254. };
  6255. Object.defineProperty(Tools, "LogCache", {
  6256. get: function () {
  6257. return Tools._LogCache;
  6258. },
  6259. enumerable: true,
  6260. configurable: true
  6261. });
  6262. Tools.ClearLogCache = function () {
  6263. Tools._LogCache = "";
  6264. Tools.errorsCount = 0;
  6265. };
  6266. Object.defineProperty(Tools, "LogLevels", {
  6267. set: function (level) {
  6268. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6269. Tools.Log = Tools._LogEnabled;
  6270. }
  6271. else {
  6272. Tools.Log = Tools._LogDisabled;
  6273. }
  6274. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6275. Tools.Warn = Tools._WarnEnabled;
  6276. }
  6277. else {
  6278. Tools.Warn = Tools._WarnDisabled;
  6279. }
  6280. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6281. Tools.Error = Tools._ErrorEnabled;
  6282. }
  6283. else {
  6284. Tools.Error = Tools._ErrorDisabled;
  6285. }
  6286. },
  6287. enumerable: true,
  6288. configurable: true
  6289. });
  6290. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6291. get: function () {
  6292. return Tools._PerformanceNoneLogLevel;
  6293. },
  6294. enumerable: true,
  6295. configurable: true
  6296. });
  6297. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6298. get: function () {
  6299. return Tools._PerformanceUserMarkLogLevel;
  6300. },
  6301. enumerable: true,
  6302. configurable: true
  6303. });
  6304. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6305. get: function () {
  6306. return Tools._PerformanceConsoleLogLevel;
  6307. },
  6308. enumerable: true,
  6309. configurable: true
  6310. });
  6311. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6312. set: function (level) {
  6313. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6314. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6315. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6316. return;
  6317. }
  6318. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6319. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6320. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6321. return;
  6322. }
  6323. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6324. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6325. },
  6326. enumerable: true,
  6327. configurable: true
  6328. });
  6329. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6330. };
  6331. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6332. };
  6333. Tools._StartUserMark = function (counterName, condition) {
  6334. if (condition === void 0) { condition = true; }
  6335. if (!condition || !Tools._performance.mark) {
  6336. return;
  6337. }
  6338. Tools._performance.mark(counterName + "-Begin");
  6339. };
  6340. Tools._EndUserMark = function (counterName, condition) {
  6341. if (condition === void 0) { condition = true; }
  6342. if (!condition || !Tools._performance.mark) {
  6343. return;
  6344. }
  6345. Tools._performance.mark(counterName + "-End");
  6346. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6347. };
  6348. Tools._StartPerformanceConsole = function (counterName, condition) {
  6349. if (condition === void 0) { condition = true; }
  6350. if (!condition) {
  6351. return;
  6352. }
  6353. Tools._StartUserMark(counterName, condition);
  6354. if (console.time) {
  6355. console.time(counterName);
  6356. }
  6357. };
  6358. Tools._EndPerformanceConsole = function (counterName, condition) {
  6359. if (condition === void 0) { condition = true; }
  6360. if (!condition) {
  6361. return;
  6362. }
  6363. Tools._EndUserMark(counterName, condition);
  6364. if (console.time) {
  6365. console.timeEnd(counterName);
  6366. }
  6367. };
  6368. Object.defineProperty(Tools, "Now", {
  6369. get: function () {
  6370. if (window.performance && window.performance.now) {
  6371. return window.performance.now();
  6372. }
  6373. return new Date().getTime();
  6374. },
  6375. enumerable: true,
  6376. configurable: true
  6377. });
  6378. /**
  6379. * This method will return the name of the class used to create the instance of the given object.
  6380. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6381. * @param object the object to get the class name from
  6382. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6383. */
  6384. Tools.GetClassName = function (object, isType) {
  6385. if (isType === void 0) { isType = false; }
  6386. var name = null;
  6387. if (!isType && object.getClassName) {
  6388. name = object.getClassName();
  6389. }
  6390. else {
  6391. if (object instanceof Object) {
  6392. var classObj = isType ? object : Object.getPrototypeOf(object);
  6393. name = classObj.constructor["__bjsclassName__"];
  6394. }
  6395. if (!name) {
  6396. name = typeof object;
  6397. }
  6398. }
  6399. return name;
  6400. };
  6401. Tools.first = function (array, predicate) {
  6402. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6403. var el = array_1[_i];
  6404. if (predicate(el)) {
  6405. return el;
  6406. }
  6407. }
  6408. };
  6409. /**
  6410. * This method will return the name of the full name of the class, including its owning module (if any).
  6411. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6412. * @param object the object to get the class name from
  6413. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6414. */
  6415. Tools.getFullClassName = function (object, isType) {
  6416. if (isType === void 0) { isType = false; }
  6417. var className = null;
  6418. var moduleName = null;
  6419. if (!isType && object.getClassName) {
  6420. className = object.getClassName();
  6421. }
  6422. else {
  6423. if (object instanceof Object) {
  6424. var classObj = isType ? object : Object.getPrototypeOf(object);
  6425. className = classObj.constructor["__bjsclassName__"];
  6426. moduleName = classObj.constructor["__bjsmoduleName__"];
  6427. }
  6428. if (!className) {
  6429. className = typeof object;
  6430. }
  6431. }
  6432. if (!className) {
  6433. return null;
  6434. }
  6435. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6436. };
  6437. /**
  6438. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  6439. * @param array
  6440. */
  6441. Tools.arrayOrStringFeeder = function (array) {
  6442. return function (index) {
  6443. if (index >= array.length) {
  6444. return null;
  6445. }
  6446. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6447. if (val && val.getHashCode) {
  6448. val = val.getHashCode();
  6449. }
  6450. if (typeof val === "string") {
  6451. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6452. }
  6453. return val;
  6454. };
  6455. };
  6456. /**
  6457. * Compute the hashCode of a stream of number
  6458. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6459. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6460. * @return the hash code computed
  6461. */
  6462. Tools.hashCodeFromStream = function (feeder) {
  6463. // Based from here: http://stackoverflow.com/a/7616484/802124
  6464. var hash = 0;
  6465. var index = 0;
  6466. var chr = feeder(index++);
  6467. while (chr != null) {
  6468. hash = ((hash << 5) - hash) + chr;
  6469. hash |= 0; // Convert to 32bit integer
  6470. chr = feeder(index++);
  6471. }
  6472. return hash;
  6473. };
  6474. Tools.BaseUrl = "";
  6475. Tools.CorsBehavior = "anonymous";
  6476. Tools.UseFallbackTexture = true;
  6477. // Used in case of a texture loading problem
  6478. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  6479. Tools.PreprocessUrl = function (url) {
  6480. return url;
  6481. };
  6482. // Logs
  6483. Tools._NoneLogLevel = 0;
  6484. Tools._MessageLogLevel = 1;
  6485. Tools._WarningLogLevel = 2;
  6486. Tools._ErrorLogLevel = 4;
  6487. Tools._LogCache = "";
  6488. Tools.errorsCount = 0;
  6489. Tools.Log = Tools._LogEnabled;
  6490. Tools.Warn = Tools._WarnEnabled;
  6491. Tools.Error = Tools._ErrorEnabled;
  6492. // Performances
  6493. Tools._PerformanceNoneLogLevel = 0;
  6494. Tools._PerformanceUserMarkLogLevel = 1;
  6495. Tools._PerformanceConsoleLogLevel = 2;
  6496. Tools._performance = window.performance;
  6497. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6498. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6499. return Tools;
  6500. }());
  6501. BABYLON.Tools = Tools;
  6502. /**
  6503. * This class is used to track a performance counter which is number based.
  6504. * The user has access to many properties which give statistics of different nature
  6505. *
  6506. * The implementer can track two kinds of Performance Counter: time and count
  6507. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  6508. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  6509. */
  6510. var PerfCounter = (function () {
  6511. function PerfCounter() {
  6512. this._startMonitoringTime = 0;
  6513. this._min = 0;
  6514. this._max = 0;
  6515. this._average = 0;
  6516. this._lastSecAverage = 0;
  6517. this._current = 0;
  6518. this._totalValueCount = 0;
  6519. this._totalAccumulated = 0;
  6520. this._lastSecAccumulated = 0;
  6521. this._lastSecTime = 0;
  6522. this._lastSecValueCount = 0;
  6523. }
  6524. Object.defineProperty(PerfCounter.prototype, "min", {
  6525. /**
  6526. * Returns the smallest value ever
  6527. */
  6528. get: function () {
  6529. return this._min;
  6530. },
  6531. enumerable: true,
  6532. configurable: true
  6533. });
  6534. Object.defineProperty(PerfCounter.prototype, "max", {
  6535. /**
  6536. * Returns the biggest value ever
  6537. */
  6538. get: function () {
  6539. return this._max;
  6540. },
  6541. enumerable: true,
  6542. configurable: true
  6543. });
  6544. Object.defineProperty(PerfCounter.prototype, "average", {
  6545. /**
  6546. * Returns the average value since the performance counter is running
  6547. */
  6548. get: function () {
  6549. return this._average;
  6550. },
  6551. enumerable: true,
  6552. configurable: true
  6553. });
  6554. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6555. /**
  6556. * Returns the average value of the last second the counter was monitored
  6557. */
  6558. get: function () {
  6559. return this._lastSecAverage;
  6560. },
  6561. enumerable: true,
  6562. configurable: true
  6563. });
  6564. Object.defineProperty(PerfCounter.prototype, "current", {
  6565. /**
  6566. * Returns the current value
  6567. */
  6568. get: function () {
  6569. return this._current;
  6570. },
  6571. enumerable: true,
  6572. configurable: true
  6573. });
  6574. Object.defineProperty(PerfCounter.prototype, "total", {
  6575. get: function () {
  6576. return this._totalAccumulated;
  6577. },
  6578. enumerable: true,
  6579. configurable: true
  6580. });
  6581. /**
  6582. * Call this method to start monitoring a new frame.
  6583. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  6584. */
  6585. PerfCounter.prototype.fetchNewFrame = function () {
  6586. this._totalValueCount++;
  6587. this._current = 0;
  6588. this._lastSecValueCount++;
  6589. };
  6590. /**
  6591. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6592. * @param newCount the count value to add to the monitored count
  6593. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  6594. */
  6595. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6596. if (!PerfCounter.Enabled) {
  6597. return;
  6598. }
  6599. this._current += newCount;
  6600. if (fetchResult) {
  6601. this._fetchResult();
  6602. }
  6603. };
  6604. /**
  6605. * Start monitoring this performance counter
  6606. */
  6607. PerfCounter.prototype.beginMonitoring = function () {
  6608. if (!PerfCounter.Enabled) {
  6609. return;
  6610. }
  6611. this._startMonitoringTime = Tools.Now;
  6612. };
  6613. /**
  6614. * Compute the time lapsed since the previous beginMonitoring() call.
  6615. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  6616. */
  6617. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6618. if (newFrame === void 0) { newFrame = true; }
  6619. if (!PerfCounter.Enabled) {
  6620. return;
  6621. }
  6622. if (newFrame) {
  6623. this.fetchNewFrame();
  6624. }
  6625. var currentTime = Tools.Now;
  6626. this._current = currentTime - this._startMonitoringTime;
  6627. if (newFrame) {
  6628. this._fetchResult();
  6629. }
  6630. };
  6631. PerfCounter.prototype._fetchResult = function () {
  6632. this._totalAccumulated += this._current;
  6633. this._lastSecAccumulated += this._current;
  6634. // Min/Max update
  6635. this._min = Math.min(this._min, this._current);
  6636. this._max = Math.max(this._max, this._current);
  6637. this._average = this._totalAccumulated / this._totalValueCount;
  6638. // Reset last sec?
  6639. var now = Tools.Now;
  6640. if ((now - this._lastSecTime) > 1000) {
  6641. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6642. this._lastSecTime = now;
  6643. this._lastSecAccumulated = 0;
  6644. this._lastSecValueCount = 0;
  6645. }
  6646. };
  6647. PerfCounter.Enabled = true;
  6648. return PerfCounter;
  6649. }());
  6650. BABYLON.PerfCounter = PerfCounter;
  6651. /**
  6652. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6653. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6654. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6655. * @param name The name of the class, case should be preserved
  6656. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6657. */
  6658. function className(name, module) {
  6659. return function (target) {
  6660. target["__bjsclassName__"] = name;
  6661. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6662. };
  6663. }
  6664. BABYLON.className = className;
  6665. /**
  6666. * An implementation of a loop for asynchronous functions.
  6667. */
  6668. var AsyncLoop = (function () {
  6669. /**
  6670. * Constroctor.
  6671. * @param iterations the number of iterations.
  6672. * @param _fn the function to run each iteration
  6673. * @param _successCallback the callback that will be called upon succesful execution
  6674. * @param offset starting offset.
  6675. */
  6676. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6677. if (offset === void 0) { offset = 0; }
  6678. this.iterations = iterations;
  6679. this._fn = _fn;
  6680. this._successCallback = _successCallback;
  6681. this.index = offset - 1;
  6682. this._done = false;
  6683. }
  6684. /**
  6685. * Execute the next iteration. Must be called after the last iteration was finished.
  6686. */
  6687. AsyncLoop.prototype.executeNext = function () {
  6688. if (!this._done) {
  6689. if (this.index + 1 < this.iterations) {
  6690. ++this.index;
  6691. this._fn(this);
  6692. }
  6693. else {
  6694. this.breakLoop();
  6695. }
  6696. }
  6697. };
  6698. /**
  6699. * Break the loop and run the success callback.
  6700. */
  6701. AsyncLoop.prototype.breakLoop = function () {
  6702. this._done = true;
  6703. this._successCallback();
  6704. };
  6705. /**
  6706. * Helper function
  6707. */
  6708. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6709. if (offset === void 0) { offset = 0; }
  6710. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6711. loop.executeNext();
  6712. return loop;
  6713. };
  6714. /**
  6715. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6716. * @param iterations total number of iterations
  6717. * @param syncedIterations number of synchronous iterations in each async iteration.
  6718. * @param fn the function to call each iteration.
  6719. * @param callback a success call back that will be called when iterating stops.
  6720. * @param breakFunction a break condition (optional)
  6721. * @param timeout timeout settings for the setTimeout function. default - 0.
  6722. * @constructor
  6723. */
  6724. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6725. if (timeout === void 0) { timeout = 0; }
  6726. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6727. if (breakFunction && breakFunction())
  6728. loop.breakLoop();
  6729. else {
  6730. setTimeout(function () {
  6731. for (var i = 0; i < syncedIterations; ++i) {
  6732. var iteration = (loop.index * syncedIterations) + i;
  6733. if (iteration >= iterations)
  6734. break;
  6735. fn(iteration);
  6736. if (breakFunction && breakFunction()) {
  6737. loop.breakLoop();
  6738. break;
  6739. }
  6740. }
  6741. loop.executeNext();
  6742. }, timeout);
  6743. }
  6744. }, callback);
  6745. };
  6746. return AsyncLoop;
  6747. }());
  6748. BABYLON.AsyncLoop = AsyncLoop;
  6749. })(BABYLON || (BABYLON = {}));
  6750. //# sourceMappingURL=babylon.tools.js.map
  6751. var BABYLON;
  6752. (function (BABYLON) {
  6753. var Internals;
  6754. (function (Internals) {
  6755. var _AlphaState = (function () {
  6756. /**
  6757. * Initializes the state.
  6758. */
  6759. function _AlphaState() {
  6760. this._isAlphaBlendDirty = false;
  6761. this._isBlendFunctionParametersDirty = false;
  6762. this._isBlendEquationParametersDirty = false;
  6763. this._isBlendConstantsDirty = false;
  6764. this._alphaBlend = false;
  6765. this._blendFunctionParameters = new Array(4);
  6766. this._blendEquationParameters = new Array(2);
  6767. this._blendConstants = new Array(4);
  6768. this.reset();
  6769. }
  6770. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6771. get: function () {
  6772. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6773. },
  6774. enumerable: true,
  6775. configurable: true
  6776. });
  6777. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6778. get: function () {
  6779. return this._alphaBlend;
  6780. },
  6781. set: function (value) {
  6782. if (this._alphaBlend === value) {
  6783. return;
  6784. }
  6785. this._alphaBlend = value;
  6786. this._isAlphaBlendDirty = true;
  6787. },
  6788. enumerable: true,
  6789. configurable: true
  6790. });
  6791. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6792. if (this._blendConstants[0] === r &&
  6793. this._blendConstants[1] === g &&
  6794. this._blendConstants[2] === b &&
  6795. this._blendConstants[3] === a) {
  6796. return;
  6797. }
  6798. this._blendConstants[0] = r;
  6799. this._blendConstants[1] = g;
  6800. this._blendConstants[2] = b;
  6801. this._blendConstants[3] = a;
  6802. this._isBlendConstantsDirty = true;
  6803. };
  6804. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6805. if (this._blendFunctionParameters[0] === value0 &&
  6806. this._blendFunctionParameters[1] === value1 &&
  6807. this._blendFunctionParameters[2] === value2 &&
  6808. this._blendFunctionParameters[3] === value3) {
  6809. return;
  6810. }
  6811. this._blendFunctionParameters[0] = value0;
  6812. this._blendFunctionParameters[1] = value1;
  6813. this._blendFunctionParameters[2] = value2;
  6814. this._blendFunctionParameters[3] = value3;
  6815. this._isBlendFunctionParametersDirty = true;
  6816. };
  6817. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6818. if (this._blendEquationParameters[0] === rgb &&
  6819. this._blendEquationParameters[1] === alpha) {
  6820. return;
  6821. }
  6822. this._blendEquationParameters[0] = rgb;
  6823. this._blendEquationParameters[1] = alpha;
  6824. this._isBlendEquationParametersDirty = true;
  6825. };
  6826. _AlphaState.prototype.reset = function () {
  6827. this._alphaBlend = false;
  6828. this._blendFunctionParameters[0] = null;
  6829. this._blendFunctionParameters[1] = null;
  6830. this._blendFunctionParameters[2] = null;
  6831. this._blendFunctionParameters[3] = null;
  6832. this._blendEquationParameters[0] = null;
  6833. this._blendEquationParameters[1] = null;
  6834. this._blendConstants[0] = null;
  6835. this._blendConstants[1] = null;
  6836. this._blendConstants[2] = null;
  6837. this._blendConstants[3] = null;
  6838. this._isAlphaBlendDirty = true;
  6839. this._isBlendFunctionParametersDirty = false;
  6840. this._isBlendEquationParametersDirty = false;
  6841. this._isBlendConstantsDirty = false;
  6842. };
  6843. _AlphaState.prototype.apply = function (gl) {
  6844. if (!this.isDirty) {
  6845. return;
  6846. }
  6847. // Alpha blend
  6848. if (this._isAlphaBlendDirty) {
  6849. if (this._alphaBlend) {
  6850. gl.enable(gl.BLEND);
  6851. }
  6852. else {
  6853. gl.disable(gl.BLEND);
  6854. }
  6855. this._isAlphaBlendDirty = false;
  6856. }
  6857. // Alpha function
  6858. if (this._isBlendFunctionParametersDirty) {
  6859. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6860. this._isBlendFunctionParametersDirty = false;
  6861. }
  6862. // Alpha equation
  6863. if (this._isBlendEquationParametersDirty) {
  6864. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6865. this._isBlendEquationParametersDirty = false;
  6866. }
  6867. // Constants
  6868. if (this._isBlendConstantsDirty) {
  6869. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6870. this._isBlendConstantsDirty = false;
  6871. }
  6872. };
  6873. return _AlphaState;
  6874. }());
  6875. Internals._AlphaState = _AlphaState;
  6876. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6877. })(BABYLON || (BABYLON = {}));
  6878. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6879. var BABYLON;
  6880. (function (BABYLON) {
  6881. var Internals;
  6882. (function (Internals) {
  6883. var _DepthCullingState = (function () {
  6884. /**
  6885. * Initializes the state.
  6886. */
  6887. function _DepthCullingState() {
  6888. this._isDepthTestDirty = false;
  6889. this._isDepthMaskDirty = false;
  6890. this._isDepthFuncDirty = false;
  6891. this._isCullFaceDirty = false;
  6892. this._isCullDirty = false;
  6893. this._isZOffsetDirty = false;
  6894. this.reset();
  6895. }
  6896. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6897. get: function () {
  6898. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6899. },
  6900. enumerable: true,
  6901. configurable: true
  6902. });
  6903. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6904. get: function () {
  6905. return this._zOffset;
  6906. },
  6907. set: function (value) {
  6908. if (this._zOffset === value) {
  6909. return;
  6910. }
  6911. this._zOffset = value;
  6912. this._isZOffsetDirty = true;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6918. get: function () {
  6919. return this._cullFace;
  6920. },
  6921. set: function (value) {
  6922. if (this._cullFace === value) {
  6923. return;
  6924. }
  6925. this._cullFace = value;
  6926. this._isCullFaceDirty = true;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6932. get: function () {
  6933. return this._cull;
  6934. },
  6935. set: function (value) {
  6936. if (this._cull === value) {
  6937. return;
  6938. }
  6939. this._cull = value;
  6940. this._isCullDirty = true;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6946. get: function () {
  6947. return this._depthFunc;
  6948. },
  6949. set: function (value) {
  6950. if (this._depthFunc === value) {
  6951. return;
  6952. }
  6953. this._depthFunc = value;
  6954. this._isDepthFuncDirty = true;
  6955. },
  6956. enumerable: true,
  6957. configurable: true
  6958. });
  6959. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6960. get: function () {
  6961. return this._depthMask;
  6962. },
  6963. set: function (value) {
  6964. if (this._depthMask === value) {
  6965. return;
  6966. }
  6967. this._depthMask = value;
  6968. this._isDepthMaskDirty = true;
  6969. },
  6970. enumerable: true,
  6971. configurable: true
  6972. });
  6973. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6974. get: function () {
  6975. return this._depthTest;
  6976. },
  6977. set: function (value) {
  6978. if (this._depthTest === value) {
  6979. return;
  6980. }
  6981. this._depthTest = value;
  6982. this._isDepthTestDirty = true;
  6983. },
  6984. enumerable: true,
  6985. configurable: true
  6986. });
  6987. _DepthCullingState.prototype.reset = function () {
  6988. this._depthMask = true;
  6989. this._depthTest = true;
  6990. this._depthFunc = null;
  6991. this._cullFace = null;
  6992. this._cull = null;
  6993. this._zOffset = 0;
  6994. this._isDepthTestDirty = true;
  6995. this._isDepthMaskDirty = true;
  6996. this._isDepthFuncDirty = false;
  6997. this._isCullFaceDirty = false;
  6998. this._isCullDirty = false;
  6999. this._isZOffsetDirty = false;
  7000. };
  7001. _DepthCullingState.prototype.apply = function (gl) {
  7002. if (!this.isDirty) {
  7003. return;
  7004. }
  7005. // Cull
  7006. if (this._isCullDirty) {
  7007. if (this.cull) {
  7008. gl.enable(gl.CULL_FACE);
  7009. }
  7010. else {
  7011. gl.disable(gl.CULL_FACE);
  7012. }
  7013. this._isCullDirty = false;
  7014. }
  7015. // Cull face
  7016. if (this._isCullFaceDirty) {
  7017. gl.cullFace(this.cullFace);
  7018. this._isCullFaceDirty = false;
  7019. }
  7020. // Depth mask
  7021. if (this._isDepthMaskDirty) {
  7022. gl.depthMask(this.depthMask);
  7023. this._isDepthMaskDirty = false;
  7024. }
  7025. // Depth test
  7026. if (this._isDepthTestDirty) {
  7027. if (this.depthTest) {
  7028. gl.enable(gl.DEPTH_TEST);
  7029. }
  7030. else {
  7031. gl.disable(gl.DEPTH_TEST);
  7032. }
  7033. this._isDepthTestDirty = false;
  7034. }
  7035. // Depth func
  7036. if (this._isDepthFuncDirty) {
  7037. gl.depthFunc(this.depthFunc);
  7038. this._isDepthFuncDirty = false;
  7039. }
  7040. // zOffset
  7041. if (this._isZOffsetDirty) {
  7042. if (this.zOffset) {
  7043. gl.enable(gl.POLYGON_OFFSET_FILL);
  7044. gl.polygonOffset(this.zOffset, 0);
  7045. }
  7046. else {
  7047. gl.disable(gl.POLYGON_OFFSET_FILL);
  7048. }
  7049. this._isZOffsetDirty = false;
  7050. }
  7051. };
  7052. return _DepthCullingState;
  7053. }());
  7054. Internals._DepthCullingState = _DepthCullingState;
  7055. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7056. })(BABYLON || (BABYLON = {}));
  7057. //# sourceMappingURL=babylon.depthCullingState.js.map
  7058. var BABYLON;
  7059. (function (BABYLON) {
  7060. var Internals;
  7061. (function (Internals) {
  7062. var _StencilState = (function () {
  7063. function _StencilState() {
  7064. this._isStencilTestDirty = false;
  7065. this._isStencilMaskDirty = false;
  7066. this._isStencilFuncDirty = false;
  7067. this._isStencilOpDirty = false;
  7068. this.reset();
  7069. }
  7070. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7071. get: function () {
  7072. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7073. },
  7074. enumerable: true,
  7075. configurable: true
  7076. });
  7077. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7078. get: function () {
  7079. return this._stencilFunc;
  7080. },
  7081. set: function (value) {
  7082. if (this._stencilFunc === value) {
  7083. return;
  7084. }
  7085. this._stencilFunc = value;
  7086. this._isStencilFuncDirty = true;
  7087. },
  7088. enumerable: true,
  7089. configurable: true
  7090. });
  7091. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7092. get: function () {
  7093. return this._stencilFuncRef;
  7094. },
  7095. set: function (value) {
  7096. if (this._stencilFuncRef === value) {
  7097. return;
  7098. }
  7099. this._stencilFuncRef = value;
  7100. this._isStencilFuncDirty = true;
  7101. },
  7102. enumerable: true,
  7103. configurable: true
  7104. });
  7105. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7106. get: function () {
  7107. return this._stencilFuncMask;
  7108. },
  7109. set: function (value) {
  7110. if (this._stencilFuncMask === value) {
  7111. return;
  7112. }
  7113. this._stencilFuncMask = value;
  7114. this._isStencilFuncDirty = true;
  7115. },
  7116. enumerable: true,
  7117. configurable: true
  7118. });
  7119. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7120. get: function () {
  7121. return this._stencilOpStencilFail;
  7122. },
  7123. set: function (value) {
  7124. if (this._stencilOpStencilFail === value) {
  7125. return;
  7126. }
  7127. this._stencilOpStencilFail = value;
  7128. this._isStencilOpDirty = true;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7134. get: function () {
  7135. return this._stencilOpDepthFail;
  7136. },
  7137. set: function (value) {
  7138. if (this._stencilOpDepthFail === value) {
  7139. return;
  7140. }
  7141. this._stencilOpDepthFail = value;
  7142. this._isStencilOpDirty = true;
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7148. get: function () {
  7149. return this._stencilOpStencilDepthPass;
  7150. },
  7151. set: function (value) {
  7152. if (this._stencilOpStencilDepthPass === value) {
  7153. return;
  7154. }
  7155. this._stencilOpStencilDepthPass = value;
  7156. this._isStencilOpDirty = true;
  7157. },
  7158. enumerable: true,
  7159. configurable: true
  7160. });
  7161. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7162. get: function () {
  7163. return this._stencilMask;
  7164. },
  7165. set: function (value) {
  7166. if (this._stencilMask === value) {
  7167. return;
  7168. }
  7169. this._stencilMask = value;
  7170. this._isStencilMaskDirty = true;
  7171. },
  7172. enumerable: true,
  7173. configurable: true
  7174. });
  7175. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7176. get: function () {
  7177. return this._stencilTest;
  7178. },
  7179. set: function (value) {
  7180. if (this._stencilTest === value) {
  7181. return;
  7182. }
  7183. this._stencilTest = value;
  7184. this._isStencilTestDirty = true;
  7185. },
  7186. enumerable: true,
  7187. configurable: true
  7188. });
  7189. _StencilState.prototype.reset = function () {
  7190. this._stencilTest = false;
  7191. this._stencilMask = 0xFF;
  7192. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7193. this._stencilFuncRef = 1;
  7194. this._stencilFuncMask = 0xFF;
  7195. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7196. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7197. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7198. this._isStencilTestDirty = true;
  7199. this._isStencilMaskDirty = true;
  7200. this._isStencilFuncDirty = true;
  7201. this._isStencilOpDirty = true;
  7202. };
  7203. _StencilState.prototype.apply = function (gl) {
  7204. if (!this.isDirty) {
  7205. return;
  7206. }
  7207. // Stencil test
  7208. if (this._isStencilTestDirty) {
  7209. if (this.stencilTest) {
  7210. gl.enable(gl.STENCIL_TEST);
  7211. }
  7212. else {
  7213. gl.disable(gl.STENCIL_TEST);
  7214. }
  7215. this._isStencilTestDirty = false;
  7216. }
  7217. // Stencil mask
  7218. if (this._isStencilMaskDirty) {
  7219. gl.stencilMask(this.stencilMask);
  7220. this._isStencilMaskDirty = false;
  7221. }
  7222. // Stencil func
  7223. if (this._isStencilFuncDirty) {
  7224. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7225. this._isStencilFuncDirty = false;
  7226. }
  7227. // Stencil op
  7228. if (this._isStencilOpDirty) {
  7229. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7230. this._isStencilOpDirty = false;
  7231. }
  7232. };
  7233. return _StencilState;
  7234. }());
  7235. Internals._StencilState = _StencilState;
  7236. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7237. })(BABYLON || (BABYLON = {}));
  7238. //# sourceMappingURL=babylon.stencilState.js.map
  7239. var BABYLON;
  7240. (function (BABYLON) {
  7241. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7242. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7243. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7244. gl.compileShader(shader);
  7245. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7246. throw new Error(gl.getShaderInfoLog(shader));
  7247. }
  7248. return shader;
  7249. };
  7250. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7251. var magFilter = gl.NEAREST;
  7252. var minFilter = gl.NEAREST;
  7253. switch (samplingMode) {
  7254. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7255. magFilter = gl.LINEAR;
  7256. if (generateMipMaps) {
  7257. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7258. }
  7259. else {
  7260. minFilter = gl.LINEAR;
  7261. }
  7262. break;
  7263. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7264. magFilter = gl.LINEAR;
  7265. if (generateMipMaps) {
  7266. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7267. }
  7268. else {
  7269. minFilter = gl.LINEAR;
  7270. }
  7271. break;
  7272. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7273. magFilter = gl.NEAREST;
  7274. if (generateMipMaps) {
  7275. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7276. }
  7277. else {
  7278. minFilter = gl.NEAREST;
  7279. }
  7280. break;
  7281. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7282. magFilter = gl.NEAREST;
  7283. if (generateMipMaps) {
  7284. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7285. }
  7286. else {
  7287. minFilter = gl.NEAREST;
  7288. }
  7289. break;
  7290. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7291. magFilter = gl.NEAREST;
  7292. if (generateMipMaps) {
  7293. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7294. }
  7295. else {
  7296. minFilter = gl.LINEAR;
  7297. }
  7298. break;
  7299. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7300. magFilter = gl.NEAREST;
  7301. if (generateMipMaps) {
  7302. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7303. }
  7304. else {
  7305. minFilter = gl.LINEAR;
  7306. }
  7307. break;
  7308. case BABYLON.Texture.NEAREST_LINEAR:
  7309. magFilter = gl.NEAREST;
  7310. minFilter = gl.LINEAR;
  7311. break;
  7312. case BABYLON.Texture.NEAREST_NEAREST:
  7313. magFilter = gl.NEAREST;
  7314. minFilter = gl.NEAREST;
  7315. break;
  7316. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7317. magFilter = gl.LINEAR;
  7318. if (generateMipMaps) {
  7319. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7320. }
  7321. else {
  7322. minFilter = gl.NEAREST;
  7323. }
  7324. break;
  7325. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7326. magFilter = gl.LINEAR;
  7327. if (generateMipMaps) {
  7328. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7329. }
  7330. else {
  7331. minFilter = gl.NEAREST;
  7332. }
  7333. break;
  7334. case BABYLON.Texture.LINEAR_LINEAR:
  7335. magFilter = gl.LINEAR;
  7336. minFilter = gl.LINEAR;
  7337. break;
  7338. case BABYLON.Texture.LINEAR_NEAREST:
  7339. magFilter = gl.LINEAR;
  7340. minFilter = gl.NEAREST;
  7341. break;
  7342. }
  7343. return {
  7344. min: minFilter,
  7345. mag: magFilter
  7346. };
  7347. };
  7348. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7349. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7350. var img;
  7351. var onload = function () {
  7352. loadedImages[index] = img;
  7353. loadedImages._internalCount++;
  7354. if (scene) {
  7355. scene._removePendingData(img);
  7356. }
  7357. if (loadedImages._internalCount === 6) {
  7358. onfinish(loadedImages);
  7359. }
  7360. };
  7361. var onerror = function () {
  7362. if (scene) {
  7363. scene._removePendingData(img);
  7364. }
  7365. if (onErrorCallBack) {
  7366. onErrorCallBack();
  7367. }
  7368. };
  7369. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7370. if (scene) {
  7371. scene._addPendingData(img);
  7372. }
  7373. };
  7374. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7375. if (onError === void 0) { onError = null; }
  7376. var loadedImages = [];
  7377. loadedImages._internalCount = 0;
  7378. for (var index = 0; index < 6; index++) {
  7379. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7380. }
  7381. };
  7382. var BufferPointer = (function () {
  7383. function BufferPointer() {
  7384. }
  7385. return BufferPointer;
  7386. }());
  7387. var InstancingAttributeInfo = (function () {
  7388. function InstancingAttributeInfo() {
  7389. }
  7390. return InstancingAttributeInfo;
  7391. }());
  7392. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7393. /**
  7394. * Regroup several parameters relative to the browser in use
  7395. */
  7396. var EngineCapabilities = (function () {
  7397. function EngineCapabilities() {
  7398. }
  7399. return EngineCapabilities;
  7400. }());
  7401. BABYLON.EngineCapabilities = EngineCapabilities;
  7402. /**
  7403. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7404. */
  7405. var Engine = (function () {
  7406. /**
  7407. * @constructor
  7408. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7409. * @param {boolean} [antialias] - enable antialias
  7410. * @param options - further options to be sent to the getContext function
  7411. */
  7412. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7413. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7414. var _this = this;
  7415. // Public members
  7416. this.forcePOTTextures = false;
  7417. this.isFullscreen = false;
  7418. this.isPointerLock = false;
  7419. this.cullBackFaces = true;
  7420. this.renderEvenInBackground = true;
  7421. this.preventCacheWipeBetweenFrames = false;
  7422. // To enable/disable IDB support and avoid XHR on .manifest
  7423. this.enableOfflineSupport = false;
  7424. this.scenes = new Array();
  7425. // Observables
  7426. /**
  7427. * Observable event triggered each time the rendering canvas is resized
  7428. */
  7429. this.onResizeObservable = new BABYLON.Observable();
  7430. /**
  7431. * Observable event triggered each time the canvas lost focus
  7432. */
  7433. this.onCanvasBlurObservable = new BABYLON.Observable();
  7434. // Uniform buffers list
  7435. this._uniformBuffers = new Array();
  7436. this._windowIsBackground = false;
  7437. this._webGLVersion = 1.0;
  7438. this._badOS = false;
  7439. this._badDesktopOS = false;
  7440. this._drawCalls = new BABYLON.PerfCounter();
  7441. this._renderingQueueLaunched = false;
  7442. this._activeRenderLoops = [];
  7443. // Deterministic lockstepMaxSteps
  7444. this._deterministicLockstep = false;
  7445. this._lockstepMaxSteps = 4;
  7446. this._contextWasLost = false;
  7447. this._doNotHandleContextLost = false;
  7448. // FPS
  7449. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7450. this._fps = 60;
  7451. this._deltaTime = 0;
  7452. /**
  7453. * Turn this value on if you want to pause FPS computation when in background
  7454. */
  7455. this.disablePerformanceMonitorInBackground = false;
  7456. // States
  7457. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7458. this._stencilState = new BABYLON.Internals._StencilState();
  7459. this._alphaState = new BABYLON.Internals._AlphaState();
  7460. this._alphaMode = Engine.ALPHA_DISABLE;
  7461. // Cache
  7462. this._internalTexturesCache = new Array();
  7463. this._maxTextureChannels = 16;
  7464. this._activeTexturesCache = {};
  7465. this._compiledEffects = {};
  7466. this._vertexAttribArraysEnabled = [];
  7467. this._uintIndicesCurrentlySet = false;
  7468. this._currentBoundBuffer = new Array();
  7469. this._currentBufferPointers = new Array();
  7470. this._currentInstanceLocations = new Array();
  7471. this._currentInstanceBuffers = new Array();
  7472. this._vaoRecordInProgress = false;
  7473. this._mustWipeVertexAttributes = false;
  7474. // Hardware supported Compressed Textures
  7475. this._texturesSupported = new Array();
  7476. this._onVRFullScreenTriggered = function () {
  7477. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7478. //get the old size before we change
  7479. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7480. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7481. //get the width and height, change the render size
  7482. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7483. var width, height;
  7484. _this.setHardwareScalingLevel(1);
  7485. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7486. }
  7487. else {
  7488. //When the specs are implemented, need to uncomment this.
  7489. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7490. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7491. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7492. _this._vrDisplayEnabled = undefined;
  7493. }
  7494. };
  7495. var canvas;
  7496. Engine.Instances.push(this);
  7497. options = options || {};
  7498. if (canvasOrContext.getContext) {
  7499. canvas = canvasOrContext;
  7500. this._renderingCanvas = canvas;
  7501. if (antialias != null) {
  7502. options.antialias = antialias;
  7503. }
  7504. if (options.deterministicLockstep === undefined) {
  7505. options.deterministicLockstep = false;
  7506. }
  7507. if (options.lockstepMaxSteps === undefined) {
  7508. options.lockstepMaxSteps = 4;
  7509. }
  7510. if (options.preserveDrawingBuffer === undefined) {
  7511. options.preserveDrawingBuffer = false;
  7512. }
  7513. if (options.audioEngine === undefined) {
  7514. options.audioEngine = true;
  7515. }
  7516. if (options.stencil === undefined) {
  7517. options.stencil = true;
  7518. }
  7519. this._deterministicLockstep = options.deterministicLockstep;
  7520. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7521. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7522. // GL
  7523. if (!options.disableWebGL2Support) {
  7524. try {
  7525. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7526. if (this._gl) {
  7527. this._webGLVersion = 2.0;
  7528. }
  7529. }
  7530. catch (e) {
  7531. // Do nothing
  7532. }
  7533. }
  7534. if (!this._gl) {
  7535. if (!canvas) {
  7536. throw new Error("The provided canvas is null or undefined.");
  7537. }
  7538. try {
  7539. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7540. }
  7541. catch (e) {
  7542. throw new Error("WebGL not supported");
  7543. }
  7544. }
  7545. if (!this._gl) {
  7546. throw new Error("WebGL not supported");
  7547. }
  7548. this._onBlur = function () {
  7549. if (_this.disablePerformanceMonitorInBackground) {
  7550. _this._performanceMonitor.disable();
  7551. }
  7552. _this._windowIsBackground = true;
  7553. };
  7554. this._onFocus = function () {
  7555. if (_this.disablePerformanceMonitorInBackground) {
  7556. _this._performanceMonitor.enable();
  7557. }
  7558. _this._windowIsBackground = false;
  7559. };
  7560. this._onCanvasBlur = function () {
  7561. _this.onCanvasBlurObservable.notifyObservers(_this);
  7562. };
  7563. window.addEventListener("blur", this._onBlur);
  7564. window.addEventListener("focus", this._onFocus);
  7565. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7566. }
  7567. else {
  7568. this._gl = canvasOrContext;
  7569. this._renderingCanvas = this._gl.canvas;
  7570. if (this._gl.renderbufferStorageMultisample) {
  7571. this._webGLVersion = 2.0;
  7572. }
  7573. options.stencil = this._gl.getContextAttributes().stencil;
  7574. }
  7575. // Context lost
  7576. if (!this._doNotHandleContextLost) {
  7577. this._onContextLost = function (evt) {
  7578. evt.preventDefault();
  7579. _this._contextWasLost = true;
  7580. BABYLON.Tools.Warn("WebGL context lost.");
  7581. };
  7582. this._onContextRestored = function (evt) {
  7583. _this._contextWasLost = false;
  7584. // Rebuild gl context
  7585. _this._initGLContext();
  7586. // Rebuild effects
  7587. _this._rebuildEffects();
  7588. // Rebuild textures
  7589. _this._rebuildInternalTextures();
  7590. // Rebuild buffers
  7591. _this._rebuildBuffers();
  7592. // Cache
  7593. _this.wipeCaches(true);
  7594. // Restart render loop
  7595. _this._renderLoop();
  7596. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7597. };
  7598. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7599. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7600. }
  7601. // Viewport
  7602. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7603. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7604. this.resize();
  7605. this._isStencilEnable = options.stencil;
  7606. this._initGLContext();
  7607. if (canvas) {
  7608. // Fullscreen
  7609. this._onFullscreenChange = function () {
  7610. if (document.fullscreen !== undefined) {
  7611. _this.isFullscreen = document.fullscreen;
  7612. }
  7613. else if (document.mozFullScreen !== undefined) {
  7614. _this.isFullscreen = document.mozFullScreen;
  7615. }
  7616. else if (document.webkitIsFullScreen !== undefined) {
  7617. _this.isFullscreen = document.webkitIsFullScreen;
  7618. }
  7619. else if (document.msIsFullScreen !== undefined) {
  7620. _this.isFullscreen = document.msIsFullScreen;
  7621. }
  7622. // Pointer lock
  7623. if (_this.isFullscreen && _this._pointerLockRequested) {
  7624. canvas.requestPointerLock = canvas.requestPointerLock ||
  7625. canvas.msRequestPointerLock ||
  7626. canvas.mozRequestPointerLock ||
  7627. canvas.webkitRequestPointerLock;
  7628. if (canvas.requestPointerLock) {
  7629. canvas.requestPointerLock();
  7630. }
  7631. }
  7632. };
  7633. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7634. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7635. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7636. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7637. // Pointer lock
  7638. this._onPointerLockChange = function () {
  7639. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7640. document.webkitPointerLockElement === canvas ||
  7641. document.msPointerLockElement === canvas ||
  7642. document.pointerLockElement === canvas);
  7643. };
  7644. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7645. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7646. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7647. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7648. this._onVRDisplayPointerRestricted = function () {
  7649. canvas.requestPointerLock();
  7650. };
  7651. this._onVRDisplayPointerUnrestricted = function () {
  7652. document.exitPointerLock();
  7653. };
  7654. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7655. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7656. }
  7657. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7658. Engine.audioEngine = new BABYLON.AudioEngine();
  7659. }
  7660. // Prepare buffer pointers
  7661. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7662. this._currentBufferPointers[i] = new BufferPointer();
  7663. }
  7664. // Load WebVR Devices
  7665. if (options.autoEnableWebVR) {
  7666. this.initWebVR();
  7667. }
  7668. // Detect if we are running on a faulty buggy OS.
  7669. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7670. // Detect if we are running on a faulty buggy desktop OS.
  7671. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7672. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7673. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7674. }
  7675. Object.defineProperty(Engine, "LastCreatedEngine", {
  7676. get: function () {
  7677. if (Engine.Instances.length === 0) {
  7678. return null;
  7679. }
  7680. return Engine.Instances[Engine.Instances.length - 1];
  7681. },
  7682. enumerable: true,
  7683. configurable: true
  7684. });
  7685. Object.defineProperty(Engine, "LastCreatedScene", {
  7686. get: function () {
  7687. var lastCreatedEngine = Engine.LastCreatedEngine;
  7688. if (!lastCreatedEngine) {
  7689. return null;
  7690. }
  7691. if (lastCreatedEngine.scenes.length === 0) {
  7692. return null;
  7693. }
  7694. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7695. },
  7696. enumerable: true,
  7697. configurable: true
  7698. });
  7699. /**
  7700. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7701. */
  7702. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7703. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7704. var engine = Engine.Instances[engineIndex];
  7705. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7706. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7707. }
  7708. }
  7709. };
  7710. Object.defineProperty(Engine, "NEVER", {
  7711. get: function () {
  7712. return Engine._NEVER;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. Object.defineProperty(Engine, "ALWAYS", {
  7718. get: function () {
  7719. return Engine._ALWAYS;
  7720. },
  7721. enumerable: true,
  7722. configurable: true
  7723. });
  7724. Object.defineProperty(Engine, "LESS", {
  7725. get: function () {
  7726. return Engine._LESS;
  7727. },
  7728. enumerable: true,
  7729. configurable: true
  7730. });
  7731. Object.defineProperty(Engine, "EQUAL", {
  7732. get: function () {
  7733. return Engine._EQUAL;
  7734. },
  7735. enumerable: true,
  7736. configurable: true
  7737. });
  7738. Object.defineProperty(Engine, "LEQUAL", {
  7739. get: function () {
  7740. return Engine._LEQUAL;
  7741. },
  7742. enumerable: true,
  7743. configurable: true
  7744. });
  7745. Object.defineProperty(Engine, "GREATER", {
  7746. get: function () {
  7747. return Engine._GREATER;
  7748. },
  7749. enumerable: true,
  7750. configurable: true
  7751. });
  7752. Object.defineProperty(Engine, "GEQUAL", {
  7753. get: function () {
  7754. return Engine._GEQUAL;
  7755. },
  7756. enumerable: true,
  7757. configurable: true
  7758. });
  7759. Object.defineProperty(Engine, "NOTEQUAL", {
  7760. get: function () {
  7761. return Engine._NOTEQUAL;
  7762. },
  7763. enumerable: true,
  7764. configurable: true
  7765. });
  7766. Object.defineProperty(Engine, "KEEP", {
  7767. get: function () {
  7768. return Engine._KEEP;
  7769. },
  7770. enumerable: true,
  7771. configurable: true
  7772. });
  7773. Object.defineProperty(Engine, "REPLACE", {
  7774. get: function () {
  7775. return Engine._REPLACE;
  7776. },
  7777. enumerable: true,
  7778. configurable: true
  7779. });
  7780. Object.defineProperty(Engine, "INCR", {
  7781. get: function () {
  7782. return Engine._INCR;
  7783. },
  7784. enumerable: true,
  7785. configurable: true
  7786. });
  7787. Object.defineProperty(Engine, "DECR", {
  7788. get: function () {
  7789. return Engine._DECR;
  7790. },
  7791. enumerable: true,
  7792. configurable: true
  7793. });
  7794. Object.defineProperty(Engine, "INVERT", {
  7795. get: function () {
  7796. return Engine._INVERT;
  7797. },
  7798. enumerable: true,
  7799. configurable: true
  7800. });
  7801. Object.defineProperty(Engine, "INCR_WRAP", {
  7802. get: function () {
  7803. return Engine._INCR_WRAP;
  7804. },
  7805. enumerable: true,
  7806. configurable: true
  7807. });
  7808. Object.defineProperty(Engine, "DECR_WRAP", {
  7809. get: function () {
  7810. return Engine._DECR_WRAP;
  7811. },
  7812. enumerable: true,
  7813. configurable: true
  7814. });
  7815. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7816. get: function () {
  7817. return Engine._ALPHA_DISABLE;
  7818. },
  7819. enumerable: true,
  7820. configurable: true
  7821. });
  7822. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7823. get: function () {
  7824. return Engine._ALPHA_ONEONE;
  7825. },
  7826. enumerable: true,
  7827. configurable: true
  7828. });
  7829. Object.defineProperty(Engine, "ALPHA_ADD", {
  7830. get: function () {
  7831. return Engine._ALPHA_ADD;
  7832. },
  7833. enumerable: true,
  7834. configurable: true
  7835. });
  7836. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7837. get: function () {
  7838. return Engine._ALPHA_COMBINE;
  7839. },
  7840. enumerable: true,
  7841. configurable: true
  7842. });
  7843. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7844. get: function () {
  7845. return Engine._ALPHA_SUBTRACT;
  7846. },
  7847. enumerable: true,
  7848. configurable: true
  7849. });
  7850. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7851. get: function () {
  7852. return Engine._ALPHA_MULTIPLY;
  7853. },
  7854. enumerable: true,
  7855. configurable: true
  7856. });
  7857. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7858. get: function () {
  7859. return Engine._ALPHA_MAXIMIZED;
  7860. },
  7861. enumerable: true,
  7862. configurable: true
  7863. });
  7864. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7865. get: function () {
  7866. return Engine._ALPHA_PREMULTIPLIED;
  7867. },
  7868. enumerable: true,
  7869. configurable: true
  7870. });
  7871. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7872. get: function () {
  7873. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7874. },
  7875. enumerable: true,
  7876. configurable: true
  7877. });
  7878. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7879. get: function () {
  7880. return Engine._ALPHA_INTERPOLATE;
  7881. },
  7882. enumerable: true,
  7883. configurable: true
  7884. });
  7885. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7886. get: function () {
  7887. return Engine._ALPHA_SCREENMODE;
  7888. },
  7889. enumerable: true,
  7890. configurable: true
  7891. });
  7892. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7893. get: function () {
  7894. return Engine._DELAYLOADSTATE_NONE;
  7895. },
  7896. enumerable: true,
  7897. configurable: true
  7898. });
  7899. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7900. get: function () {
  7901. return Engine._DELAYLOADSTATE_LOADED;
  7902. },
  7903. enumerable: true,
  7904. configurable: true
  7905. });
  7906. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7907. get: function () {
  7908. return Engine._DELAYLOADSTATE_LOADING;
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7914. get: function () {
  7915. return Engine._DELAYLOADSTATE_NOTLOADED;
  7916. },
  7917. enumerable: true,
  7918. configurable: true
  7919. });
  7920. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7921. get: function () {
  7922. return Engine._TEXTUREFORMAT_ALPHA;
  7923. },
  7924. enumerable: true,
  7925. configurable: true
  7926. });
  7927. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7928. get: function () {
  7929. return Engine._TEXTUREFORMAT_LUMINANCE;
  7930. },
  7931. enumerable: true,
  7932. configurable: true
  7933. });
  7934. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7935. get: function () {
  7936. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7937. },
  7938. enumerable: true,
  7939. configurable: true
  7940. });
  7941. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7942. get: function () {
  7943. return Engine._TEXTUREFORMAT_RGB;
  7944. },
  7945. enumerable: true,
  7946. configurable: true
  7947. });
  7948. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7949. get: function () {
  7950. return Engine._TEXTUREFORMAT_RGBA;
  7951. },
  7952. enumerable: true,
  7953. configurable: true
  7954. });
  7955. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7956. get: function () {
  7957. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7958. },
  7959. enumerable: true,
  7960. configurable: true
  7961. });
  7962. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7963. get: function () {
  7964. return Engine._TEXTURETYPE_FLOAT;
  7965. },
  7966. enumerable: true,
  7967. configurable: true
  7968. });
  7969. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7970. get: function () {
  7971. return Engine._TEXTURETYPE_HALF_FLOAT;
  7972. },
  7973. enumerable: true,
  7974. configurable: true
  7975. });
  7976. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7977. get: function () {
  7978. return Engine._SCALEMODE_FLOOR;
  7979. },
  7980. enumerable: true,
  7981. configurable: true
  7982. });
  7983. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7984. get: function () {
  7985. return Engine._SCALEMODE_NEAREST;
  7986. },
  7987. enumerable: true,
  7988. configurable: true
  7989. });
  7990. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7991. get: function () {
  7992. return Engine._SCALEMODE_CEILING;
  7993. },
  7994. enumerable: true,
  7995. configurable: true
  7996. });
  7997. Object.defineProperty(Engine, "Version", {
  7998. get: function () {
  7999. return "3.1-alpha";
  8000. },
  8001. enumerable: true,
  8002. configurable: true
  8003. });
  8004. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8005. get: function () {
  8006. return this._webGLVersion < 2 || this.forcePOTTextures;
  8007. },
  8008. enumerable: true,
  8009. configurable: true
  8010. });
  8011. Object.defineProperty(Engine.prototype, "badOS", {
  8012. get: function () {
  8013. return this._badOS;
  8014. },
  8015. enumerable: true,
  8016. configurable: true
  8017. });
  8018. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8019. get: function () {
  8020. return this._badDesktopOS;
  8021. },
  8022. enumerable: true,
  8023. configurable: true
  8024. });
  8025. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8026. get: function () {
  8027. return this._performanceMonitor;
  8028. },
  8029. enumerable: true,
  8030. configurable: true
  8031. });
  8032. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8033. get: function () {
  8034. return this._texturesSupported;
  8035. },
  8036. enumerable: true,
  8037. configurable: true
  8038. });
  8039. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8040. get: function () {
  8041. return this._textureFormatInUse;
  8042. },
  8043. enumerable: true,
  8044. configurable: true
  8045. });
  8046. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8047. // Empty texture
  8048. get: function () {
  8049. if (!this._emptyTexture) {
  8050. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8051. }
  8052. return this._emptyTexture;
  8053. },
  8054. enumerable: true,
  8055. configurable: true
  8056. });
  8057. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8058. get: function () {
  8059. if (!this._emptyCubeTexture) {
  8060. var faceData = new Uint8Array(4);
  8061. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8062. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8063. }
  8064. return this._emptyCubeTexture;
  8065. },
  8066. enumerable: true,
  8067. configurable: true
  8068. });
  8069. Engine.prototype._rebuildInternalTextures = function () {
  8070. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8071. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8072. var internalTexture = currentState_1[_i];
  8073. internalTexture._rebuild();
  8074. }
  8075. };
  8076. Engine.prototype._rebuildEffects = function () {
  8077. for (var key in this._compiledEffects) {
  8078. var effect = this._compiledEffects[key];
  8079. effect._prepareEffect();
  8080. }
  8081. BABYLON.Effect.ResetCache();
  8082. };
  8083. Engine.prototype._rebuildBuffers = function () {
  8084. // Index / Vertex
  8085. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8086. var scene = _a[_i];
  8087. scene.resetCachedMaterial();
  8088. scene._rebuildGeometries();
  8089. scene._rebuildTextures();
  8090. }
  8091. // Uniforms
  8092. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8093. var uniformBuffer = _c[_b];
  8094. uniformBuffer._rebuild();
  8095. }
  8096. };
  8097. Engine.prototype._initGLContext = function () {
  8098. // Caps
  8099. this._caps = new EngineCapabilities();
  8100. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8101. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8102. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8103. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8104. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8105. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8106. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8107. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8108. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8109. // Infos
  8110. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8111. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8112. if (rendererInfo != null) {
  8113. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8114. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8115. }
  8116. if (!this._glVendor) {
  8117. this._glVendor = "Unknown vendor";
  8118. }
  8119. if (!this._glRenderer) {
  8120. this._glRenderer = "Unknown renderer";
  8121. }
  8122. // Constants
  8123. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8124. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8125. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8126. this._gl.DEPTH24_STENCIL8 = 35056;
  8127. // Extensions
  8128. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8129. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8130. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8131. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8132. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8133. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8134. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8135. 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');
  8136. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8137. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8138. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8139. this._caps.highPrecisionShaderSupported = true;
  8140. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8141. // Checks if some of the format renders first to allow the use of webgl inspector.
  8142. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8143. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8144. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8145. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8146. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8147. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8148. if (this._webGLVersion > 1) {
  8149. this._gl.HALF_FLOAT_OES = 0x140B;
  8150. }
  8151. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8152. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8153. // Vertex array object
  8154. if (this._webGLVersion > 1) {
  8155. this._caps.vertexArrayObject = true;
  8156. }
  8157. else {
  8158. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8159. if (vertexArrayObjectExtension != null) {
  8160. this._caps.vertexArrayObject = true;
  8161. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8162. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8163. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8164. }
  8165. else {
  8166. this._caps.vertexArrayObject = false;
  8167. }
  8168. }
  8169. // Instances count
  8170. if (this._webGLVersion > 1) {
  8171. this._caps.instancedArrays = true;
  8172. }
  8173. else {
  8174. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8175. if (instanceExtension != null) {
  8176. this._caps.instancedArrays = true;
  8177. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8178. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8179. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8180. }
  8181. else {
  8182. this._caps.instancedArrays = false;
  8183. }
  8184. }
  8185. // Intelligently add supported compressed formats in order to check for.
  8186. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8187. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8188. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8189. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8190. if (this._caps.astc)
  8191. this.texturesSupported.push('-astc.ktx');
  8192. if (this._caps.s3tc)
  8193. this.texturesSupported.push('-dxt.ktx');
  8194. if (this._caps.pvrtc)
  8195. this.texturesSupported.push('-pvrtc.ktx');
  8196. if (this._caps.etc2)
  8197. this.texturesSupported.push('-etc2.ktx');
  8198. if (this._caps.etc1)
  8199. this.texturesSupported.push('-etc1.ktx');
  8200. if (this._gl.getShaderPrecisionFormat) {
  8201. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8202. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8203. }
  8204. // Depth buffer
  8205. this.setDepthBuffer(true);
  8206. this.setDepthFunctionToLessOrEqual();
  8207. this.setDepthWrite(true);
  8208. };
  8209. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8210. get: function () {
  8211. return this._webGLVersion;
  8212. },
  8213. enumerable: true,
  8214. configurable: true
  8215. });
  8216. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8217. /**
  8218. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8219. */
  8220. get: function () {
  8221. return this._isStencilEnable;
  8222. },
  8223. enumerable: true,
  8224. configurable: true
  8225. });
  8226. Engine.prototype._prepareWorkingCanvas = function () {
  8227. if (this._workingCanvas) {
  8228. return;
  8229. }
  8230. this._workingCanvas = document.createElement("canvas");
  8231. this._workingContext = this._workingCanvas.getContext("2d");
  8232. };
  8233. Engine.prototype.resetTextureCache = function () {
  8234. for (var key in this._activeTexturesCache) {
  8235. this._activeTexturesCache[key] = null;
  8236. }
  8237. };
  8238. Engine.prototype.isDeterministicLockStep = function () {
  8239. return this._deterministicLockstep;
  8240. };
  8241. Engine.prototype.getLockstepMaxSteps = function () {
  8242. return this._lockstepMaxSteps;
  8243. };
  8244. Engine.prototype.getGlInfo = function () {
  8245. return {
  8246. vendor: this._glVendor,
  8247. renderer: this._glRenderer,
  8248. version: this._glVersion
  8249. };
  8250. };
  8251. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8252. if (useScreen === void 0) { useScreen = false; }
  8253. var viewport = camera.viewport;
  8254. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8255. };
  8256. Engine.prototype.getRenderWidth = function (useScreen) {
  8257. if (useScreen === void 0) { useScreen = false; }
  8258. if (!useScreen && this._currentRenderTarget) {
  8259. return this._currentRenderTarget.width;
  8260. }
  8261. return this._gl.drawingBufferWidth;
  8262. };
  8263. Engine.prototype.getRenderHeight = function (useScreen) {
  8264. if (useScreen === void 0) { useScreen = false; }
  8265. if (!useScreen && this._currentRenderTarget) {
  8266. return this._currentRenderTarget.height;
  8267. }
  8268. return this._gl.drawingBufferHeight;
  8269. };
  8270. Engine.prototype.getRenderingCanvas = function () {
  8271. return this._renderingCanvas;
  8272. };
  8273. Engine.prototype.getRenderingCanvasClientRect = function () {
  8274. return this._renderingCanvas.getBoundingClientRect();
  8275. };
  8276. Engine.prototype.setHardwareScalingLevel = function (level) {
  8277. this._hardwareScalingLevel = level;
  8278. this.resize();
  8279. };
  8280. Engine.prototype.getHardwareScalingLevel = function () {
  8281. return this._hardwareScalingLevel;
  8282. };
  8283. Engine.prototype.getLoadedTexturesCache = function () {
  8284. return this._internalTexturesCache;
  8285. };
  8286. Engine.prototype.getCaps = function () {
  8287. return this._caps;
  8288. };
  8289. Object.defineProperty(Engine.prototype, "drawCalls", {
  8290. /** The number of draw calls submitted last frame */
  8291. get: function () {
  8292. return this._drawCalls.current;
  8293. },
  8294. enumerable: true,
  8295. configurable: true
  8296. });
  8297. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8298. get: function () {
  8299. return this._drawCalls;
  8300. },
  8301. enumerable: true,
  8302. configurable: true
  8303. });
  8304. Engine.prototype.getDepthFunction = function () {
  8305. return this._depthCullingState.depthFunc;
  8306. };
  8307. Engine.prototype.setDepthFunction = function (depthFunc) {
  8308. this._depthCullingState.depthFunc = depthFunc;
  8309. };
  8310. Engine.prototype.setDepthFunctionToGreater = function () {
  8311. this._depthCullingState.depthFunc = this._gl.GREATER;
  8312. };
  8313. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8314. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8315. };
  8316. Engine.prototype.setDepthFunctionToLess = function () {
  8317. this._depthCullingState.depthFunc = this._gl.LESS;
  8318. };
  8319. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8320. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8321. };
  8322. Engine.prototype.getStencilBuffer = function () {
  8323. return this._stencilState.stencilTest;
  8324. };
  8325. Engine.prototype.setStencilBuffer = function (enable) {
  8326. this._stencilState.stencilTest = enable;
  8327. };
  8328. Engine.prototype.getStencilMask = function () {
  8329. return this._stencilState.stencilMask;
  8330. };
  8331. Engine.prototype.setStencilMask = function (mask) {
  8332. this._stencilState.stencilMask = mask;
  8333. };
  8334. Engine.prototype.getStencilFunction = function () {
  8335. return this._stencilState.stencilFunc;
  8336. };
  8337. Engine.prototype.getStencilFunctionReference = function () {
  8338. return this._stencilState.stencilFuncRef;
  8339. };
  8340. Engine.prototype.getStencilFunctionMask = function () {
  8341. return this._stencilState.stencilFuncMask;
  8342. };
  8343. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8344. this._stencilState.stencilFunc = stencilFunc;
  8345. };
  8346. Engine.prototype.setStencilFunctionReference = function (reference) {
  8347. this._stencilState.stencilFuncRef = reference;
  8348. };
  8349. Engine.prototype.setStencilFunctionMask = function (mask) {
  8350. this._stencilState.stencilFuncMask = mask;
  8351. };
  8352. Engine.prototype.getStencilOperationFail = function () {
  8353. return this._stencilState.stencilOpStencilFail;
  8354. };
  8355. Engine.prototype.getStencilOperationDepthFail = function () {
  8356. return this._stencilState.stencilOpDepthFail;
  8357. };
  8358. Engine.prototype.getStencilOperationPass = function () {
  8359. return this._stencilState.stencilOpStencilDepthPass;
  8360. };
  8361. Engine.prototype.setStencilOperationFail = function (operation) {
  8362. this._stencilState.stencilOpStencilFail = operation;
  8363. };
  8364. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8365. this._stencilState.stencilOpDepthFail = operation;
  8366. };
  8367. Engine.prototype.setStencilOperationPass = function (operation) {
  8368. this._stencilState.stencilOpStencilDepthPass = operation;
  8369. };
  8370. Engine.prototype.setDitheringState = function (value) {
  8371. if (value) {
  8372. this._gl.enable(this._gl.DITHER);
  8373. }
  8374. else {
  8375. this._gl.disable(this._gl.DITHER);
  8376. }
  8377. };
  8378. /**
  8379. * stop executing a render loop function and remove it from the execution array
  8380. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8381. */
  8382. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8383. if (!renderFunction) {
  8384. this._activeRenderLoops = [];
  8385. return;
  8386. }
  8387. var index = this._activeRenderLoops.indexOf(renderFunction);
  8388. if (index >= 0) {
  8389. this._activeRenderLoops.splice(index, 1);
  8390. }
  8391. };
  8392. Engine.prototype._renderLoop = function () {
  8393. if (this._contextWasLost) {
  8394. return;
  8395. }
  8396. var shouldRender = true;
  8397. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8398. shouldRender = false;
  8399. }
  8400. if (shouldRender) {
  8401. // Start new frame
  8402. this.beginFrame();
  8403. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8404. var renderFunction = this._activeRenderLoops[index];
  8405. renderFunction();
  8406. }
  8407. // Present
  8408. this.endFrame();
  8409. }
  8410. if (this._activeRenderLoops.length > 0) {
  8411. // Register new frame
  8412. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8413. }
  8414. else {
  8415. this._renderingQueueLaunched = false;
  8416. }
  8417. };
  8418. /**
  8419. * Register and execute a render loop. The engine can have more than one render function.
  8420. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8421. * @example
  8422. * engine.runRenderLoop(function () {
  8423. * scene.render()
  8424. * })
  8425. */
  8426. Engine.prototype.runRenderLoop = function (renderFunction) {
  8427. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8428. return;
  8429. }
  8430. this._activeRenderLoops.push(renderFunction);
  8431. if (!this._renderingQueueLaunched) {
  8432. this._renderingQueueLaunched = true;
  8433. this._bindedRenderFunction = this._renderLoop.bind(this);
  8434. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8435. }
  8436. };
  8437. /**
  8438. * Toggle full screen mode.
  8439. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8440. * @param {any} options - an options object to be sent to the requestFullscreen function
  8441. */
  8442. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8443. if (this.isFullscreen) {
  8444. BABYLON.Tools.ExitFullscreen();
  8445. }
  8446. else {
  8447. this._pointerLockRequested = requestPointerLock;
  8448. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8449. }
  8450. };
  8451. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8452. if (stencil === void 0) { stencil = false; }
  8453. this.applyStates();
  8454. var mode = 0;
  8455. if (backBuffer && color) {
  8456. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8457. mode |= this._gl.COLOR_BUFFER_BIT;
  8458. }
  8459. if (depth) {
  8460. this._gl.clearDepth(1.0);
  8461. mode |= this._gl.DEPTH_BUFFER_BIT;
  8462. }
  8463. if (stencil) {
  8464. this._gl.clearStencil(0);
  8465. mode |= this._gl.STENCIL_BUFFER_BIT;
  8466. }
  8467. this._gl.clear(mode);
  8468. };
  8469. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8470. var gl = this._gl;
  8471. // Save state
  8472. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8473. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8474. // Change state
  8475. gl.enable(gl.SCISSOR_TEST);
  8476. gl.scissor(x, y, width, height);
  8477. // Clear
  8478. this.clear(clearColor, true, true, true);
  8479. // Restore state
  8480. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8481. if (curScissor === true) {
  8482. gl.enable(gl.SCISSOR_TEST);
  8483. }
  8484. else {
  8485. gl.disable(gl.SCISSOR_TEST);
  8486. }
  8487. };
  8488. /**
  8489. * Set the WebGL's viewport
  8490. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8491. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8492. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8493. */
  8494. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8495. var width = requiredWidth || this.getRenderWidth();
  8496. var height = requiredHeight || this.getRenderHeight();
  8497. var x = viewport.x || 0;
  8498. var y = viewport.y || 0;
  8499. this._cachedViewport = viewport;
  8500. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8501. };
  8502. /**
  8503. * Directly set the WebGL Viewport
  8504. * The x, y, width & height are directly passed to the WebGL call
  8505. * @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.
  8506. */
  8507. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8508. var currentViewport = this._cachedViewport;
  8509. this._cachedViewport = null;
  8510. this._gl.viewport(x, y, width, height);
  8511. return currentViewport;
  8512. };
  8513. Engine.prototype.beginFrame = function () {
  8514. this._measureFps();
  8515. };
  8516. Engine.prototype.endFrame = function () {
  8517. //force a flush in case we are using a bad OS.
  8518. if (this._badOS) {
  8519. this.flushFramebuffer();
  8520. }
  8521. //submit frame to the vr device, if enabled
  8522. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8523. this._vrDisplayEnabled.submitFrame();
  8524. }
  8525. };
  8526. /**
  8527. * resize the view according to the canvas' size.
  8528. * @example
  8529. * window.addEventListener("resize", function () {
  8530. * engine.resize();
  8531. * });
  8532. */
  8533. Engine.prototype.resize = function () {
  8534. // We're not resizing the size of the canvas while in VR mode & presenting
  8535. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8536. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8537. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8538. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8539. }
  8540. };
  8541. /**
  8542. * force a specific size of the canvas
  8543. * @param {number} width - the new canvas' width
  8544. * @param {number} height - the new canvas' height
  8545. */
  8546. Engine.prototype.setSize = function (width, height) {
  8547. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8548. return;
  8549. }
  8550. this._renderingCanvas.width = width;
  8551. this._renderingCanvas.height = height;
  8552. for (var index = 0; index < this.scenes.length; index++) {
  8553. var scene = this.scenes[index];
  8554. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8555. var cam = scene.cameras[camIndex];
  8556. cam._currentRenderId = 0;
  8557. }
  8558. }
  8559. if (this.onResizeObservable.hasObservers) {
  8560. this.onResizeObservable.notifyObservers(this);
  8561. }
  8562. };
  8563. //WebVR functions
  8564. Engine.prototype.isVRDevicePresent = function (callback) {
  8565. this.getVRDevice(null, function (device) {
  8566. callback(device !== null);
  8567. });
  8568. };
  8569. Engine.prototype.getVRDevice = function (name, callback) {
  8570. if (!this.vrDisplaysPromise) {
  8571. callback(null);
  8572. return;
  8573. }
  8574. this.vrDisplaysPromise.then(function (devices) {
  8575. if (devices.length > 0) {
  8576. if (name) {
  8577. var found = devices.some(function (device) {
  8578. if (device.displayName === name) {
  8579. callback(device);
  8580. return true;
  8581. }
  8582. else {
  8583. return false;
  8584. }
  8585. });
  8586. if (!found) {
  8587. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8588. callback(devices[0]);
  8589. }
  8590. }
  8591. else {
  8592. //choose the first one
  8593. callback(devices[0]);
  8594. }
  8595. }
  8596. else {
  8597. BABYLON.Tools.Error("No WebVR devices found!");
  8598. callback(null);
  8599. }
  8600. });
  8601. };
  8602. Engine.prototype.initWebVR = function () {
  8603. if (!this.vrDisplaysPromise) {
  8604. this._getVRDisplays();
  8605. }
  8606. };
  8607. Engine.prototype.enableVR = function (vrDevice) {
  8608. this._vrDisplayEnabled = vrDevice;
  8609. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8610. };
  8611. Engine.prototype.disableVR = function () {
  8612. if (this._vrDisplayEnabled) {
  8613. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8614. }
  8615. };
  8616. Engine.prototype._getVRDisplays = function () {
  8617. var _this = this;
  8618. var getWebVRDevices = function (devices) {
  8619. var size = devices.length;
  8620. var i = 0;
  8621. _this._vrDisplays = devices.filter(function (device) {
  8622. return devices[i] instanceof VRDisplay;
  8623. });
  8624. return _this._vrDisplays;
  8625. };
  8626. //using a key due to typescript
  8627. if (navigator.getVRDisplays) {
  8628. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8629. }
  8630. };
  8631. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8632. if (this._currentRenderTarget) {
  8633. this.unBindFramebuffer(this._currentRenderTarget);
  8634. }
  8635. this._currentRenderTarget = texture;
  8636. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8637. var gl = this._gl;
  8638. if (texture.isCube) {
  8639. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8640. }
  8641. if (this._cachedViewport && !forceFullscreenViewport) {
  8642. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8643. }
  8644. else {
  8645. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8646. }
  8647. this.wipeCaches();
  8648. };
  8649. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8650. if (this._currentFramebuffer !== framebuffer) {
  8651. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8652. this._currentFramebuffer = framebuffer;
  8653. }
  8654. };
  8655. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8656. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8657. this._currentRenderTarget = null;
  8658. // If MSAA, we need to bitblt back to main texture
  8659. var gl = this._gl;
  8660. if (texture._MSAAFramebuffer) {
  8661. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8662. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8663. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8664. }
  8665. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8666. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8667. gl.generateMipmap(gl.TEXTURE_2D);
  8668. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8669. }
  8670. if (onBeforeUnbind) {
  8671. if (texture._MSAAFramebuffer) {
  8672. // Bind the correct framebuffer
  8673. this.bindUnboundFramebuffer(texture._framebuffer);
  8674. }
  8675. onBeforeUnbind();
  8676. }
  8677. this.bindUnboundFramebuffer(null);
  8678. };
  8679. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8680. if (texture.generateMipMaps) {
  8681. var gl = this._gl;
  8682. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8683. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8684. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8685. }
  8686. };
  8687. Engine.prototype.flushFramebuffer = function () {
  8688. this._gl.flush();
  8689. };
  8690. Engine.prototype.restoreDefaultFramebuffer = function () {
  8691. if (this._currentRenderTarget) {
  8692. this.unBindFramebuffer(this._currentRenderTarget);
  8693. }
  8694. else {
  8695. this.bindUnboundFramebuffer(null);
  8696. }
  8697. if (this._cachedViewport) {
  8698. this.setViewport(this._cachedViewport);
  8699. }
  8700. this.wipeCaches();
  8701. };
  8702. // UBOs
  8703. Engine.prototype.createUniformBuffer = function (elements) {
  8704. var ubo = this._gl.createBuffer();
  8705. this.bindUniformBuffer(ubo);
  8706. if (elements instanceof Float32Array) {
  8707. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8708. }
  8709. else {
  8710. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8711. }
  8712. this.bindUniformBuffer(null);
  8713. ubo.references = 1;
  8714. return ubo;
  8715. };
  8716. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8717. var ubo = this._gl.createBuffer();
  8718. this.bindUniformBuffer(ubo);
  8719. if (elements instanceof Float32Array) {
  8720. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8721. }
  8722. else {
  8723. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8724. }
  8725. this.bindUniformBuffer(null);
  8726. ubo.references = 1;
  8727. return ubo;
  8728. };
  8729. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8730. this.bindUniformBuffer(uniformBuffer);
  8731. if (offset === undefined) {
  8732. offset = 0;
  8733. }
  8734. if (count === undefined) {
  8735. if (elements instanceof Float32Array) {
  8736. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8737. }
  8738. else {
  8739. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8740. }
  8741. }
  8742. else {
  8743. if (elements instanceof Float32Array) {
  8744. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8745. }
  8746. else {
  8747. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8748. }
  8749. }
  8750. this.bindUniformBuffer(null);
  8751. };
  8752. // VBOs
  8753. Engine.prototype._resetVertexBufferBinding = function () {
  8754. this.bindArrayBuffer(null);
  8755. this._cachedVertexBuffers = null;
  8756. };
  8757. Engine.prototype.createVertexBuffer = function (vertices) {
  8758. var vbo = this._gl.createBuffer();
  8759. this.bindArrayBuffer(vbo);
  8760. if (vertices instanceof Float32Array) {
  8761. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8762. }
  8763. else {
  8764. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8765. }
  8766. this._resetVertexBufferBinding();
  8767. vbo.references = 1;
  8768. return vbo;
  8769. };
  8770. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8771. var vbo = this._gl.createBuffer();
  8772. this.bindArrayBuffer(vbo);
  8773. if (vertices instanceof Float32Array) {
  8774. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8775. }
  8776. else {
  8777. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8778. }
  8779. this._resetVertexBufferBinding();
  8780. vbo.references = 1;
  8781. return vbo;
  8782. };
  8783. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8784. this.bindArrayBuffer(vertexBuffer);
  8785. if (offset === undefined) {
  8786. offset = 0;
  8787. }
  8788. if (count === undefined) {
  8789. if (vertices instanceof Float32Array) {
  8790. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8791. }
  8792. else {
  8793. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8794. }
  8795. }
  8796. else {
  8797. if (vertices instanceof Float32Array) {
  8798. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8799. }
  8800. else {
  8801. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8802. }
  8803. }
  8804. this._resetVertexBufferBinding();
  8805. };
  8806. Engine.prototype._resetIndexBufferBinding = function () {
  8807. this.bindIndexBuffer(null);
  8808. this._cachedIndexBuffer = null;
  8809. };
  8810. Engine.prototype.createIndexBuffer = function (indices) {
  8811. var vbo = this._gl.createBuffer();
  8812. this.bindIndexBuffer(vbo);
  8813. // Check for 32 bits indices
  8814. var arrayBuffer;
  8815. var need32Bits = false;
  8816. if (indices instanceof Uint16Array) {
  8817. arrayBuffer = indices;
  8818. }
  8819. else {
  8820. //check 32 bit support
  8821. if (this._caps.uintIndices) {
  8822. if (indices instanceof Uint32Array) {
  8823. arrayBuffer = indices;
  8824. need32Bits = true;
  8825. }
  8826. else {
  8827. //number[] or Int32Array, check if 32 bit is necessary
  8828. for (var index = 0; index < indices.length; index++) {
  8829. if (indices[index] > 65535) {
  8830. need32Bits = true;
  8831. break;
  8832. }
  8833. }
  8834. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8835. }
  8836. }
  8837. else {
  8838. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8839. arrayBuffer = new Uint16Array(indices);
  8840. }
  8841. }
  8842. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8843. this._resetIndexBufferBinding();
  8844. vbo.references = 1;
  8845. vbo.is32Bits = need32Bits;
  8846. return vbo;
  8847. };
  8848. Engine.prototype.bindArrayBuffer = function (buffer) {
  8849. if (!this._vaoRecordInProgress) {
  8850. this._unbindVertexArrayObject();
  8851. }
  8852. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8853. };
  8854. Engine.prototype.bindUniformBuffer = function (buffer) {
  8855. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8856. };
  8857. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8858. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8859. };
  8860. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8861. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8862. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8863. };
  8864. ;
  8865. Engine.prototype.bindIndexBuffer = function (buffer) {
  8866. if (!this._vaoRecordInProgress) {
  8867. this._unbindVertexArrayObject();
  8868. }
  8869. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8870. };
  8871. Engine.prototype.bindBuffer = function (buffer, target) {
  8872. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8873. this._gl.bindBuffer(target, buffer);
  8874. this._currentBoundBuffer[target] = buffer;
  8875. }
  8876. };
  8877. Engine.prototype.updateArrayBuffer = function (data) {
  8878. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8879. };
  8880. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8881. var pointer = this._currentBufferPointers[indx];
  8882. var changed = false;
  8883. if (!pointer.active) {
  8884. changed = true;
  8885. pointer.active = true;
  8886. pointer.index = indx;
  8887. pointer.size = size;
  8888. pointer.type = type;
  8889. pointer.normalized = normalized;
  8890. pointer.stride = stride;
  8891. pointer.offset = offset;
  8892. pointer.buffer = buffer;
  8893. }
  8894. else {
  8895. if (pointer.buffer !== buffer) {
  8896. pointer.buffer = buffer;
  8897. changed = true;
  8898. }
  8899. if (pointer.size !== size) {
  8900. pointer.size = size;
  8901. changed = true;
  8902. }
  8903. if (pointer.type !== type) {
  8904. pointer.type = type;
  8905. changed = true;
  8906. }
  8907. if (pointer.normalized !== normalized) {
  8908. pointer.normalized = normalized;
  8909. changed = true;
  8910. }
  8911. if (pointer.stride !== stride) {
  8912. pointer.stride = stride;
  8913. changed = true;
  8914. }
  8915. if (pointer.offset !== offset) {
  8916. pointer.offset = offset;
  8917. changed = true;
  8918. }
  8919. }
  8920. if (changed || this._vaoRecordInProgress) {
  8921. this.bindArrayBuffer(buffer);
  8922. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8923. }
  8924. };
  8925. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8926. if (indexBuffer == null) {
  8927. return;
  8928. }
  8929. if (this._cachedIndexBuffer !== indexBuffer) {
  8930. this._cachedIndexBuffer = indexBuffer;
  8931. this.bindIndexBuffer(indexBuffer);
  8932. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8933. }
  8934. };
  8935. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8936. var attributes = effect.getAttributesNames();
  8937. if (!this._vaoRecordInProgress) {
  8938. this._unbindVertexArrayObject();
  8939. }
  8940. this.unbindAllAttributes();
  8941. for (var index = 0; index < attributes.length; index++) {
  8942. var order = effect.getAttributeLocation(index);
  8943. if (order >= 0) {
  8944. var vertexBuffer = vertexBuffers[attributes[index]];
  8945. if (!vertexBuffer) {
  8946. continue;
  8947. }
  8948. this._gl.enableVertexAttribArray(order);
  8949. if (!this._vaoRecordInProgress) {
  8950. this._vertexAttribArraysEnabled[order] = true;
  8951. }
  8952. var buffer = vertexBuffer.getBuffer();
  8953. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8954. if (vertexBuffer.getIsInstanced()) {
  8955. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8956. if (!this._vaoRecordInProgress) {
  8957. this._currentInstanceLocations.push(order);
  8958. this._currentInstanceBuffers.push(buffer);
  8959. }
  8960. }
  8961. }
  8962. }
  8963. };
  8964. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8965. var vao = this._gl.createVertexArray();
  8966. this._vaoRecordInProgress = true;
  8967. this._gl.bindVertexArray(vao);
  8968. this._mustWipeVertexAttributes = true;
  8969. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8970. this.bindIndexBuffer(indexBuffer);
  8971. this._vaoRecordInProgress = false;
  8972. this._gl.bindVertexArray(null);
  8973. return vao;
  8974. };
  8975. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8976. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8977. this._cachedVertexArrayObject = vertexArrayObject;
  8978. this._gl.bindVertexArray(vertexArrayObject);
  8979. this._cachedVertexBuffers = null;
  8980. this._cachedIndexBuffer = null;
  8981. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8982. this._mustWipeVertexAttributes = true;
  8983. }
  8984. };
  8985. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8986. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8987. this._cachedVertexBuffers = vertexBuffer;
  8988. this._cachedEffectForVertexBuffers = effect;
  8989. var attributesCount = effect.getAttributesCount();
  8990. this._unbindVertexArrayObject();
  8991. this.unbindAllAttributes();
  8992. var offset = 0;
  8993. for (var index = 0; index < attributesCount; index++) {
  8994. if (index < vertexDeclaration.length) {
  8995. var order = effect.getAttributeLocation(index);
  8996. if (order >= 0) {
  8997. this._gl.enableVertexAttribArray(order);
  8998. this._vertexAttribArraysEnabled[order] = true;
  8999. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9000. }
  9001. offset += vertexDeclaration[index] * 4;
  9002. }
  9003. }
  9004. }
  9005. this._bindIndexBufferWithCache(indexBuffer);
  9006. };
  9007. Engine.prototype._unbindVertexArrayObject = function () {
  9008. if (!this._cachedVertexArrayObject) {
  9009. return;
  9010. }
  9011. this._cachedVertexArrayObject = null;
  9012. this._gl.bindVertexArray(null);
  9013. };
  9014. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9015. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9016. this._cachedVertexBuffers = vertexBuffers;
  9017. this._cachedEffectForVertexBuffers = effect;
  9018. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9019. }
  9020. this._bindIndexBufferWithCache(indexBuffer);
  9021. };
  9022. Engine.prototype.unbindInstanceAttributes = function () {
  9023. var boundBuffer;
  9024. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9025. var instancesBuffer = this._currentInstanceBuffers[i];
  9026. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9027. boundBuffer = instancesBuffer;
  9028. this.bindArrayBuffer(instancesBuffer);
  9029. }
  9030. var offsetLocation = this._currentInstanceLocations[i];
  9031. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9032. }
  9033. this._currentInstanceBuffers.length = 0;
  9034. this._currentInstanceLocations.length = 0;
  9035. };
  9036. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9037. this._gl.deleteVertexArray(vao);
  9038. };
  9039. Engine.prototype._releaseBuffer = function (buffer) {
  9040. buffer.references--;
  9041. if (buffer.references === 0) {
  9042. this._gl.deleteBuffer(buffer);
  9043. return true;
  9044. }
  9045. return false;
  9046. };
  9047. Engine.prototype.createInstancesBuffer = function (capacity) {
  9048. var buffer = this._gl.createBuffer();
  9049. buffer.capacity = capacity;
  9050. this.bindArrayBuffer(buffer);
  9051. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9052. return buffer;
  9053. };
  9054. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9055. this._gl.deleteBuffer(buffer);
  9056. };
  9057. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9058. this.bindArrayBuffer(instancesBuffer);
  9059. if (data) {
  9060. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9061. }
  9062. if (offsetLocations[0].index !== undefined) {
  9063. var stride = 0;
  9064. for (var i = 0; i < offsetLocations.length; i++) {
  9065. var ai = offsetLocations[i];
  9066. stride += ai.attributeSize * 4;
  9067. }
  9068. for (var i = 0; i < offsetLocations.length; i++) {
  9069. var ai = offsetLocations[i];
  9070. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9071. this._gl.enableVertexAttribArray(ai.index);
  9072. this._vertexAttribArraysEnabled[ai.index] = true;
  9073. }
  9074. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9075. this._gl.vertexAttribDivisor(ai.index, 1);
  9076. this._currentInstanceLocations.push(ai.index);
  9077. this._currentInstanceBuffers.push(instancesBuffer);
  9078. }
  9079. }
  9080. else {
  9081. for (var index = 0; index < 4; index++) {
  9082. var offsetLocation = offsetLocations[index];
  9083. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9084. this._gl.enableVertexAttribArray(offsetLocation);
  9085. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9086. }
  9087. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9088. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9089. this._currentInstanceLocations.push(offsetLocation);
  9090. this._currentInstanceBuffers.push(instancesBuffer);
  9091. }
  9092. }
  9093. };
  9094. Engine.prototype.applyStates = function () {
  9095. this._depthCullingState.apply(this._gl);
  9096. this._stencilState.apply(this._gl);
  9097. this._alphaState.apply(this._gl);
  9098. };
  9099. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9100. // Apply states
  9101. this.applyStates();
  9102. this._drawCalls.addCount(1, false);
  9103. // Render
  9104. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9105. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9106. if (instancesCount) {
  9107. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9108. return;
  9109. }
  9110. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9111. };
  9112. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9113. // Apply states
  9114. this.applyStates();
  9115. this._drawCalls.addCount(1, false);
  9116. if (instancesCount) {
  9117. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9118. return;
  9119. }
  9120. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9121. };
  9122. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9123. // Apply states
  9124. this.applyStates();
  9125. this._drawCalls.addCount(1, false);
  9126. if (instancesCount) {
  9127. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9128. return;
  9129. }
  9130. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9131. };
  9132. // Shaders
  9133. Engine.prototype._releaseEffect = function (effect) {
  9134. if (this._compiledEffects[effect._key]) {
  9135. delete this._compiledEffects[effect._key];
  9136. if (effect.getProgram()) {
  9137. this._gl.deleteProgram(effect.getProgram());
  9138. }
  9139. }
  9140. };
  9141. /**
  9142. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9143. * @param samplers An array of string used to represent textures
  9144. */
  9145. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9146. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9147. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9148. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9149. if (this._compiledEffects[name]) {
  9150. var compiledEffect = this._compiledEffects[name];
  9151. if (onCompiled && compiledEffect.isReady()) {
  9152. onCompiled(compiledEffect);
  9153. }
  9154. return compiledEffect;
  9155. }
  9156. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9157. effect._key = name;
  9158. this._compiledEffects[name] = effect;
  9159. return effect;
  9160. };
  9161. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9162. if (uniformsNames === void 0) { uniformsNames = []; }
  9163. if (samplers === void 0) { samplers = []; }
  9164. if (defines === void 0) { defines = ""; }
  9165. return this.createEffect({
  9166. vertex: "particles",
  9167. fragmentElement: fragmentName
  9168. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9169. };
  9170. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9171. context = context || this._gl;
  9172. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9173. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9174. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9175. var shaderProgram = context.createProgram();
  9176. context.attachShader(shaderProgram, vertexShader);
  9177. context.attachShader(shaderProgram, fragmentShader);
  9178. context.linkProgram(shaderProgram);
  9179. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9180. if (!linked) {
  9181. context.validateProgram(shaderProgram);
  9182. var error = context.getProgramInfoLog(shaderProgram);
  9183. if (error) {
  9184. throw new Error(error);
  9185. }
  9186. }
  9187. context.deleteShader(vertexShader);
  9188. context.deleteShader(fragmentShader);
  9189. return shaderProgram;
  9190. };
  9191. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9192. var results = [];
  9193. for (var index = 0; index < uniformsNames.length; index++) {
  9194. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9195. }
  9196. return results;
  9197. };
  9198. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9199. var results = [];
  9200. for (var index = 0; index < attributesNames.length; index++) {
  9201. try {
  9202. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9203. }
  9204. catch (e) {
  9205. results.push(-1);
  9206. }
  9207. }
  9208. return results;
  9209. };
  9210. Engine.prototype.enableEffect = function (effect) {
  9211. // Use program
  9212. this.setProgram(effect.getProgram());
  9213. this._currentEffect = effect;
  9214. if (effect.onBind) {
  9215. effect.onBind(effect);
  9216. }
  9217. effect.onBindObservable.notifyObservers(effect);
  9218. };
  9219. Engine.prototype.setIntArray = function (uniform, array) {
  9220. if (!uniform)
  9221. return;
  9222. this._gl.uniform1iv(uniform, array);
  9223. };
  9224. Engine.prototype.setIntArray2 = function (uniform, array) {
  9225. if (!uniform || array.length % 2 !== 0)
  9226. return;
  9227. this._gl.uniform2iv(uniform, array);
  9228. };
  9229. Engine.prototype.setIntArray3 = function (uniform, array) {
  9230. if (!uniform || array.length % 3 !== 0)
  9231. return;
  9232. this._gl.uniform3iv(uniform, array);
  9233. };
  9234. Engine.prototype.setIntArray4 = function (uniform, array) {
  9235. if (!uniform || array.length % 4 !== 0)
  9236. return;
  9237. this._gl.uniform4iv(uniform, array);
  9238. };
  9239. Engine.prototype.setFloatArray = function (uniform, array) {
  9240. if (!uniform)
  9241. return;
  9242. this._gl.uniform1fv(uniform, array);
  9243. };
  9244. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9245. if (!uniform || array.length % 2 !== 0)
  9246. return;
  9247. this._gl.uniform2fv(uniform, array);
  9248. };
  9249. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9250. if (!uniform || array.length % 3 !== 0)
  9251. return;
  9252. this._gl.uniform3fv(uniform, array);
  9253. };
  9254. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9255. if (!uniform || array.length % 4 !== 0)
  9256. return;
  9257. this._gl.uniform4fv(uniform, array);
  9258. };
  9259. Engine.prototype.setArray = function (uniform, array) {
  9260. if (!uniform)
  9261. return;
  9262. this._gl.uniform1fv(uniform, array);
  9263. };
  9264. Engine.prototype.setArray2 = function (uniform, array) {
  9265. if (!uniform || array.length % 2 !== 0)
  9266. return;
  9267. this._gl.uniform2fv(uniform, array);
  9268. };
  9269. Engine.prototype.setArray3 = function (uniform, array) {
  9270. if (!uniform || array.length % 3 !== 0)
  9271. return;
  9272. this._gl.uniform3fv(uniform, array);
  9273. };
  9274. Engine.prototype.setArray4 = function (uniform, array) {
  9275. if (!uniform || array.length % 4 !== 0)
  9276. return;
  9277. this._gl.uniform4fv(uniform, array);
  9278. };
  9279. Engine.prototype.setMatrices = function (uniform, matrices) {
  9280. if (!uniform)
  9281. return;
  9282. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9283. };
  9284. Engine.prototype.setMatrix = function (uniform, matrix) {
  9285. if (!uniform)
  9286. return;
  9287. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9288. };
  9289. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9290. if (!uniform)
  9291. return;
  9292. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9293. };
  9294. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9295. if (!uniform)
  9296. return;
  9297. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9298. };
  9299. Engine.prototype.setFloat = function (uniform, value) {
  9300. if (!uniform)
  9301. return;
  9302. this._gl.uniform1f(uniform, value);
  9303. };
  9304. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9305. if (!uniform)
  9306. return;
  9307. this._gl.uniform2f(uniform, x, y);
  9308. };
  9309. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9310. if (!uniform)
  9311. return;
  9312. this._gl.uniform3f(uniform, x, y, z);
  9313. };
  9314. Engine.prototype.setBool = function (uniform, bool) {
  9315. if (!uniform)
  9316. return;
  9317. this._gl.uniform1i(uniform, bool);
  9318. };
  9319. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9320. if (!uniform)
  9321. return;
  9322. this._gl.uniform4f(uniform, x, y, z, w);
  9323. };
  9324. Engine.prototype.setColor3 = function (uniform, color3) {
  9325. if (!uniform)
  9326. return;
  9327. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9328. };
  9329. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9330. if (!uniform)
  9331. return;
  9332. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9333. };
  9334. // States
  9335. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9336. if (zOffset === void 0) { zOffset = 0; }
  9337. if (reverseSide === void 0) { reverseSide = false; }
  9338. // Culling
  9339. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9340. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9341. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9342. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9343. if (culling) {
  9344. this._depthCullingState.cullFace = cullFace;
  9345. this._depthCullingState.cull = true;
  9346. }
  9347. else {
  9348. this._depthCullingState.cull = false;
  9349. }
  9350. }
  9351. // Z offset
  9352. this.setZOffset(zOffset);
  9353. };
  9354. Engine.prototype.setZOffset = function (value) {
  9355. this._depthCullingState.zOffset = value;
  9356. };
  9357. Engine.prototype.getZOffset = function () {
  9358. return this._depthCullingState.zOffset;
  9359. };
  9360. Engine.prototype.setDepthBuffer = function (enable) {
  9361. this._depthCullingState.depthTest = enable;
  9362. };
  9363. Engine.prototype.getDepthWrite = function () {
  9364. return this._depthCullingState.depthMask;
  9365. };
  9366. Engine.prototype.setDepthWrite = function (enable) {
  9367. this._depthCullingState.depthMask = enable;
  9368. };
  9369. Engine.prototype.setColorWrite = function (enable) {
  9370. this._gl.colorMask(enable, enable, enable, enable);
  9371. };
  9372. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9373. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9374. };
  9375. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9376. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9377. if (this._alphaMode === mode) {
  9378. return;
  9379. }
  9380. switch (mode) {
  9381. case Engine.ALPHA_DISABLE:
  9382. this._alphaState.alphaBlend = false;
  9383. break;
  9384. case Engine.ALPHA_PREMULTIPLIED:
  9385. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9386. this._alphaState.alphaBlend = true;
  9387. break;
  9388. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9389. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9390. this._alphaState.alphaBlend = true;
  9391. break;
  9392. case Engine.ALPHA_COMBINE:
  9393. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9394. this._alphaState.alphaBlend = true;
  9395. break;
  9396. case Engine.ALPHA_ONEONE:
  9397. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9398. this._alphaState.alphaBlend = true;
  9399. break;
  9400. case Engine.ALPHA_ADD:
  9401. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9402. this._alphaState.alphaBlend = true;
  9403. break;
  9404. case Engine.ALPHA_SUBTRACT:
  9405. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9406. this._alphaState.alphaBlend = true;
  9407. break;
  9408. case Engine.ALPHA_MULTIPLY:
  9409. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9410. this._alphaState.alphaBlend = true;
  9411. break;
  9412. case Engine.ALPHA_MAXIMIZED:
  9413. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9414. this._alphaState.alphaBlend = true;
  9415. break;
  9416. case Engine.ALPHA_INTERPOLATE:
  9417. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9418. this._alphaState.alphaBlend = true;
  9419. break;
  9420. case Engine.ALPHA_SCREENMODE:
  9421. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9422. this._alphaState.alphaBlend = true;
  9423. break;
  9424. }
  9425. if (!noDepthWriteChange) {
  9426. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9427. }
  9428. this._alphaMode = mode;
  9429. };
  9430. Engine.prototype.getAlphaMode = function () {
  9431. return this._alphaMode;
  9432. };
  9433. Engine.prototype.setAlphaTesting = function (enable) {
  9434. this._alphaTest = enable;
  9435. };
  9436. Engine.prototype.getAlphaTesting = function () {
  9437. return !!this._alphaTest;
  9438. };
  9439. // Textures
  9440. Engine.prototype.wipeCaches = function (bruteForce) {
  9441. if (this.preventCacheWipeBetweenFrames) {
  9442. return;
  9443. }
  9444. this.resetTextureCache();
  9445. this._currentEffect = null;
  9446. // 6/8/2017: deltakosh: Should not be required anymore.
  9447. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9448. if (bruteForce) {
  9449. this._currentProgram = null;
  9450. this._stencilState.reset();
  9451. this._depthCullingState.reset();
  9452. this.setDepthFunctionToLessOrEqual();
  9453. this._alphaState.reset();
  9454. }
  9455. this._cachedVertexBuffers = null;
  9456. this._cachedIndexBuffer = null;
  9457. this._cachedEffectForVertexBuffers = null;
  9458. this._unbindVertexArrayObject();
  9459. this.bindIndexBuffer(null);
  9460. this.bindArrayBuffer(null);
  9461. };
  9462. /**
  9463. * Set the compressed texture format to use, based on the formats you have, and the formats
  9464. * supported by the hardware / browser.
  9465. *
  9466. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9467. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9468. * to API arguments needed to compressed textures. This puts the burden on the container
  9469. * generator to house the arcane code for determining these for current & future formats.
  9470. *
  9471. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9472. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9473. *
  9474. * Note: The result of this call is not taken into account when a texture is base64.
  9475. *
  9476. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9477. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9478. *
  9479. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9480. * @returns The extension selected.
  9481. */
  9482. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9483. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9484. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9485. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9486. return this._textureFormatInUse = this._texturesSupported[i];
  9487. }
  9488. }
  9489. }
  9490. // actively set format to nothing, to allow this to be called more than once
  9491. // and possibly fail the 2nd time
  9492. return this._textureFormatInUse = null;
  9493. };
  9494. Engine.prototype._createTexture = function () {
  9495. return this._gl.createTexture();
  9496. };
  9497. /**
  9498. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9499. * @param {string} urlArg- This contains one of the following:
  9500. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9501. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9502. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9503. *
  9504. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9505. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9506. * @param {Scene} scene- Needed for loading to the correct scene.
  9507. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9508. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9509. * @param {callback} onError- Optional callback to be called upon failure.
  9510. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9511. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9512. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9513. *
  9514. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9515. */
  9516. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9517. var _this = this;
  9518. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9519. if (onLoad === void 0) { onLoad = null; }
  9520. if (onError === void 0) { onError = null; }
  9521. if (buffer === void 0) { buffer = null; }
  9522. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9523. var fromData = url.substr(0, 5) === "data:";
  9524. var fromBlob = url.substr(0, 5) === "blob:";
  9525. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9526. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9527. // establish the file extension, if possible
  9528. var lastDot = url.lastIndexOf('.');
  9529. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9530. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9531. var isTGA = (extension === ".tga");
  9532. // determine if a ktx file should be substituted
  9533. var isKTX = false;
  9534. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9535. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9536. isKTX = true;
  9537. }
  9538. if (scene) {
  9539. scene._addPendingData(texture);
  9540. }
  9541. texture.url = url;
  9542. texture.generateMipMaps = !noMipmap;
  9543. texture.samplingMode = samplingMode;
  9544. texture.invertY = invertY;
  9545. if (!this._doNotHandleContextLost) {
  9546. // Keep a link to the buffer only if we plan to handle context lost
  9547. texture._buffer = buffer;
  9548. }
  9549. if (onLoad) {
  9550. texture.onLoadedObservable.add(onLoad);
  9551. }
  9552. if (!fallBack)
  9553. this._internalTexturesCache.push(texture);
  9554. var onerror = function () {
  9555. if (scene) {
  9556. scene._removePendingData(texture);
  9557. }
  9558. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9559. if (isKTX) {
  9560. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9561. }
  9562. else if (onError) {
  9563. onError();
  9564. }
  9565. };
  9566. var callback;
  9567. // processing for non-image formats
  9568. if (isKTX || isTGA || isDDS) {
  9569. if (isKTX) {
  9570. callback = function (data) {
  9571. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9572. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9573. ktx.uploadLevels(_this._gl, !noMipmap);
  9574. return false;
  9575. }, samplingMode);
  9576. };
  9577. }
  9578. else if (isTGA) {
  9579. callback = function (arrayBuffer) {
  9580. var data = new Uint8Array(arrayBuffer);
  9581. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9582. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9583. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9584. return false;
  9585. }, samplingMode);
  9586. };
  9587. }
  9588. else if (isDDS) {
  9589. callback = function (data) {
  9590. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9591. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9592. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9593. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9594. return false;
  9595. }, samplingMode);
  9596. };
  9597. }
  9598. if (!buffer) {
  9599. BABYLON.Tools.LoadFile(url, function (data) {
  9600. callback(data);
  9601. }, null, scene ? scene.database : null, true, onerror);
  9602. }
  9603. else {
  9604. callback(buffer);
  9605. }
  9606. // image format processing
  9607. }
  9608. else {
  9609. var onload = function (img) {
  9610. if (fromBlob && !_this._doNotHandleContextLost) {
  9611. // We need to store the image if we need to rebuild the texture
  9612. // in case of a webgl context lost
  9613. texture._buffer = img;
  9614. }
  9615. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9616. var gl = _this._gl;
  9617. var isPot = (img.width === potWidth && img.height === potHeight);
  9618. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9619. if (isPot) {
  9620. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9621. return false;
  9622. }
  9623. // Using shaders to rescale because canvas.drawImage is lossy
  9624. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9625. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9626. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9628. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9629. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9630. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9631. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9632. _this._releaseTexture(source);
  9633. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9634. continuationCallback();
  9635. });
  9636. return true;
  9637. }, samplingMode);
  9638. };
  9639. if (!fromData || isBase64)
  9640. if (buffer instanceof HTMLImageElement) {
  9641. onload(buffer);
  9642. }
  9643. else {
  9644. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9645. }
  9646. else if (buffer instanceof Array || typeof buffer === "string")
  9647. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9648. else
  9649. onload(buffer);
  9650. }
  9651. return texture;
  9652. };
  9653. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9654. var _this = this;
  9655. var rtt = this.createRenderTargetTexture({
  9656. width: destination.width,
  9657. height: destination.height,
  9658. }, {
  9659. generateMipMaps: false,
  9660. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9661. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9662. generateDepthBuffer: false,
  9663. generateStencilBuffer: false
  9664. });
  9665. if (!this._rescalePostProcess) {
  9666. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9667. }
  9668. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9669. _this._rescalePostProcess.onApply = function (effect) {
  9670. effect._bindTexture("textureSampler", source);
  9671. };
  9672. scene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9673. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9674. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9675. _this.unBindFramebuffer(rtt);
  9676. _this._releaseTexture(rtt);
  9677. if (onComplete) {
  9678. onComplete();
  9679. }
  9680. });
  9681. };
  9682. Engine.prototype._getInternalFormat = function (format) {
  9683. var internalFormat = this._gl.RGBA;
  9684. switch (format) {
  9685. case Engine.TEXTUREFORMAT_ALPHA:
  9686. internalFormat = this._gl.ALPHA;
  9687. break;
  9688. case Engine.TEXTUREFORMAT_LUMINANCE:
  9689. internalFormat = this._gl.LUMINANCE;
  9690. break;
  9691. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9692. internalFormat = this._gl.LUMINANCE_ALPHA;
  9693. break;
  9694. case Engine.TEXTUREFORMAT_RGB:
  9695. internalFormat = this._gl.RGB;
  9696. break;
  9697. case Engine.TEXTUREFORMAT_RGBA:
  9698. internalFormat = this._gl.RGBA;
  9699. break;
  9700. }
  9701. return internalFormat;
  9702. };
  9703. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9704. if (compression === void 0) { compression = null; }
  9705. var internalFormat = this._getInternalFormat(format);
  9706. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9707. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9708. if (texture.width % 4 !== 0) {
  9709. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9710. }
  9711. if (compression) {
  9712. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9713. }
  9714. else {
  9715. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9716. }
  9717. if (texture.generateMipMaps) {
  9718. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9719. }
  9720. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9721. this.resetTextureCache();
  9722. texture.isReady = true;
  9723. };
  9724. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9725. if (compression === void 0) { compression = null; }
  9726. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9727. texture.baseWidth = width;
  9728. texture.baseHeight = height;
  9729. texture.width = width;
  9730. texture.height = height;
  9731. this.updateRawTexture(texture, data, format, invertY, compression);
  9732. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9733. // Filters
  9734. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9735. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9736. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9737. if (generateMipMaps) {
  9738. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9739. }
  9740. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9741. texture.samplingMode = samplingMode;
  9742. this._internalTexturesCache.push(texture);
  9743. return texture;
  9744. };
  9745. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9746. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  9747. texture.baseWidth = width;
  9748. texture.baseHeight = height;
  9749. if (generateMipMaps) {
  9750. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9751. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9752. }
  9753. this.resetTextureCache();
  9754. texture.width = width;
  9755. texture.height = height;
  9756. texture.isReady = false;
  9757. texture.generateMipMaps = generateMipMaps;
  9758. texture.samplingMode = samplingMode;
  9759. this.updateTextureSamplingMode(samplingMode, texture);
  9760. this._internalTexturesCache.push(texture);
  9761. return texture;
  9762. };
  9763. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9764. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9765. if (texture.isCube) {
  9766. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9767. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9768. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9769. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9770. }
  9771. else {
  9772. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9773. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9774. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9775. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9776. }
  9777. texture.samplingMode = samplingMode;
  9778. };
  9779. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9780. if (premulAlpha === void 0) { premulAlpha = false; }
  9781. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9782. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9783. if (premulAlpha) {
  9784. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9785. }
  9786. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9787. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9788. if (texture.generateMipMaps) {
  9789. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9790. }
  9791. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9792. if (premulAlpha) {
  9793. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9794. }
  9795. this.resetTextureCache();
  9796. texture.isReady = true;
  9797. };
  9798. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9799. if (texture._isDisabled) {
  9800. return;
  9801. }
  9802. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9803. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9804. try {
  9805. // Testing video texture support
  9806. if (this._videoTextureSupported === undefined) {
  9807. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9808. if (this._gl.getError() !== 0) {
  9809. this._videoTextureSupported = false;
  9810. }
  9811. else {
  9812. this._videoTextureSupported = true;
  9813. }
  9814. }
  9815. // Copy video through the current working canvas if video texture is not supported
  9816. if (!this._videoTextureSupported) {
  9817. if (!texture._workingCanvas) {
  9818. texture._workingCanvas = document.createElement("canvas");
  9819. texture._workingContext = texture._workingCanvas.getContext("2d");
  9820. texture._workingCanvas.width = texture.width;
  9821. texture._workingCanvas.height = texture.height;
  9822. }
  9823. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  9824. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9825. }
  9826. else {
  9827. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9828. }
  9829. if (texture.generateMipMaps) {
  9830. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9831. }
  9832. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9833. this.resetTextureCache();
  9834. texture.isReady = true;
  9835. }
  9836. catch (ex) {
  9837. // Something unexpected
  9838. // Let's disable the texture
  9839. texture._isDisabled = true;
  9840. }
  9841. };
  9842. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9843. // old version had a "generateMipMaps" arg instead of options.
  9844. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9845. // in the same way, generateDepthBuffer is defaulted to true
  9846. var generateMipMaps = false;
  9847. var generateDepthBuffer = true;
  9848. var generateStencilBuffer = false;
  9849. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9850. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9851. if (options !== undefined) {
  9852. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9853. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9854. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9855. type = options.type === undefined ? type : options.type;
  9856. if (options.samplingMode !== undefined) {
  9857. samplingMode = options.samplingMode;
  9858. }
  9859. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9860. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9861. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9862. }
  9863. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9864. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9865. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9866. }
  9867. }
  9868. var gl = this._gl;
  9869. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  9870. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9871. var width = size.width || size;
  9872. var height = size.height || size;
  9873. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9874. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9875. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9876. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9877. }
  9878. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9879. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9880. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9881. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9882. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9883. // Create the framebuffer
  9884. var framebuffer = gl.createFramebuffer();
  9885. this.bindUnboundFramebuffer(framebuffer);
  9886. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9887. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9888. if (generateMipMaps) {
  9889. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9890. }
  9891. // Unbind
  9892. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9893. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9894. this.bindUnboundFramebuffer(null);
  9895. texture._framebuffer = framebuffer;
  9896. texture.baseWidth = width;
  9897. texture.baseHeight = height;
  9898. texture.width = width;
  9899. texture.height = height;
  9900. texture.isReady = true;
  9901. texture.samples = 1;
  9902. texture.generateMipMaps = generateMipMaps;
  9903. texture.samplingMode = samplingMode;
  9904. texture.type = type;
  9905. texture._generateDepthBuffer = generateDepthBuffer;
  9906. texture._generateStencilBuffer = generateStencilBuffer;
  9907. this.resetTextureCache();
  9908. this._internalTexturesCache.push(texture);
  9909. return texture;
  9910. };
  9911. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9912. var generateMipMaps = false;
  9913. var generateDepthBuffer = true;
  9914. var generateStencilBuffer = false;
  9915. var generateDepthTexture = false;
  9916. var textureCount = 1;
  9917. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9918. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9919. var types = [], samplingModes = [];
  9920. if (options !== undefined) {
  9921. generateMipMaps = options.generateMipMaps;
  9922. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9923. generateStencilBuffer = options.generateStencilBuffer;
  9924. generateDepthTexture = options.generateDepthTexture;
  9925. textureCount = options.textureCount || 1;
  9926. if (options.types) {
  9927. types = options.types;
  9928. }
  9929. if (options.samplingModes) {
  9930. samplingModes = options.samplingModes;
  9931. }
  9932. }
  9933. var gl = this._gl;
  9934. // Create the framebuffer
  9935. var framebuffer = gl.createFramebuffer();
  9936. this.bindUnboundFramebuffer(framebuffer);
  9937. var width = size.width || size;
  9938. var height = size.height || size;
  9939. var textures = [];
  9940. var attachments = [];
  9941. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9942. for (var i = 0; i < textureCount; i++) {
  9943. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9944. var type = types[i] || defaultType;
  9945. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9946. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9947. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9948. }
  9949. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9950. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9951. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9952. }
  9953. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9954. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9955. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9956. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9957. }
  9958. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  9959. var attachment = gl["COLOR_ATTACHMENT" + i];
  9960. textures.push(texture);
  9961. attachments.push(attachment);
  9962. gl.activeTexture(gl["TEXTURE" + i]);
  9963. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  9964. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9965. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9966. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9967. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9968. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9969. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9970. if (generateMipMaps) {
  9971. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9972. }
  9973. // Unbind
  9974. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9975. texture._framebuffer = framebuffer;
  9976. texture._depthStencilBuffer = depthStencilBuffer;
  9977. texture.baseWidth = width;
  9978. texture.baseHeight = height;
  9979. texture.width = width;
  9980. texture.height = height;
  9981. texture.isReady = true;
  9982. texture.samples = 1;
  9983. texture.generateMipMaps = generateMipMaps;
  9984. texture.samplingMode = samplingMode;
  9985. texture.type = type;
  9986. texture._generateDepthBuffer = generateDepthBuffer;
  9987. texture._generateStencilBuffer = generateStencilBuffer;
  9988. this._internalTexturesCache.push(texture);
  9989. }
  9990. if (generateDepthTexture) {
  9991. // Depth texture
  9992. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  9993. gl.activeTexture(gl.TEXTURE0);
  9994. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  9995. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9996. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9999. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10000. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10001. depthTexture._framebuffer = framebuffer;
  10002. depthTexture.baseWidth = width;
  10003. depthTexture.baseHeight = height;
  10004. depthTexture.width = width;
  10005. depthTexture.height = height;
  10006. depthTexture.isReady = true;
  10007. depthTexture.samples = 1;
  10008. depthTexture.generateMipMaps = generateMipMaps;
  10009. depthTexture.samplingMode = gl.NEAREST;
  10010. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10011. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10012. textures.push(depthTexture);
  10013. this._internalTexturesCache.push(depthTexture);
  10014. }
  10015. gl.drawBuffers(attachments);
  10016. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10017. this.bindUnboundFramebuffer(null);
  10018. this.resetTextureCache();
  10019. return textures;
  10020. };
  10021. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10022. if (samples === void 0) { samples = 1; }
  10023. var depthStencilBuffer = null;
  10024. var gl = this._gl;
  10025. // Create the depth/stencil buffer
  10026. if (generateStencilBuffer) {
  10027. depthStencilBuffer = gl.createRenderbuffer();
  10028. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10029. if (samples > 1) {
  10030. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10031. }
  10032. else {
  10033. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10034. }
  10035. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10036. }
  10037. else if (generateDepthBuffer) {
  10038. depthStencilBuffer = gl.createRenderbuffer();
  10039. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10040. if (samples > 1) {
  10041. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10042. }
  10043. else {
  10044. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10045. }
  10046. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10047. }
  10048. return depthStencilBuffer;
  10049. };
  10050. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10051. if (this.webGLVersion < 2) {
  10052. return 1;
  10053. }
  10054. if (texture.samples === samples) {
  10055. return samples;
  10056. }
  10057. var gl = this._gl;
  10058. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10059. // Dispose previous render buffers
  10060. if (texture._depthStencilBuffer) {
  10061. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10062. }
  10063. if (texture._MSAAFramebuffer) {
  10064. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10065. }
  10066. if (texture._MSAARenderBuffer) {
  10067. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10068. }
  10069. if (samples > 1) {
  10070. texture._MSAAFramebuffer = gl.createFramebuffer();
  10071. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10072. var colorRenderbuffer = gl.createRenderbuffer();
  10073. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10074. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10075. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10076. texture._MSAARenderBuffer = colorRenderbuffer;
  10077. }
  10078. else {
  10079. this.bindUnboundFramebuffer(texture._framebuffer);
  10080. }
  10081. texture.samples = samples;
  10082. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10083. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10084. this.bindUnboundFramebuffer(null);
  10085. return samples;
  10086. };
  10087. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10088. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10089. };
  10090. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10091. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10092. };
  10093. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10094. var gl = this._gl;
  10095. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10096. var generateMipMaps = true;
  10097. var generateDepthBuffer = true;
  10098. var generateStencilBuffer = false;
  10099. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10100. if (options !== undefined) {
  10101. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  10102. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10103. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10104. if (options.samplingMode !== undefined) {
  10105. samplingMode = options.samplingMode;
  10106. }
  10107. }
  10108. texture.isCube = true;
  10109. texture.generateMipMaps = generateMipMaps;
  10110. texture.samples = 1;
  10111. texture.samplingMode = samplingMode;
  10112. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10113. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10114. for (var face = 0; face < 6; face++) {
  10115. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10116. }
  10117. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10118. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10119. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10120. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10121. // Create the framebuffer
  10122. var framebuffer = gl.createFramebuffer();
  10123. this.bindUnboundFramebuffer(framebuffer);
  10124. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10125. // Mipmaps
  10126. if (texture.generateMipMaps) {
  10127. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10128. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10129. }
  10130. // Unbind
  10131. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10132. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10133. this.bindUnboundFramebuffer(null);
  10134. texture._framebuffer = framebuffer;
  10135. texture.width = size;
  10136. texture.height = size;
  10137. texture.isReady = true;
  10138. this.resetTextureCache();
  10139. this._internalTexturesCache.push(texture);
  10140. return texture;
  10141. };
  10142. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10143. var _this = this;
  10144. if (onError === void 0) { onError = null; }
  10145. if (forcedExtension === void 0) { forcedExtension = null; }
  10146. var callback = function (loadData) {
  10147. if (!loadData) {
  10148. if (onLoad) {
  10149. onLoad(null);
  10150. }
  10151. return;
  10152. }
  10153. var texture = loadData.texture;
  10154. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10155. texture._lodGenerationScale = scale;
  10156. texture._lodGenerationOffset = offset;
  10157. if (_this._caps.textureLOD) {
  10158. // Do not add extra process if texture lod is supported.
  10159. if (onLoad) {
  10160. onLoad(texture);
  10161. }
  10162. return;
  10163. }
  10164. var mipSlices = 3;
  10165. var gl = _this._gl;
  10166. var width = loadData.width;
  10167. if (!width) {
  10168. return;
  10169. }
  10170. var textures = [];
  10171. for (var i = 0; i < mipSlices; i++) {
  10172. //compute LOD from even spacing in smoothness (matching shader calculation)
  10173. var smoothness = i / (mipSlices - 1);
  10174. var roughness = 1 - smoothness;
  10175. var minLODIndex = offset; // roughness = 0
  10176. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10177. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10178. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10179. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10180. glTextureFromLod.isCube = true;
  10181. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10182. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10183. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10184. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10185. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10186. if (loadData.isDDS) {
  10187. var info = loadData.info;
  10188. var data = loadData.data;
  10189. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10190. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10191. }
  10192. else {
  10193. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10194. }
  10195. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10196. // Wrap in a base texture for easy binding.
  10197. var lodTexture = new BABYLON.BaseTexture(scene);
  10198. lodTexture.isCube = true;
  10199. lodTexture._texture = glTextureFromLod;
  10200. glTextureFromLod.isReady = true;
  10201. textures.push(lodTexture);
  10202. }
  10203. texture._lodTextureHigh = textures[2];
  10204. texture._lodTextureMid = textures[1];
  10205. texture._lodTextureLow = textures[0];
  10206. if (onLoad) {
  10207. onLoad(texture);
  10208. }
  10209. };
  10210. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10211. };
  10212. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10213. var _this = this;
  10214. if (onLoad === void 0) { onLoad = null; }
  10215. if (onError === void 0) { onError = null; }
  10216. if (forcedExtension === void 0) { forcedExtension = null; }
  10217. var gl = this._gl;
  10218. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10219. texture.isCube = true;
  10220. texture.url = rootUrl;
  10221. texture.generateMipMaps = !noMipmap;
  10222. if (!this._doNotHandleContextLost) {
  10223. texture._extension = forcedExtension;
  10224. texture._files = files;
  10225. }
  10226. var isKTX = false;
  10227. var isDDS = false;
  10228. var lastDot = rootUrl.lastIndexOf('.');
  10229. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10230. if (this._textureFormatInUse) {
  10231. extension = this._textureFormatInUse;
  10232. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10233. isKTX = true;
  10234. }
  10235. else {
  10236. isDDS = (extension === ".dds");
  10237. }
  10238. if (isKTX) {
  10239. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10240. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10241. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10242. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10243. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10244. ktx.uploadLevels(_this._gl, !noMipmap);
  10245. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10246. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10247. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10248. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10249. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10250. _this.resetTextureCache();
  10251. texture.width = ktx.pixelWidth;
  10252. texture.height = ktx.pixelHeight;
  10253. texture.isReady = true;
  10254. }, null, null, true, onError);
  10255. }
  10256. else if (isDDS) {
  10257. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10258. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10259. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10260. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10261. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10262. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10263. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10264. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10265. }
  10266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10268. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10269. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10270. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10271. _this.resetTextureCache();
  10272. texture.width = info.width;
  10273. texture.height = info.height;
  10274. texture.isReady = true;
  10275. texture.type = info.textureType;
  10276. if (onLoad) {
  10277. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10278. }
  10279. }, null, null, true, onError);
  10280. }
  10281. else {
  10282. cascadeLoad(rootUrl, scene, function (imgs) {
  10283. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10284. var height = width;
  10285. _this._prepareWorkingCanvas();
  10286. _this._workingCanvas.width = width;
  10287. _this._workingCanvas.height = height;
  10288. var faces = [
  10289. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10290. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10291. ];
  10292. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10293. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10294. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10295. for (var index = 0; index < faces.length; index++) {
  10296. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10297. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10298. }
  10299. if (!noMipmap) {
  10300. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10301. }
  10302. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10303. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10304. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10305. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10306. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10307. _this.resetTextureCache();
  10308. texture.width = width;
  10309. texture.height = height;
  10310. texture.isReady = true;
  10311. texture.format = format;
  10312. texture.onLoadedObservable.notifyObservers(texture);
  10313. texture.onLoadedObservable.clear();
  10314. if (onLoad) {
  10315. onLoad();
  10316. }
  10317. }, files, onError);
  10318. }
  10319. this._internalTexturesCache.push(texture);
  10320. return texture;
  10321. };
  10322. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10323. if (compression === void 0) { compression = null; }
  10324. if (level === void 0) { level = 0; }
  10325. var gl = this._gl;
  10326. var textureType = this._getWebGLTextureType(type);
  10327. var internalFormat = this._getInternalFormat(format);
  10328. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10329. var needConversion = false;
  10330. if (internalFormat === gl.RGB) {
  10331. internalFormat = gl.RGBA;
  10332. needConversion = true;
  10333. }
  10334. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10335. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10336. if (texture.width % 4 !== 0) {
  10337. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10338. }
  10339. // Data are known to be in +X +Y +Z -X -Y -Z
  10340. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10341. var faceData = data[faceIndex];
  10342. if (compression) {
  10343. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10344. }
  10345. else {
  10346. if (needConversion) {
  10347. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10348. }
  10349. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10350. }
  10351. }
  10352. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10353. if (isPot && texture.generateMipMaps && level === 0) {
  10354. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10355. }
  10356. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10357. this.resetTextureCache();
  10358. texture.isReady = true;
  10359. };
  10360. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10361. if (compression === void 0) { compression = null; }
  10362. var gl = this._gl;
  10363. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10364. texture.isCube = true;
  10365. texture.generateMipMaps = generateMipMaps;
  10366. texture.format = format;
  10367. texture.type = type;
  10368. var textureType = this._getWebGLTextureType(type);
  10369. var internalFormat = this._getInternalFormat(format);
  10370. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10371. var needConversion = false;
  10372. if (internalFormat === gl.RGB) {
  10373. internalFormat = gl.RGBA;
  10374. needConversion = true;
  10375. }
  10376. var width = size;
  10377. var height = width;
  10378. texture.width = width;
  10379. texture.height = height;
  10380. // Double check on POT to generate Mips.
  10381. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10382. if (!isPot) {
  10383. generateMipMaps = false;
  10384. }
  10385. // Upload data if needed. The texture won t be ready until then.
  10386. if (data) {
  10387. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10388. }
  10389. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10390. // Filters
  10391. if (data && generateMipMaps) {
  10392. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10393. }
  10394. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10395. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10396. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10397. }
  10398. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10399. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10400. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10401. }
  10402. else {
  10403. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10404. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10405. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10406. }
  10407. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10408. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10409. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10410. return texture;
  10411. };
  10412. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10413. var _this = this;
  10414. if (onLoad === void 0) { onLoad = null; }
  10415. if (onError === void 0) { onError = null; }
  10416. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10417. if (invertY === void 0) { invertY = false; }
  10418. var gl = this._gl;
  10419. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10420. scene._addPendingData(texture);
  10421. texture.url = url;
  10422. this._internalTexturesCache.push(texture);
  10423. var onerror = function () {
  10424. scene._removePendingData(texture);
  10425. if (onError) {
  10426. onError();
  10427. }
  10428. };
  10429. var internalCallback = function (data) {
  10430. var width = texture.width;
  10431. var height = texture.height;
  10432. var faceDataArrays = callback(data);
  10433. if (mipmmapGenerator) {
  10434. var textureType = _this._getWebGLTextureType(type);
  10435. var internalFormat = _this._getInternalFormat(format);
  10436. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10437. var needConversion = false;
  10438. if (internalFormat === gl.RGB) {
  10439. internalFormat = gl.RGBA;
  10440. needConversion = true;
  10441. }
  10442. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10443. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10444. var mipData = mipmmapGenerator(faceDataArrays);
  10445. for (var level = 0; level < mipData.length; level++) {
  10446. var mipSize = width >> level;
  10447. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10448. var mipFaceData = mipData[level][faceIndex];
  10449. if (needConversion) {
  10450. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10451. }
  10452. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10453. }
  10454. }
  10455. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10456. }
  10457. else {
  10458. texture.generateMipMaps = !noMipmap;
  10459. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10460. }
  10461. texture.isReady = true;
  10462. _this.resetTextureCache();
  10463. scene._removePendingData(texture);
  10464. if (onLoad) {
  10465. onLoad();
  10466. }
  10467. };
  10468. BABYLON.Tools.LoadFile(url, function (data) {
  10469. internalCallback(data);
  10470. }, onerror, scene.database, true);
  10471. return texture;
  10472. };
  10473. ;
  10474. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10475. var gl = this._gl;
  10476. if (!gl) {
  10477. return;
  10478. }
  10479. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10480. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10481. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10482. if (!noMipmap && !isCompressed) {
  10483. gl.generateMipmap(gl.TEXTURE_2D);
  10484. }
  10485. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10486. this.resetTextureCache();
  10487. if (scene) {
  10488. scene._removePendingData(texture);
  10489. }
  10490. texture.onLoadedObservable.notifyObservers(texture);
  10491. texture.onLoadedObservable.clear();
  10492. };
  10493. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10494. var _this = this;
  10495. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10496. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10497. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10498. var gl = this._gl;
  10499. if (!gl) {
  10500. return;
  10501. }
  10502. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10503. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10504. texture.baseWidth = width;
  10505. texture.baseHeight = height;
  10506. texture.width = potWidth;
  10507. texture.height = potHeight;
  10508. texture.isReady = true;
  10509. if (processFunction(potWidth, potHeight, function () {
  10510. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10511. })) {
  10512. // Returning as texture needs extra async steps
  10513. return;
  10514. }
  10515. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10516. };
  10517. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10518. // Create new RGBA data container.
  10519. var rgbaData;
  10520. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10521. rgbaData = new Float32Array(width * height * 4);
  10522. }
  10523. else {
  10524. rgbaData = new Uint32Array(width * height * 4);
  10525. }
  10526. // Convert each pixel.
  10527. for (var x = 0; x < width; x++) {
  10528. for (var y = 0; y < height; y++) {
  10529. var index = (y * width + x) * 3;
  10530. var newIndex = (y * width + x) * 4;
  10531. // Map Old Value to new value.
  10532. rgbaData[newIndex + 0] = rgbData[index + 0];
  10533. rgbaData[newIndex + 1] = rgbData[index + 1];
  10534. rgbaData[newIndex + 2] = rgbData[index + 2];
  10535. // Add fully opaque alpha channel.
  10536. rgbaData[newIndex + 3] = 1;
  10537. }
  10538. }
  10539. return rgbaData;
  10540. };
  10541. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10542. var gl = this._gl;
  10543. if (texture._framebuffer) {
  10544. gl.deleteFramebuffer(texture._framebuffer);
  10545. texture._framebuffer = null;
  10546. }
  10547. if (texture._depthStencilBuffer) {
  10548. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10549. texture._depthStencilBuffer = null;
  10550. }
  10551. if (texture._MSAAFramebuffer) {
  10552. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10553. texture._MSAAFramebuffer = null;
  10554. }
  10555. if (texture._MSAARenderBuffer) {
  10556. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10557. texture._MSAARenderBuffer = null;
  10558. }
  10559. };
  10560. Engine.prototype._releaseTexture = function (texture) {
  10561. var gl = this._gl;
  10562. this._releaseFramebufferObjects(texture);
  10563. gl.deleteTexture(texture._webGLTexture);
  10564. // Unbind channels
  10565. this.unbindAllTextures();
  10566. var index = this._internalTexturesCache.indexOf(texture);
  10567. if (index !== -1) {
  10568. this._internalTexturesCache.splice(index, 1);
  10569. }
  10570. // Integrated fixed lod samplers.
  10571. if (texture._lodTextureHigh) {
  10572. texture._lodTextureHigh.dispose();
  10573. }
  10574. if (texture._lodTextureMid) {
  10575. texture._lodTextureMid.dispose();
  10576. }
  10577. if (texture._lodTextureLow) {
  10578. texture._lodTextureLow.dispose();
  10579. }
  10580. };
  10581. Engine.prototype.setProgram = function (program) {
  10582. if (this._currentProgram !== program) {
  10583. this._gl.useProgram(program);
  10584. this._currentProgram = program;
  10585. }
  10586. };
  10587. Engine.prototype.bindSamplers = function (effect) {
  10588. this.setProgram(effect.getProgram());
  10589. var samplers = effect.getSamplers();
  10590. for (var index = 0; index < samplers.length; index++) {
  10591. var uniform = effect.getUniform(samplers[index]);
  10592. this._gl.uniform1i(uniform, index);
  10593. }
  10594. this._currentEffect = null;
  10595. };
  10596. Engine.prototype.activateTexture = function (texture) {
  10597. if (this._activeTexture !== texture) {
  10598. this._gl.activeTexture(texture);
  10599. this._activeTexture = texture;
  10600. }
  10601. };
  10602. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10603. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10604. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10605. this._activeTexturesCache[this._activeTexture] = texture;
  10606. }
  10607. };
  10608. Engine.prototype._bindTexture = function (channel, texture) {
  10609. if (channel < 0) {
  10610. return;
  10611. }
  10612. this.activateTexture(this._gl.TEXTURE0 + channel);
  10613. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10614. };
  10615. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10616. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10617. };
  10618. Engine.prototype.unbindAllTextures = function () {
  10619. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10620. this.activateTexture(this._gl["TEXTURE" + channel]);
  10621. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10622. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10623. }
  10624. };
  10625. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10626. if (channel < 0) {
  10627. return;
  10628. }
  10629. this._gl.uniform1i(uniform, channel);
  10630. this._setTexture(channel, texture);
  10631. };
  10632. Engine.prototype._setTexture = function (channel, texture) {
  10633. // Not ready?
  10634. if (!texture) {
  10635. if (this._activeTexturesCache[channel] != null) {
  10636. this.activateTexture(this._gl["TEXTURE" + channel]);
  10637. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10638. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10639. }
  10640. return;
  10641. }
  10642. // Video
  10643. var alreadyActivated = false;
  10644. if (texture.video) {
  10645. this.activateTexture(this._gl["TEXTURE" + channel]);
  10646. alreadyActivated = true;
  10647. texture.update();
  10648. }
  10649. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10650. texture.delayLoad();
  10651. return;
  10652. }
  10653. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10654. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10655. if (this._activeTexturesCache[channel] === internalTexture) {
  10656. return;
  10657. }
  10658. if (!alreadyActivated) {
  10659. this.activateTexture(this._gl["TEXTURE" + channel]);
  10660. }
  10661. if (internalTexture.isCube) {
  10662. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10663. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10664. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10665. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10666. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10667. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10668. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10669. }
  10670. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10671. }
  10672. else {
  10673. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10674. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10675. internalTexture._cachedWrapU = texture.wrapU;
  10676. switch (texture.wrapU) {
  10677. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10678. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10679. break;
  10680. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10681. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10682. break;
  10683. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10684. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10685. break;
  10686. }
  10687. }
  10688. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10689. internalTexture._cachedWrapV = texture.wrapV;
  10690. switch (texture.wrapV) {
  10691. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10692. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10693. break;
  10694. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10695. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10696. break;
  10697. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10698. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10699. break;
  10700. }
  10701. }
  10702. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10703. }
  10704. };
  10705. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10706. if (channel < 0) {
  10707. return;
  10708. }
  10709. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10710. this._textureUnits = new Int32Array(textures.length);
  10711. }
  10712. for (var i = 0; i < textures.length; i++) {
  10713. this._textureUnits[i] = channel + i;
  10714. }
  10715. this._gl.uniform1iv(uniform, this._textureUnits);
  10716. for (var index = 0; index < textures.length; index++) {
  10717. this._setTexture(channel + index, textures[index]);
  10718. }
  10719. };
  10720. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10721. var internalTexture = texture.getInternalTexture();
  10722. if (!internalTexture) {
  10723. return;
  10724. }
  10725. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10726. var value = texture.anisotropicFilteringLevel;
  10727. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10728. value = 1;
  10729. }
  10730. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10731. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10732. internalTexture._cachedAnisotropicFilteringLevel = value;
  10733. }
  10734. };
  10735. Engine.prototype.readPixels = function (x, y, width, height) {
  10736. var data = new Uint8Array(height * width * 4);
  10737. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10738. return data;
  10739. };
  10740. /**
  10741. * Add an externaly attached data from its key.
  10742. * This method call will fail and return false, if such key already exists.
  10743. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10744. * @param key the unique key that identifies the data
  10745. * @param data the data object to associate to the key for this Engine instance
  10746. * @return true if no such key were already present and the data was added successfully, false otherwise
  10747. */
  10748. Engine.prototype.addExternalData = function (key, data) {
  10749. if (!this._externalData) {
  10750. this._externalData = new BABYLON.StringDictionary();
  10751. }
  10752. return this._externalData.add(key, data);
  10753. };
  10754. /**
  10755. * Get an externaly attached data from its key
  10756. * @param key the unique key that identifies the data
  10757. * @return the associated data, if present (can be null), or undefined if not present
  10758. */
  10759. Engine.prototype.getExternalData = function (key) {
  10760. if (!this._externalData) {
  10761. this._externalData = new BABYLON.StringDictionary();
  10762. }
  10763. return this._externalData.get(key);
  10764. };
  10765. /**
  10766. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10767. * @param key the unique key that identifies the data
  10768. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10769. * @return the associated data, can be null if the factory returned null.
  10770. */
  10771. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10772. if (!this._externalData) {
  10773. this._externalData = new BABYLON.StringDictionary();
  10774. }
  10775. return this._externalData.getOrAddWithFactory(key, factory);
  10776. };
  10777. /**
  10778. * Remove an externaly attached data from the Engine instance
  10779. * @param key the unique key that identifies the data
  10780. * @return true if the data was successfully removed, false if it doesn't exist
  10781. */
  10782. Engine.prototype.removeExternalData = function (key) {
  10783. if (!this._externalData) {
  10784. this._externalData = new BABYLON.StringDictionary();
  10785. }
  10786. return this._externalData.remove(key);
  10787. };
  10788. Engine.prototype.unbindAllAttributes = function () {
  10789. if (this._mustWipeVertexAttributes) {
  10790. this._mustWipeVertexAttributes = false;
  10791. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10792. this._gl.disableVertexAttribArray(i);
  10793. this._vertexAttribArraysEnabled[i] = false;
  10794. this._currentBufferPointers[i].active = false;
  10795. }
  10796. return;
  10797. }
  10798. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10799. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10800. continue;
  10801. }
  10802. this._gl.disableVertexAttribArray(i);
  10803. this._vertexAttribArraysEnabled[i] = false;
  10804. this._currentBufferPointers[i].active = false;
  10805. }
  10806. };
  10807. Engine.prototype.releaseEffects = function () {
  10808. for (var name in this._compiledEffects) {
  10809. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10810. }
  10811. this._compiledEffects = {};
  10812. };
  10813. // Dispose
  10814. Engine.prototype.dispose = function () {
  10815. this.hideLoadingUI();
  10816. this.stopRenderLoop();
  10817. // Empty texture
  10818. if (this._emptyTexture) {
  10819. this._releaseTexture(this._emptyTexture);
  10820. this._emptyTexture = null;
  10821. }
  10822. if (this._emptyCubeTexture) {
  10823. this._releaseTexture(this._emptyCubeTexture);
  10824. this._emptyCubeTexture = null;
  10825. }
  10826. // Rescale PP
  10827. if (this._rescalePostProcess) {
  10828. this._rescalePostProcess.dispose();
  10829. }
  10830. // Release scenes
  10831. while (this.scenes.length) {
  10832. this.scenes[0].dispose();
  10833. }
  10834. // Release audio engine
  10835. if (Engine.audioEngine) {
  10836. Engine.audioEngine.dispose();
  10837. }
  10838. // Release effects
  10839. this.releaseEffects();
  10840. // Unbind
  10841. this.unbindAllAttributes();
  10842. if (this._dummyFramebuffer) {
  10843. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10844. }
  10845. this._gl = null;
  10846. //WebVR
  10847. this.disableVR();
  10848. // Events
  10849. window.removeEventListener("blur", this._onBlur);
  10850. window.removeEventListener("focus", this._onFocus);
  10851. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  10852. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  10853. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  10854. if (!this._doNotHandleContextLost) {
  10855. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  10856. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  10857. }
  10858. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10859. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10860. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10861. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10862. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10863. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10864. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10865. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10866. // Remove from Instances
  10867. var index = Engine.Instances.indexOf(this);
  10868. if (index >= 0) {
  10869. Engine.Instances.splice(index, 1);
  10870. }
  10871. this._workingCanvas = null;
  10872. this._workingContext = null;
  10873. this._currentBufferPointers = null;
  10874. this._renderingCanvas = null;
  10875. this._currentProgram = null;
  10876. this.onResizeObservable.clear();
  10877. this.onCanvasBlurObservable.clear();
  10878. BABYLON.Effect.ResetCache();
  10879. };
  10880. // Loading screen
  10881. Engine.prototype.displayLoadingUI = function () {
  10882. var loadingScreen = this.loadingScreen;
  10883. if (loadingScreen) {
  10884. loadingScreen.displayLoadingUI();
  10885. }
  10886. };
  10887. Engine.prototype.hideLoadingUI = function () {
  10888. var loadingScreen = this.loadingScreen;
  10889. if (loadingScreen) {
  10890. loadingScreen.hideLoadingUI();
  10891. }
  10892. };
  10893. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10894. get: function () {
  10895. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10896. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10897. return this._loadingScreen;
  10898. },
  10899. set: function (loadingScreen) {
  10900. this._loadingScreen = loadingScreen;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10906. set: function (text) {
  10907. this.loadingScreen.loadingUIText = text;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10913. set: function (color) {
  10914. this.loadingScreen.loadingUIBackgroundColor = color;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Engine.prototype.attachContextLostEvent = function (callback) {
  10920. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10921. };
  10922. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10923. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10924. };
  10925. Engine.prototype.getVertexShaderSource = function (program) {
  10926. var shaders = this._gl.getAttachedShaders(program);
  10927. return this._gl.getShaderSource(shaders[0]);
  10928. };
  10929. Engine.prototype.getFragmentShaderSource = function (program) {
  10930. var shaders = this._gl.getAttachedShaders(program);
  10931. return this._gl.getShaderSource(shaders[1]);
  10932. };
  10933. Engine.prototype.getError = function () {
  10934. return this._gl.getError();
  10935. };
  10936. // FPS
  10937. Engine.prototype.getFps = function () {
  10938. return this._fps;
  10939. };
  10940. Engine.prototype.getDeltaTime = function () {
  10941. return this._deltaTime;
  10942. };
  10943. Engine.prototype._measureFps = function () {
  10944. this._performanceMonitor.sampleFrame();
  10945. this._fps = this._performanceMonitor.averageFPS;
  10946. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  10947. };
  10948. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10949. if (faceIndex === void 0) { faceIndex = -1; }
  10950. var gl = this._gl;
  10951. if (!this._dummyFramebuffer) {
  10952. this._dummyFramebuffer = gl.createFramebuffer();
  10953. }
  10954. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10955. if (faceIndex > -1) {
  10956. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10957. }
  10958. else {
  10959. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10960. }
  10961. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10962. var buffer;
  10963. switch (readType) {
  10964. case gl.UNSIGNED_BYTE:
  10965. buffer = new Uint8Array(4 * width * height);
  10966. readType = gl.UNSIGNED_BYTE;
  10967. break;
  10968. default:
  10969. buffer = new Float32Array(4 * width * height);
  10970. readType = gl.FLOAT;
  10971. break;
  10972. }
  10973. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  10974. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  10975. return buffer;
  10976. };
  10977. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10978. if (this._webGLVersion > 1) {
  10979. return this._caps.colorBufferFloat;
  10980. }
  10981. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10982. };
  10983. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10984. if (this._webGLVersion > 1) {
  10985. return this._caps.colorBufferFloat;
  10986. }
  10987. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10988. };
  10989. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10990. Engine.prototype._canRenderToFramebuffer = function (type) {
  10991. var gl = this._gl;
  10992. //clear existing errors
  10993. while (gl.getError() !== gl.NO_ERROR) { }
  10994. var successful = true;
  10995. var texture = gl.createTexture();
  10996. gl.bindTexture(gl.TEXTURE_2D, texture);
  10997. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11000. var fb = gl.createFramebuffer();
  11001. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11002. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11003. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11004. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11005. successful = successful && (gl.getError() === gl.NO_ERROR);
  11006. //try render by clearing frame buffer's color buffer
  11007. if (successful) {
  11008. gl.clear(gl.COLOR_BUFFER_BIT);
  11009. successful = successful && (gl.getError() === gl.NO_ERROR);
  11010. }
  11011. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11012. if (successful) {
  11013. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11014. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11015. var readFormat = gl.RGBA;
  11016. var readType = gl.UNSIGNED_BYTE;
  11017. var buffer = new Uint8Array(4);
  11018. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11019. successful = successful && (gl.getError() === gl.NO_ERROR);
  11020. }
  11021. //clean up
  11022. gl.deleteTexture(texture);
  11023. gl.deleteFramebuffer(fb);
  11024. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11025. //clear accumulated errors
  11026. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11027. return successful;
  11028. };
  11029. Engine.prototype._getWebGLTextureType = function (type) {
  11030. if (type === Engine.TEXTURETYPE_FLOAT) {
  11031. return this._gl.FLOAT;
  11032. }
  11033. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11034. // Add Half Float Constant.
  11035. return this._gl.HALF_FLOAT_OES;
  11036. }
  11037. return this._gl.UNSIGNED_BYTE;
  11038. };
  11039. ;
  11040. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11041. if (this._webGLVersion === 1) {
  11042. return this._gl.RGBA;
  11043. }
  11044. if (type === Engine.TEXTURETYPE_FLOAT) {
  11045. return this._gl.RGBA32F;
  11046. }
  11047. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11048. return this._gl.RGBA16F;
  11049. }
  11050. return this._gl.RGBA;
  11051. };
  11052. ;
  11053. Engine.prototype.createQuery = function () {
  11054. return this._gl.createQuery();
  11055. };
  11056. Engine.prototype.deleteQuery = function (query) {
  11057. this.deleteQuery(query);
  11058. return this;
  11059. };
  11060. Engine.prototype.isQueryResultAvailable = function (query) {
  11061. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11062. };
  11063. Engine.prototype.getQueryResult = function (query) {
  11064. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11065. };
  11066. Engine.prototype.beginQuery = function (algorithmType, query) {
  11067. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11068. this._gl.beginQuery(glAlgorithm, query);
  11069. };
  11070. Engine.prototype.endQuery = function (algorithmType) {
  11071. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11072. this._gl.endQuery(glAlgorithm);
  11073. return this;
  11074. };
  11075. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11076. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11077. };
  11078. // Statics
  11079. Engine.isSupported = function () {
  11080. try {
  11081. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11082. if (navigator.isCocoonJS) {
  11083. return true;
  11084. }
  11085. var tempcanvas = document.createElement("canvas");
  11086. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11087. return gl != null && !!window.WebGLRenderingContext;
  11088. }
  11089. catch (e) {
  11090. return false;
  11091. }
  11092. };
  11093. Engine.Instances = new Array();
  11094. // Const statics
  11095. Engine._ALPHA_DISABLE = 0;
  11096. Engine._ALPHA_ADD = 1;
  11097. Engine._ALPHA_COMBINE = 2;
  11098. Engine._ALPHA_SUBTRACT = 3;
  11099. Engine._ALPHA_MULTIPLY = 4;
  11100. Engine._ALPHA_MAXIMIZED = 5;
  11101. Engine._ALPHA_ONEONE = 6;
  11102. Engine._ALPHA_PREMULTIPLIED = 7;
  11103. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11104. Engine._ALPHA_INTERPOLATE = 9;
  11105. Engine._ALPHA_SCREENMODE = 10;
  11106. Engine._DELAYLOADSTATE_NONE = 0;
  11107. Engine._DELAYLOADSTATE_LOADED = 1;
  11108. Engine._DELAYLOADSTATE_LOADING = 2;
  11109. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11110. Engine._TEXTUREFORMAT_ALPHA = 0;
  11111. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11112. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11113. Engine._TEXTUREFORMAT_RGB = 4;
  11114. Engine._TEXTUREFORMAT_RGBA = 5;
  11115. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11116. Engine._TEXTURETYPE_FLOAT = 1;
  11117. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11118. // Depht or Stencil test Constants.
  11119. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11120. 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.
  11121. 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.
  11122. 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.
  11123. 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.
  11124. 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.
  11125. 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.
  11126. 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.
  11127. // Stencil Actions Constants.
  11128. Engine._KEEP = 0x1E00;
  11129. Engine._REPLACE = 0x1E01;
  11130. Engine._INCR = 0x1E02;
  11131. Engine._DECR = 0x1E03;
  11132. Engine._INVERT = 0x150A;
  11133. Engine._INCR_WRAP = 0x8507;
  11134. Engine._DECR_WRAP = 0x8508;
  11135. // Texture rescaling mode
  11136. Engine._SCALEMODE_FLOOR = 1;
  11137. Engine._SCALEMODE_NEAREST = 2;
  11138. Engine._SCALEMODE_CEILING = 3;
  11139. // Updatable statics so stick with vars here
  11140. Engine.CollisionsEpsilon = 0.001;
  11141. Engine.CodeRepository = "src/";
  11142. Engine.ShadersRepository = "src/Shaders/";
  11143. return Engine;
  11144. }());
  11145. BABYLON.Engine = Engine;
  11146. })(BABYLON || (BABYLON = {}));
  11147. //# sourceMappingURL=babylon.engine.js.map
  11148. /// <reference path="Tools\babylon.decorators.ts" />
  11149. var BABYLON;
  11150. (function (BABYLON) {
  11151. /**
  11152. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11153. */
  11154. var Node = (function () {
  11155. /**
  11156. * @constructor
  11157. * @param {string} name - the name and id to be given to this node
  11158. * @param {BABYLON.Scene} the scene this node will be added to
  11159. */
  11160. function Node(name, scene) {
  11161. this.state = "";
  11162. this.metadata = null;
  11163. this.doNotSerialize = false;
  11164. this.animations = new Array();
  11165. this._ranges = {};
  11166. this._childrenFlag = -1;
  11167. this._isEnabled = true;
  11168. this._isReady = true;
  11169. this._currentRenderId = -1;
  11170. this._parentRenderId = -1;
  11171. /**
  11172. * An event triggered when the mesh is disposed.
  11173. * @type {BABYLON.Observable}
  11174. */
  11175. this.onDisposeObservable = new BABYLON.Observable();
  11176. // Behaviors
  11177. this._behaviors = new Array();
  11178. this.name = name;
  11179. this.id = name;
  11180. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11181. this._initCache();
  11182. }
  11183. Object.defineProperty(Node.prototype, "parent", {
  11184. get: function () {
  11185. return this._parentNode;
  11186. },
  11187. set: function (parent) {
  11188. if (this._parentNode === parent) {
  11189. return;
  11190. }
  11191. if (this._parentNode) {
  11192. var index = this._parentNode._children.indexOf(this);
  11193. if (index !== -1) {
  11194. this._parentNode._children.splice(index, 1);
  11195. }
  11196. }
  11197. this._parentNode = parent;
  11198. if (this._parentNode) {
  11199. if (!this._parentNode._children) {
  11200. this._parentNode._children = new Array();
  11201. }
  11202. this._parentNode._children.push(this);
  11203. }
  11204. },
  11205. enumerable: true,
  11206. configurable: true
  11207. });
  11208. Node.prototype.getClassName = function () {
  11209. return "Node";
  11210. };
  11211. Object.defineProperty(Node.prototype, "onDispose", {
  11212. set: function (callback) {
  11213. if (this._onDisposeObserver) {
  11214. this.onDisposeObservable.remove(this._onDisposeObserver);
  11215. }
  11216. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11217. },
  11218. enumerable: true,
  11219. configurable: true
  11220. });
  11221. Node.prototype.getScene = function () {
  11222. return this._scene;
  11223. };
  11224. Node.prototype.getEngine = function () {
  11225. return this._scene.getEngine();
  11226. };
  11227. Node.prototype.addBehavior = function (behavior) {
  11228. var index = this._behaviors.indexOf(behavior);
  11229. if (index !== -1) {
  11230. return;
  11231. }
  11232. behavior.attach(this);
  11233. this._behaviors.push(behavior);
  11234. return this;
  11235. };
  11236. Node.prototype.removeBehavior = function (behavior) {
  11237. var index = this._behaviors.indexOf(behavior);
  11238. if (index === -1) {
  11239. return;
  11240. }
  11241. this._behaviors[index].detach();
  11242. this._behaviors.splice(index, 1);
  11243. return this;
  11244. };
  11245. Object.defineProperty(Node.prototype, "behaviors", {
  11246. get: function () {
  11247. return this._behaviors;
  11248. },
  11249. enumerable: true,
  11250. configurable: true
  11251. });
  11252. Node.prototype.getBehaviorByName = function (name) {
  11253. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11254. var behavior = _a[_i];
  11255. if (behavior.name === name) {
  11256. return behavior;
  11257. }
  11258. }
  11259. return null;
  11260. };
  11261. // override it in derived class
  11262. Node.prototype.getWorldMatrix = function () {
  11263. return BABYLON.Matrix.Identity();
  11264. };
  11265. // override it in derived class if you add new variables to the cache
  11266. // and call the parent class method
  11267. Node.prototype._initCache = function () {
  11268. this._cache = {};
  11269. this._cache.parent = undefined;
  11270. };
  11271. Node.prototype.updateCache = function (force) {
  11272. if (!force && this.isSynchronized())
  11273. return;
  11274. this._cache.parent = this.parent;
  11275. this._updateCache();
  11276. };
  11277. // override it in derived class if you add new variables to the cache
  11278. // and call the parent class method if !ignoreParentClass
  11279. Node.prototype._updateCache = function (ignoreParentClass) {
  11280. };
  11281. // override it in derived class if you add new variables to the cache
  11282. Node.prototype._isSynchronized = function () {
  11283. return true;
  11284. };
  11285. Node.prototype._markSyncedWithParent = function () {
  11286. this._parentRenderId = this.parent._currentRenderId;
  11287. };
  11288. Node.prototype.isSynchronizedWithParent = function () {
  11289. if (!this.parent) {
  11290. return true;
  11291. }
  11292. if (this._parentRenderId !== this.parent._currentRenderId) {
  11293. return false;
  11294. }
  11295. return this.parent.isSynchronized();
  11296. };
  11297. Node.prototype.isSynchronized = function (updateCache) {
  11298. var check = this.hasNewParent();
  11299. check = check || !this.isSynchronizedWithParent();
  11300. check = check || !this._isSynchronized();
  11301. if (updateCache)
  11302. this.updateCache(true);
  11303. return !check;
  11304. };
  11305. Node.prototype.hasNewParent = function (update) {
  11306. if (this._cache.parent === this.parent)
  11307. return false;
  11308. if (update)
  11309. this._cache.parent = this.parent;
  11310. return true;
  11311. };
  11312. /**
  11313. * Is this node ready to be used/rendered
  11314. * @return {boolean} is it ready
  11315. */
  11316. Node.prototype.isReady = function () {
  11317. return this._isReady;
  11318. };
  11319. /**
  11320. * Is this node enabled.
  11321. * If the node has a parent and is enabled, the parent will be inspected as well.
  11322. * @return {boolean} whether this node (and its parent) is enabled.
  11323. * @see setEnabled
  11324. */
  11325. Node.prototype.isEnabled = function () {
  11326. if (!this._isEnabled) {
  11327. return false;
  11328. }
  11329. if (this.parent) {
  11330. return this.parent.isEnabled();
  11331. }
  11332. return true;
  11333. };
  11334. /**
  11335. * Set the enabled state of this node.
  11336. * @param {boolean} value - the new enabled state
  11337. * @see isEnabled
  11338. */
  11339. Node.prototype.setEnabled = function (value) {
  11340. this._isEnabled = value;
  11341. };
  11342. /**
  11343. * Is this node a descendant of the given node.
  11344. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11345. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11346. * @see parent
  11347. */
  11348. Node.prototype.isDescendantOf = function (ancestor) {
  11349. if (this.parent) {
  11350. if (this.parent === ancestor) {
  11351. return true;
  11352. }
  11353. return this.parent.isDescendantOf(ancestor);
  11354. }
  11355. return false;
  11356. };
  11357. /**
  11358. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11359. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11360. * @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.
  11361. * @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.
  11362. */
  11363. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11364. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11365. if (!this._children) {
  11366. return;
  11367. }
  11368. for (var index = 0; index < this._children.length; index++) {
  11369. var item = this._children[index];
  11370. if (!predicate || predicate(item)) {
  11371. results.push(item);
  11372. }
  11373. if (!directDescendantsOnly) {
  11374. item._getDescendants(results, false, predicate);
  11375. }
  11376. }
  11377. };
  11378. /**
  11379. * Will return all nodes that have this node as ascendant.
  11380. * @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.
  11381. * @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.
  11382. * @return {BABYLON.Node[]} all children nodes of all types.
  11383. */
  11384. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11385. var results = [];
  11386. this._getDescendants(results, directDescendantsOnly, predicate);
  11387. return results;
  11388. };
  11389. /**
  11390. * Get all child-meshes of this node.
  11391. */
  11392. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11393. var results = [];
  11394. this._getDescendants(results, directDecendantsOnly, function (node) {
  11395. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11396. });
  11397. return results;
  11398. };
  11399. /**
  11400. * Get all direct children of this node.
  11401. */
  11402. Node.prototype.getChildren = function (predicate) {
  11403. return this.getDescendants(true, predicate);
  11404. };
  11405. Node.prototype._setReady = function (state) {
  11406. if (state === this._isReady) {
  11407. return;
  11408. }
  11409. if (!state) {
  11410. this._isReady = false;
  11411. return;
  11412. }
  11413. this._isReady = true;
  11414. if (this.onReady) {
  11415. this.onReady(this);
  11416. }
  11417. };
  11418. Node.prototype.getAnimationByName = function (name) {
  11419. for (var i = 0; i < this.animations.length; i++) {
  11420. var animation = this.animations[i];
  11421. if (animation.name === name) {
  11422. return animation;
  11423. }
  11424. }
  11425. return null;
  11426. };
  11427. Node.prototype.createAnimationRange = function (name, from, to) {
  11428. // check name not already in use
  11429. if (!this._ranges[name]) {
  11430. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11431. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11432. if (this.animations[i]) {
  11433. this.animations[i].createRange(name, from, to);
  11434. }
  11435. }
  11436. }
  11437. };
  11438. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11439. if (deleteFrames === void 0) { deleteFrames = true; }
  11440. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11441. if (this.animations[i]) {
  11442. this.animations[i].deleteRange(name, deleteFrames);
  11443. }
  11444. }
  11445. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11446. };
  11447. Node.prototype.getAnimationRange = function (name) {
  11448. return this._ranges[name];
  11449. };
  11450. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11451. var range = this.getAnimationRange(name);
  11452. if (!range) {
  11453. return null;
  11454. }
  11455. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11456. };
  11457. Node.prototype.serializeAnimationRanges = function () {
  11458. var serializationRanges = [];
  11459. for (var name in this._ranges) {
  11460. var range = {};
  11461. range.name = name;
  11462. range.from = this._ranges[name].from;
  11463. range.to = this._ranges[name].to;
  11464. serializationRanges.push(range);
  11465. }
  11466. return serializationRanges;
  11467. };
  11468. Node.prototype.dispose = function () {
  11469. this.parent = null;
  11470. // Callback
  11471. this.onDisposeObservable.notifyObservers(this);
  11472. this.onDisposeObservable.clear();
  11473. // Behaviors
  11474. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11475. var behavior = _a[_i];
  11476. behavior.detach();
  11477. }
  11478. this._behaviors = [];
  11479. };
  11480. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11481. if (parsedNode.ranges) {
  11482. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11483. var data = parsedNode.ranges[index];
  11484. node.createAnimationRange(data.name, data.from, data.to);
  11485. }
  11486. }
  11487. };
  11488. __decorate([
  11489. BABYLON.serialize()
  11490. ], Node.prototype, "name", void 0);
  11491. __decorate([
  11492. BABYLON.serialize()
  11493. ], Node.prototype, "id", void 0);
  11494. __decorate([
  11495. BABYLON.serialize()
  11496. ], Node.prototype, "uniqueId", void 0);
  11497. __decorate([
  11498. BABYLON.serialize()
  11499. ], Node.prototype, "state", void 0);
  11500. __decorate([
  11501. BABYLON.serialize()
  11502. ], Node.prototype, "metadata", void 0);
  11503. return Node;
  11504. }());
  11505. BABYLON.Node = Node;
  11506. })(BABYLON || (BABYLON = {}));
  11507. //# sourceMappingURL=babylon.node.js.map
  11508. var BABYLON;
  11509. (function (BABYLON) {
  11510. var BoundingSphere = (function () {
  11511. function BoundingSphere(minimum, maximum) {
  11512. this.minimum = minimum;
  11513. this.maximum = maximum;
  11514. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11515. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11516. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11517. this.radius = distance * 0.5;
  11518. this.centerWorld = BABYLON.Vector3.Zero();
  11519. this._update(BABYLON.Matrix.Identity());
  11520. }
  11521. // Methods
  11522. BoundingSphere.prototype._update = function (world) {
  11523. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11524. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11525. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11526. };
  11527. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11528. for (var i = 0; i < 6; i++) {
  11529. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11530. return false;
  11531. }
  11532. return true;
  11533. };
  11534. BoundingSphere.prototype.intersectsPoint = function (point) {
  11535. var x = this.centerWorld.x - point.x;
  11536. var y = this.centerWorld.y - point.y;
  11537. var z = this.centerWorld.z - point.z;
  11538. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11539. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11540. return false;
  11541. return true;
  11542. };
  11543. // Statics
  11544. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11545. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11546. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11547. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11548. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11549. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11550. return false;
  11551. return true;
  11552. };
  11553. return BoundingSphere;
  11554. }());
  11555. BABYLON.BoundingSphere = BoundingSphere;
  11556. })(BABYLON || (BABYLON = {}));
  11557. //# sourceMappingURL=babylon.boundingSphere.js.map
  11558. var BABYLON;
  11559. (function (BABYLON) {
  11560. var BoundingBox = (function () {
  11561. function BoundingBox(minimum, maximum) {
  11562. this.minimum = minimum;
  11563. this.maximum = maximum;
  11564. this.vectors = new Array();
  11565. this.vectorsWorld = new Array();
  11566. // Bounding vectors
  11567. this.vectors.push(this.minimum.clone());
  11568. this.vectors.push(this.maximum.clone());
  11569. this.vectors.push(this.minimum.clone());
  11570. this.vectors[2].x = this.maximum.x;
  11571. this.vectors.push(this.minimum.clone());
  11572. this.vectors[3].y = this.maximum.y;
  11573. this.vectors.push(this.minimum.clone());
  11574. this.vectors[4].z = this.maximum.z;
  11575. this.vectors.push(this.maximum.clone());
  11576. this.vectors[5].z = this.minimum.z;
  11577. this.vectors.push(this.maximum.clone());
  11578. this.vectors[6].x = this.minimum.x;
  11579. this.vectors.push(this.maximum.clone());
  11580. this.vectors[7].y = this.minimum.y;
  11581. // OBB
  11582. this.center = this.maximum.add(this.minimum).scale(0.5);
  11583. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11584. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11585. // World
  11586. for (var index = 0; index < this.vectors.length; index++) {
  11587. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11588. }
  11589. this.minimumWorld = BABYLON.Vector3.Zero();
  11590. this.maximumWorld = BABYLON.Vector3.Zero();
  11591. this.centerWorld = BABYLON.Vector3.Zero();
  11592. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11593. this._update(BABYLON.Matrix.Identity());
  11594. }
  11595. // Methods
  11596. BoundingBox.prototype.getWorldMatrix = function () {
  11597. return this._worldMatrix;
  11598. };
  11599. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11600. this._worldMatrix.copyFrom(matrix);
  11601. return this;
  11602. };
  11603. BoundingBox.prototype._update = function (world) {
  11604. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11605. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11606. for (var index = 0; index < this.vectors.length; index++) {
  11607. var v = this.vectorsWorld[index];
  11608. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11609. if (v.x < this.minimumWorld.x)
  11610. this.minimumWorld.x = v.x;
  11611. if (v.y < this.minimumWorld.y)
  11612. this.minimumWorld.y = v.y;
  11613. if (v.z < this.minimumWorld.z)
  11614. this.minimumWorld.z = v.z;
  11615. if (v.x > this.maximumWorld.x)
  11616. this.maximumWorld.x = v.x;
  11617. if (v.y > this.maximumWorld.y)
  11618. this.maximumWorld.y = v.y;
  11619. if (v.z > this.maximumWorld.z)
  11620. this.maximumWorld.z = v.z;
  11621. }
  11622. // Extend
  11623. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11624. this.extendSizeWorld.scaleInPlace(0.5);
  11625. // OBB
  11626. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11627. this.centerWorld.scaleInPlace(0.5);
  11628. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11629. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11630. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11631. this._worldMatrix = world;
  11632. };
  11633. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11634. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11635. };
  11636. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11637. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11638. };
  11639. BoundingBox.prototype.intersectsPoint = function (point) {
  11640. var delta = -BABYLON.Epsilon;
  11641. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11642. return false;
  11643. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11644. return false;
  11645. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11646. return false;
  11647. return true;
  11648. };
  11649. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11650. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11651. };
  11652. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11653. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11654. return false;
  11655. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11656. return false;
  11657. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11658. return false;
  11659. return true;
  11660. };
  11661. // Statics
  11662. BoundingBox.Intersects = function (box0, box1) {
  11663. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11664. return false;
  11665. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11666. return false;
  11667. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11668. return false;
  11669. return true;
  11670. };
  11671. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11672. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11673. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11674. return (num <= (sphereRadius * sphereRadius));
  11675. };
  11676. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11677. for (var p = 0; p < 6; p++) {
  11678. for (var i = 0; i < 8; i++) {
  11679. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11680. return false;
  11681. }
  11682. }
  11683. }
  11684. return true;
  11685. };
  11686. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11687. for (var p = 0; p < 6; p++) {
  11688. var inCount = 8;
  11689. for (var i = 0; i < 8; i++) {
  11690. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11691. --inCount;
  11692. }
  11693. else {
  11694. break;
  11695. }
  11696. }
  11697. if (inCount === 0)
  11698. return false;
  11699. }
  11700. return true;
  11701. };
  11702. return BoundingBox;
  11703. }());
  11704. BABYLON.BoundingBox = BoundingBox;
  11705. })(BABYLON || (BABYLON = {}));
  11706. //# sourceMappingURL=babylon.boundingBox.js.map
  11707. var BABYLON;
  11708. (function (BABYLON) {
  11709. var computeBoxExtents = function (axis, box) {
  11710. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11711. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11712. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11713. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11714. var r = r0 + r1 + r2;
  11715. return {
  11716. min: p - r,
  11717. max: p + r
  11718. };
  11719. };
  11720. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11721. var axisOverlap = function (axis, box0, box1) {
  11722. var result0 = computeBoxExtents(axis, box0);
  11723. var result1 = computeBoxExtents(axis, box1);
  11724. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11725. };
  11726. var BoundingInfo = (function () {
  11727. function BoundingInfo(minimum, maximum) {
  11728. this.minimum = minimum;
  11729. this.maximum = maximum;
  11730. this._isLocked = false;
  11731. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11732. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11733. }
  11734. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11735. get: function () {
  11736. return this._isLocked;
  11737. },
  11738. set: function (value) {
  11739. this._isLocked = value;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. // Methods
  11745. BoundingInfo.prototype.update = function (world) {
  11746. if (this._isLocked) {
  11747. return;
  11748. }
  11749. this.boundingBox._update(world);
  11750. this.boundingSphere._update(world);
  11751. };
  11752. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11753. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11754. return false;
  11755. return this.boundingBox.isInFrustum(frustumPlanes);
  11756. };
  11757. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  11758. /**
  11759. * Gets the world distance between the min and max points of the bounding box
  11760. */
  11761. get: function () {
  11762. var boundingBox = this.boundingBox;
  11763. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  11764. return size.length();
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11770. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11771. };
  11772. BoundingInfo.prototype._checkCollision = function (collider) {
  11773. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11774. };
  11775. BoundingInfo.prototype.intersectsPoint = function (point) {
  11776. if (!this.boundingSphere.centerWorld) {
  11777. return false;
  11778. }
  11779. if (!this.boundingSphere.intersectsPoint(point)) {
  11780. return false;
  11781. }
  11782. if (!this.boundingBox.intersectsPoint(point)) {
  11783. return false;
  11784. }
  11785. return true;
  11786. };
  11787. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11788. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11789. return false;
  11790. }
  11791. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11792. return false;
  11793. }
  11794. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11795. return false;
  11796. }
  11797. if (!precise) {
  11798. return true;
  11799. }
  11800. var box0 = this.boundingBox;
  11801. var box1 = boundingInfo.boundingBox;
  11802. if (!axisOverlap(box0.directions[0], box0, box1))
  11803. return false;
  11804. if (!axisOverlap(box0.directions[1], box0, box1))
  11805. return false;
  11806. if (!axisOverlap(box0.directions[2], box0, box1))
  11807. return false;
  11808. if (!axisOverlap(box1.directions[0], box0, box1))
  11809. return false;
  11810. if (!axisOverlap(box1.directions[1], box0, box1))
  11811. return false;
  11812. if (!axisOverlap(box1.directions[2], box0, box1))
  11813. return false;
  11814. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11815. return false;
  11816. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11817. return false;
  11818. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11819. return false;
  11820. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11821. return false;
  11822. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11823. return false;
  11824. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11825. return false;
  11826. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11827. return false;
  11828. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11829. return false;
  11830. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11831. return false;
  11832. return true;
  11833. };
  11834. return BoundingInfo;
  11835. }());
  11836. BABYLON.BoundingInfo = BoundingInfo;
  11837. })(BABYLON || (BABYLON = {}));
  11838. //# sourceMappingURL=babylon.boundingInfo.js.map
  11839. var BABYLON;
  11840. (function (BABYLON) {
  11841. var AbstractMesh = (function (_super) {
  11842. __extends(AbstractMesh, _super);
  11843. // Constructor
  11844. function AbstractMesh(name, scene) {
  11845. var _this = _super.call(this, name, scene) || this;
  11846. _this._facetNb = 0; // facet number
  11847. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11848. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11849. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11850. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11851. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11852. _this._subDiv = {
  11853. max: 1,
  11854. X: 1,
  11855. Y: 1,
  11856. Z: 1
  11857. };
  11858. // Events
  11859. /**
  11860. * An event triggered when this mesh collides with another one
  11861. * @type {BABYLON.Observable}
  11862. */
  11863. _this.onCollideObservable = new BABYLON.Observable();
  11864. /**
  11865. * An event triggered when the collision's position changes
  11866. * @type {BABYLON.Observable}
  11867. */
  11868. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11869. /**
  11870. * An event triggered after the world matrix is updated
  11871. * @type {BABYLON.Observable}
  11872. */
  11873. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11874. /**
  11875. * An event triggered when material is changed
  11876. * @type {BABYLON.Observable}
  11877. */
  11878. _this.onMaterialChangedObservable = new BABYLON.Observable();
  11879. // Properties
  11880. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11881. _this.position = BABYLON.Vector3.Zero();
  11882. /**
  11883. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  11884. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  11885. * or
  11886. * 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.
  11887. * for more info check WebGl documentations
  11888. */
  11889. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  11890. /**
  11891. * 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:
  11892. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  11893. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  11894. * 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.
  11895. */
  11896. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  11897. /**
  11898. * 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.
  11899. * The default value is -1 which means don't break the query and wait till the result.
  11900. */
  11901. _this.occlusionRetryCount = -1;
  11902. _this._occlusionInternalRetryCounter = 0;
  11903. _this._isOccluded = false;
  11904. _this._isOcclusionQueryInProgress = false;
  11905. _this._rotation = BABYLON.Vector3.Zero();
  11906. _this._scaling = BABYLON.Vector3.One();
  11907. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11908. _this.visibility = 1.0;
  11909. _this.alphaIndex = Number.MAX_VALUE;
  11910. _this.infiniteDistance = false;
  11911. _this.isVisible = true;
  11912. _this.isPickable = true;
  11913. _this.showBoundingBox = false;
  11914. _this.showSubMeshesBoundingBox = false;
  11915. _this.isBlocker = false;
  11916. _this.enablePointerMoveEvents = false;
  11917. _this.renderingGroupId = 0;
  11918. _this._receiveShadows = false;
  11919. _this.renderOutline = false;
  11920. _this.outlineColor = BABYLON.Color3.Red();
  11921. _this.outlineWidth = 0.02;
  11922. _this.renderOverlay = false;
  11923. _this.overlayColor = BABYLON.Color3.Red();
  11924. _this.overlayAlpha = 0.5;
  11925. _this._hasVertexAlpha = false;
  11926. _this._useVertexColors = true;
  11927. _this._computeBonesUsingShaders = true;
  11928. _this._numBoneInfluencers = 4;
  11929. _this._applyFog = true;
  11930. _this.scalingDeterminant = 1;
  11931. _this.useOctreeForRenderingSelection = true;
  11932. _this.useOctreeForPicking = true;
  11933. _this.useOctreeForCollisions = true;
  11934. _this._layerMask = 0x0FFFFFFF;
  11935. /**
  11936. * True if the mesh must be rendered in any case.
  11937. */
  11938. _this.alwaysSelectAsActiveMesh = false;
  11939. // Collisions
  11940. _this._checkCollisions = false;
  11941. _this._collisionMask = -1;
  11942. _this._collisionGroup = -1;
  11943. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11944. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11945. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11946. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11947. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11948. // Edges
  11949. _this.edgesWidth = 1;
  11950. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11951. // Cache
  11952. _this._localWorld = BABYLON.Matrix.Zero();
  11953. _this._worldMatrix = BABYLON.Matrix.Zero();
  11954. _this._absolutePosition = BABYLON.Vector3.Zero();
  11955. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11956. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11957. _this._isDirty = false;
  11958. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11959. _this._isDisposed = false;
  11960. _this._renderId = 0;
  11961. _this._intersectionsInProgress = new Array();
  11962. _this._isWorldMatrixFrozen = false;
  11963. _this._unIndexed = false;
  11964. _this._lightSources = new Array();
  11965. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11966. if (collidedMesh === void 0) { collidedMesh = null; }
  11967. //TODO move this to the collision coordinator!
  11968. if (_this.getScene().workerCollisions)
  11969. newPosition.multiplyInPlace(_this._collider.radius);
  11970. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11971. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11972. _this.position.addInPlace(_this._diffPositionForCollisions);
  11973. }
  11974. if (collidedMesh) {
  11975. _this.onCollideObservable.notifyObservers(collidedMesh);
  11976. }
  11977. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11978. };
  11979. _this.getScene().addMesh(_this);
  11980. _this._resyncLightSources();
  11981. return _this;
  11982. }
  11983. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11984. get: function () {
  11985. return AbstractMesh._BILLBOARDMODE_NONE;
  11986. },
  11987. enumerable: true,
  11988. configurable: true
  11989. });
  11990. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11991. get: function () {
  11992. return AbstractMesh._BILLBOARDMODE_X;
  11993. },
  11994. enumerable: true,
  11995. configurable: true
  11996. });
  11997. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11998. get: function () {
  11999. return AbstractMesh._BILLBOARDMODE_Y;
  12000. },
  12001. enumerable: true,
  12002. configurable: true
  12003. });
  12004. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12005. get: function () {
  12006. return AbstractMesh._BILLBOARDMODE_Z;
  12007. },
  12008. enumerable: true,
  12009. configurable: true
  12010. });
  12011. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12012. get: function () {
  12013. return AbstractMesh._BILLBOARDMODE_ALL;
  12014. },
  12015. enumerable: true,
  12016. configurable: true
  12017. });
  12018. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12019. /**
  12020. * Read-only : the number of facets in the mesh
  12021. */
  12022. get: function () {
  12023. return this._facetNb;
  12024. },
  12025. enumerable: true,
  12026. configurable: true
  12027. });
  12028. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12029. /**
  12030. * The number (integer) of subdivisions per axis in the partioning space
  12031. */
  12032. get: function () {
  12033. return this._partitioningSubdivisions;
  12034. },
  12035. set: function (nb) {
  12036. this._partitioningSubdivisions = nb;
  12037. },
  12038. enumerable: true,
  12039. configurable: true
  12040. });
  12041. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12042. /**
  12043. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12044. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12045. */
  12046. get: function () {
  12047. return this._partitioningBBoxRatio;
  12048. },
  12049. set: function (ratio) {
  12050. this._partitioningBBoxRatio = ratio;
  12051. },
  12052. enumerable: true,
  12053. configurable: true
  12054. });
  12055. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12056. /**
  12057. * Read-only boolean : is the feature facetData enabled ?
  12058. */
  12059. get: function () {
  12060. return this._facetDataEnabled;
  12061. },
  12062. enumerable: true,
  12063. configurable: true
  12064. });
  12065. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12066. set: function (callback) {
  12067. if (this._onCollideObserver) {
  12068. this.onCollideObservable.remove(this._onCollideObserver);
  12069. }
  12070. this._onCollideObserver = this.onCollideObservable.add(callback);
  12071. },
  12072. enumerable: true,
  12073. configurable: true
  12074. });
  12075. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12076. set: function (callback) {
  12077. if (this._onCollisionPositionChangeObserver) {
  12078. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12079. }
  12080. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12086. /**
  12087. * 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.
  12088. */
  12089. get: function () {
  12090. return this._isOccluded;
  12091. },
  12092. set: function (value) {
  12093. this._isOccluded = value;
  12094. },
  12095. enumerable: true,
  12096. configurable: true
  12097. });
  12098. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12099. /**
  12100. * Flag to check the progress status of the query
  12101. */
  12102. get: function () {
  12103. return this._isOcclusionQueryInProgress;
  12104. },
  12105. enumerable: true,
  12106. configurable: true
  12107. });
  12108. Object.defineProperty(AbstractMesh.prototype, "material", {
  12109. get: function () {
  12110. return this._material;
  12111. },
  12112. set: function (value) {
  12113. if (this._material === value) {
  12114. return;
  12115. }
  12116. this._material = value;
  12117. if (this.onMaterialChangedObservable.hasObservers) {
  12118. this.onMaterialChangedObservable.notifyObservers(this);
  12119. }
  12120. if (!this.subMeshes) {
  12121. return;
  12122. }
  12123. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12124. var subMesh = _a[_i];
  12125. subMesh.setEffect(null);
  12126. }
  12127. },
  12128. enumerable: true,
  12129. configurable: true
  12130. });
  12131. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12132. get: function () {
  12133. return this._receiveShadows;
  12134. },
  12135. set: function (value) {
  12136. if (this._receiveShadows === value) {
  12137. return;
  12138. }
  12139. this._receiveShadows = value;
  12140. this._markSubMeshesAsLightDirty();
  12141. },
  12142. enumerable: true,
  12143. configurable: true
  12144. });
  12145. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12146. get: function () {
  12147. return this._hasVertexAlpha;
  12148. },
  12149. set: function (value) {
  12150. if (this._hasVertexAlpha === value) {
  12151. return;
  12152. }
  12153. this._hasVertexAlpha = value;
  12154. this._markSubMeshesAsAttributesDirty();
  12155. },
  12156. enumerable: true,
  12157. configurable: true
  12158. });
  12159. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12160. get: function () {
  12161. return this._useVertexColors;
  12162. },
  12163. set: function (value) {
  12164. if (this._useVertexColors === value) {
  12165. return;
  12166. }
  12167. this._useVertexColors = value;
  12168. this._markSubMeshesAsAttributesDirty();
  12169. },
  12170. enumerable: true,
  12171. configurable: true
  12172. });
  12173. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12174. get: function () {
  12175. return this._computeBonesUsingShaders;
  12176. },
  12177. set: function (value) {
  12178. if (this._computeBonesUsingShaders === value) {
  12179. return;
  12180. }
  12181. this._computeBonesUsingShaders = value;
  12182. this._markSubMeshesAsAttributesDirty();
  12183. },
  12184. enumerable: true,
  12185. configurable: true
  12186. });
  12187. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12188. get: function () {
  12189. return this._numBoneInfluencers;
  12190. },
  12191. set: function (value) {
  12192. if (this._numBoneInfluencers === value) {
  12193. return;
  12194. }
  12195. this._numBoneInfluencers = value;
  12196. this._markSubMeshesAsAttributesDirty();
  12197. },
  12198. enumerable: true,
  12199. configurable: true
  12200. });
  12201. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12202. get: function () {
  12203. return this._applyFog;
  12204. },
  12205. set: function (value) {
  12206. if (this._applyFog === value) {
  12207. return;
  12208. }
  12209. this._applyFog = value;
  12210. this._markSubMeshesAsMiscDirty();
  12211. },
  12212. enumerable: true,
  12213. configurable: true
  12214. });
  12215. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12216. get: function () {
  12217. return this._layerMask;
  12218. },
  12219. set: function (value) {
  12220. if (value === this._layerMask) {
  12221. return;
  12222. }
  12223. this._layerMask = value;
  12224. this._resyncLightSources();
  12225. },
  12226. enumerable: true,
  12227. configurable: true
  12228. });
  12229. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12230. get: function () {
  12231. return this._collisionMask;
  12232. },
  12233. set: function (mask) {
  12234. this._collisionMask = !isNaN(mask) ? mask : -1;
  12235. },
  12236. enumerable: true,
  12237. configurable: true
  12238. });
  12239. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12240. get: function () {
  12241. return this._collisionGroup;
  12242. },
  12243. set: function (mask) {
  12244. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12245. },
  12246. enumerable: true,
  12247. configurable: true
  12248. });
  12249. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12250. get: function () {
  12251. return null;
  12252. },
  12253. enumerable: true,
  12254. configurable: true
  12255. });
  12256. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12257. get: function () {
  12258. return this._skeleton;
  12259. },
  12260. set: function (value) {
  12261. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12262. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12263. }
  12264. if (value && value.needInitialSkinMatrix) {
  12265. value._registerMeshWithPoseMatrix(this);
  12266. }
  12267. this._skeleton = value;
  12268. if (!this._skeleton) {
  12269. this._bonesTransformMatrices = null;
  12270. }
  12271. this._markSubMeshesAsAttributesDirty();
  12272. },
  12273. enumerable: true,
  12274. configurable: true
  12275. });
  12276. /**
  12277. * Boolean : true if the mesh has been disposed.
  12278. */
  12279. AbstractMesh.prototype.isDisposed = function () {
  12280. return this._isDisposed;
  12281. };
  12282. /**
  12283. * Returns the string "AbstractMesh"
  12284. */
  12285. AbstractMesh.prototype.getClassName = function () {
  12286. return "AbstractMesh";
  12287. };
  12288. /**
  12289. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12290. */
  12291. AbstractMesh.prototype.toString = function (fullDetails) {
  12292. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12293. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12294. if (this._skeleton) {
  12295. ret += ", skeleton: " + this._skeleton.name;
  12296. }
  12297. if (fullDetails) {
  12298. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12299. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12300. }
  12301. return ret;
  12302. };
  12303. AbstractMesh.prototype._rebuild = function () {
  12304. if (!this.subMeshes) {
  12305. return;
  12306. }
  12307. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12308. var subMesh = _a[_i];
  12309. subMesh._rebuild();
  12310. }
  12311. };
  12312. AbstractMesh.prototype._resyncLightSources = function () {
  12313. this._lightSources.length = 0;
  12314. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12315. var light = _a[_i];
  12316. if (!light.isEnabled()) {
  12317. continue;
  12318. }
  12319. if (light.canAffectMesh(this)) {
  12320. this._lightSources.push(light);
  12321. }
  12322. }
  12323. this._markSubMeshesAsLightDirty();
  12324. };
  12325. AbstractMesh.prototype._resyncLighSource = function (light) {
  12326. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12327. var index = this._lightSources.indexOf(light);
  12328. if (index === -1) {
  12329. if (!isIn) {
  12330. return;
  12331. }
  12332. this._lightSources.push(light);
  12333. }
  12334. else {
  12335. if (isIn) {
  12336. return;
  12337. }
  12338. this._lightSources.splice(index, 1);
  12339. }
  12340. this._markSubMeshesAsLightDirty();
  12341. };
  12342. AbstractMesh.prototype._removeLightSource = function (light) {
  12343. var index = this._lightSources.indexOf(light);
  12344. if (index === -1) {
  12345. return;
  12346. }
  12347. this._lightSources.splice(index, 1);
  12348. };
  12349. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12350. if (!this.subMeshes) {
  12351. return;
  12352. }
  12353. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12354. var subMesh = _a[_i];
  12355. if (subMesh._materialDefines) {
  12356. func(subMesh._materialDefines);
  12357. }
  12358. }
  12359. };
  12360. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12361. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12362. };
  12363. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12364. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12365. };
  12366. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12367. if (!this.subMeshes) {
  12368. return;
  12369. }
  12370. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12371. var subMesh = _a[_i];
  12372. var material = subMesh.getMaterial();
  12373. if (material) {
  12374. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12375. }
  12376. }
  12377. };
  12378. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12379. /**
  12380. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12381. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12382. * Default : (0.0, 0.0, 0.0)
  12383. */
  12384. get: function () {
  12385. return this._rotation;
  12386. },
  12387. set: function (newRotation) {
  12388. this._rotation = newRotation;
  12389. },
  12390. enumerable: true,
  12391. configurable: true
  12392. });
  12393. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12394. /**
  12395. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12396. * Default : (1.0, 1.0, 1.0)
  12397. */
  12398. get: function () {
  12399. return this._scaling;
  12400. },
  12401. set: function (newScaling) {
  12402. this._scaling = newScaling;
  12403. if (this.physicsImpostor) {
  12404. this.physicsImpostor.forceUpdate();
  12405. }
  12406. },
  12407. enumerable: true,
  12408. configurable: true
  12409. });
  12410. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12411. /**
  12412. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12413. * It's null by default.
  12414. * 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)
  12415. */
  12416. get: function () {
  12417. return this._rotationQuaternion;
  12418. },
  12419. set: function (quaternion) {
  12420. this._rotationQuaternion = quaternion;
  12421. //reset the rotation vector.
  12422. if (quaternion && this.rotation.length()) {
  12423. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12424. }
  12425. },
  12426. enumerable: true,
  12427. configurable: true
  12428. });
  12429. // Methods
  12430. /**
  12431. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12432. * Returns the AbstractMesh.
  12433. */
  12434. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12435. this._poseMatrix.copyFrom(matrix);
  12436. return this;
  12437. };
  12438. /**
  12439. * Returns the mesh Pose matrix.
  12440. * Returned object : Matrix
  12441. */
  12442. AbstractMesh.prototype.getPoseMatrix = function () {
  12443. return this._poseMatrix;
  12444. };
  12445. /**
  12446. * Disables the mesh edger rendering mode.
  12447. * Returns the AbstractMesh.
  12448. */
  12449. AbstractMesh.prototype.disableEdgesRendering = function () {
  12450. if (this._edgesRenderer !== undefined) {
  12451. this._edgesRenderer.dispose();
  12452. this._edgesRenderer = undefined;
  12453. }
  12454. return this;
  12455. };
  12456. /**
  12457. * Enables the edge rendering mode on the mesh.
  12458. * This mode makes the mesh edges visible.
  12459. * Returns the AbstractMesh.
  12460. */
  12461. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12462. if (epsilon === void 0) { epsilon = 0.95; }
  12463. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12464. this.disableEdgesRendering();
  12465. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12466. return this;
  12467. };
  12468. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12469. /**
  12470. * Returns true if the mesh is blocked. Used by the class Mesh.
  12471. * Returns the boolean `false` by default.
  12472. */
  12473. get: function () {
  12474. return false;
  12475. },
  12476. enumerable: true,
  12477. configurable: true
  12478. });
  12479. /**
  12480. * Returns the mesh itself by default, used by the class Mesh.
  12481. * Returned type : AbstractMesh
  12482. */
  12483. AbstractMesh.prototype.getLOD = function (camera) {
  12484. return this;
  12485. };
  12486. /**
  12487. * Returns 0 by default, used by the class Mesh.
  12488. * Returns an integer.
  12489. */
  12490. AbstractMesh.prototype.getTotalVertices = function () {
  12491. return 0;
  12492. };
  12493. /**
  12494. * Returns null by default, used by the class Mesh.
  12495. * Returned type : integer array
  12496. */
  12497. AbstractMesh.prototype.getIndices = function () {
  12498. return null;
  12499. };
  12500. /**
  12501. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12502. * Returned type : float array or Float32Array
  12503. */
  12504. AbstractMesh.prototype.getVerticesData = function (kind) {
  12505. return null;
  12506. };
  12507. /**
  12508. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12509. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12510. * The `data` are either a numeric array either a Float32Array.
  12511. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12512. * 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).
  12513. * Note that a new underlying VertexBuffer object is created each call.
  12514. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12515. *
  12516. * Possible `kind` values :
  12517. * - BABYLON.VertexBuffer.PositionKind
  12518. * - BABYLON.VertexBuffer.UVKind
  12519. * - BABYLON.VertexBuffer.UV2Kind
  12520. * - BABYLON.VertexBuffer.UV3Kind
  12521. * - BABYLON.VertexBuffer.UV4Kind
  12522. * - BABYLON.VertexBuffer.UV5Kind
  12523. * - BABYLON.VertexBuffer.UV6Kind
  12524. * - BABYLON.VertexBuffer.ColorKind
  12525. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12526. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12527. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12528. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12529. *
  12530. * Returns the Mesh.
  12531. */
  12532. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12533. return null;
  12534. };
  12535. /**
  12536. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12537. * If the mesh has no geometry, it is simply returned as it is.
  12538. * The `data` are either a numeric array either a Float32Array.
  12539. * No new underlying VertexBuffer object is created.
  12540. * 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.
  12541. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12542. *
  12543. * Possible `kind` values :
  12544. * - BABYLON.VertexBuffer.PositionKind
  12545. * - BABYLON.VertexBuffer.UVKind
  12546. * - BABYLON.VertexBuffer.UV2Kind
  12547. * - BABYLON.VertexBuffer.UV3Kind
  12548. * - BABYLON.VertexBuffer.UV4Kind
  12549. * - BABYLON.VertexBuffer.UV5Kind
  12550. * - BABYLON.VertexBuffer.UV6Kind
  12551. * - BABYLON.VertexBuffer.ColorKind
  12552. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12553. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12554. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12555. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12556. *
  12557. * Returns the Mesh.
  12558. */
  12559. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12560. return null;
  12561. };
  12562. /**
  12563. * Sets the mesh indices.
  12564. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12565. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12566. * This method creates a new index buffer each call.
  12567. * Returns the Mesh.
  12568. */
  12569. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12570. return null;
  12571. };
  12572. /** Returns false by default, used by the class Mesh.
  12573. * Returns a boolean
  12574. */
  12575. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12576. return false;
  12577. };
  12578. /**
  12579. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12580. * Returns a BoundingInfo
  12581. */
  12582. AbstractMesh.prototype.getBoundingInfo = function () {
  12583. if (this._masterMesh) {
  12584. return this._masterMesh.getBoundingInfo();
  12585. }
  12586. if (!this._boundingInfo) {
  12587. this._updateBoundingInfo();
  12588. }
  12589. return this._boundingInfo;
  12590. };
  12591. /**
  12592. * Sets a mesh new object BoundingInfo.
  12593. * Returns the AbstractMesh.
  12594. */
  12595. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12596. this._boundingInfo = boundingInfo;
  12597. return this;
  12598. };
  12599. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12600. get: function () {
  12601. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12602. },
  12603. enumerable: true,
  12604. configurable: true
  12605. });
  12606. AbstractMesh.prototype._preActivate = function () {
  12607. };
  12608. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12609. };
  12610. AbstractMesh.prototype._activate = function (renderId) {
  12611. this._renderId = renderId;
  12612. };
  12613. /**
  12614. * Returns the last update of the World matrix
  12615. * Returns a Matrix.
  12616. */
  12617. AbstractMesh.prototype.getWorldMatrix = function () {
  12618. if (this._masterMesh) {
  12619. return this._masterMesh.getWorldMatrix();
  12620. }
  12621. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12622. this.computeWorldMatrix();
  12623. }
  12624. return this._worldMatrix;
  12625. };
  12626. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12627. /**
  12628. * Returns directly the last state of the mesh World matrix.
  12629. * A Matrix is returned.
  12630. */
  12631. get: function () {
  12632. return this._worldMatrix;
  12633. },
  12634. enumerable: true,
  12635. configurable: true
  12636. });
  12637. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12638. /**
  12639. * Returns the current mesh absolute position.
  12640. * Retuns a Vector3.
  12641. */
  12642. get: function () {
  12643. return this._absolutePosition;
  12644. },
  12645. enumerable: true,
  12646. configurable: true
  12647. });
  12648. /**
  12649. * Prevents the World matrix to be computed any longer.
  12650. * Returns the AbstractMesh.
  12651. */
  12652. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12653. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12654. this.computeWorldMatrix(true);
  12655. this._isWorldMatrixFrozen = true;
  12656. return this;
  12657. };
  12658. /**
  12659. * Allows back the World matrix computation.
  12660. * Returns the AbstractMesh.
  12661. */
  12662. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12663. this._isWorldMatrixFrozen = false;
  12664. this.computeWorldMatrix(true);
  12665. return this;
  12666. };
  12667. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12668. /**
  12669. * True if the World matrix has been frozen.
  12670. * Returns a boolean.
  12671. */
  12672. get: function () {
  12673. return this._isWorldMatrixFrozen;
  12674. },
  12675. enumerable: true,
  12676. configurable: true
  12677. });
  12678. /**
  12679. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12680. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12681. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12682. * The passed axis is also normalized.
  12683. * Returns the AbstractMesh.
  12684. */
  12685. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12686. axis.normalize();
  12687. if (!this.rotationQuaternion) {
  12688. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12689. this.rotation = BABYLON.Vector3.Zero();
  12690. }
  12691. var rotationQuaternion;
  12692. if (!space || space === BABYLON.Space.LOCAL) {
  12693. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12694. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12695. }
  12696. else {
  12697. if (this.parent) {
  12698. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12699. invertParentWorldMatrix.invert();
  12700. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12701. }
  12702. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12703. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12704. }
  12705. return this;
  12706. };
  12707. /**
  12708. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12709. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12710. * The passed axis is also normalized.
  12711. * Returns the AbstractMesh.
  12712. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12713. */
  12714. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12715. axis.normalize();
  12716. if (!this.rotationQuaternion) {
  12717. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12718. this.rotation.copyFromFloats(0, 0, 0);
  12719. }
  12720. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12721. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12722. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12723. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12724. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12725. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12726. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12727. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12728. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12729. return this;
  12730. };
  12731. /**
  12732. * Translates the mesh along the axis vector for the passed distance in the given space.
  12733. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12734. * Returns the AbstractMesh.
  12735. */
  12736. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12737. var displacementVector = axis.scale(distance);
  12738. if (!space || space === BABYLON.Space.LOCAL) {
  12739. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12740. this.setPositionWithLocalVector(tempV3);
  12741. }
  12742. else {
  12743. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12744. }
  12745. return this;
  12746. };
  12747. /**
  12748. * Adds a rotation step to the mesh current rotation.
  12749. * x, y, z are Euler angles expressed in radians.
  12750. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12751. * This means this rotation is made in the mesh local space only.
  12752. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12753. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12754. * ```javascript
  12755. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12756. * ```
  12757. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12758. * 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.
  12759. * Returns the AbstractMesh.
  12760. */
  12761. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12762. var rotationQuaternion;
  12763. if (this.rotationQuaternion) {
  12764. rotationQuaternion = this.rotationQuaternion;
  12765. }
  12766. else {
  12767. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12768. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12769. }
  12770. var accumulation = BABYLON.Tmp.Quaternion[0];
  12771. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12772. rotationQuaternion.multiplyInPlace(accumulation);
  12773. if (!this.rotationQuaternion) {
  12774. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12775. }
  12776. return this;
  12777. };
  12778. /**
  12779. * Retuns the mesh absolute position in the World.
  12780. * Returns a Vector3.
  12781. */
  12782. AbstractMesh.prototype.getAbsolutePosition = function () {
  12783. this.computeWorldMatrix();
  12784. return this._absolutePosition;
  12785. };
  12786. /**
  12787. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12788. * Returns the AbstractMesh.
  12789. */
  12790. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12791. if (!absolutePosition) {
  12792. return;
  12793. }
  12794. var absolutePositionX;
  12795. var absolutePositionY;
  12796. var absolutePositionZ;
  12797. if (absolutePosition.x === undefined) {
  12798. if (arguments.length < 3) {
  12799. return;
  12800. }
  12801. absolutePositionX = arguments[0];
  12802. absolutePositionY = arguments[1];
  12803. absolutePositionZ = arguments[2];
  12804. }
  12805. else {
  12806. absolutePositionX = absolutePosition.x;
  12807. absolutePositionY = absolutePosition.y;
  12808. absolutePositionZ = absolutePosition.z;
  12809. }
  12810. if (this.parent) {
  12811. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12812. invertParentWorldMatrix.invert();
  12813. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12814. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12815. }
  12816. else {
  12817. this.position.x = absolutePositionX;
  12818. this.position.y = absolutePositionY;
  12819. this.position.z = absolutePositionZ;
  12820. }
  12821. return this;
  12822. };
  12823. // ================================== Point of View Movement =================================
  12824. /**
  12825. * Perform relative position change from the point of view of behind the front of the mesh.
  12826. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12827. * Supports definition of mesh facing forward or backward.
  12828. * @param {number} amountRight
  12829. * @param {number} amountUp
  12830. * @param {number} amountForward
  12831. *
  12832. * Returns the AbstractMesh.
  12833. */
  12834. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12835. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12836. return this;
  12837. };
  12838. /**
  12839. * Calculate relative position change from the point of view of behind the front of the mesh.
  12840. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12841. * Supports definition of mesh facing forward or backward.
  12842. * @param {number} amountRight
  12843. * @param {number} amountUp
  12844. * @param {number} amountForward
  12845. *
  12846. * Returns a new Vector3.
  12847. */
  12848. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12849. var rotMatrix = new BABYLON.Matrix();
  12850. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12851. rotQuaternion.toRotationMatrix(rotMatrix);
  12852. var translationDelta = BABYLON.Vector3.Zero();
  12853. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12854. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12855. return translationDelta;
  12856. };
  12857. // ================================== Point of View Rotation =================================
  12858. /**
  12859. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12860. * Supports definition of mesh facing forward or backward.
  12861. * @param {number} flipBack
  12862. * @param {number} twirlClockwise
  12863. * @param {number} tiltRight
  12864. *
  12865. * Returns the AbstractMesh.
  12866. */
  12867. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12868. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12869. return this;
  12870. };
  12871. /**
  12872. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12873. * Supports definition of mesh facing forward or backward.
  12874. * @param {number} flipBack
  12875. * @param {number} twirlClockwise
  12876. * @param {number} tiltRight
  12877. *
  12878. * Returns a new Vector3.
  12879. */
  12880. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12881. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12882. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12883. };
  12884. /**
  12885. * Sets a new pivot matrix to the mesh.
  12886. * Returns the AbstractMesh.
  12887. */
  12888. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12889. this._pivotMatrix = matrix;
  12890. this._cache.pivotMatrixUpdated = true;
  12891. return this;
  12892. };
  12893. /**
  12894. * Returns the mesh pivot matrix.
  12895. * Default : Identity.
  12896. * A Matrix is returned.
  12897. */
  12898. AbstractMesh.prototype.getPivotMatrix = function () {
  12899. return this._pivotMatrix;
  12900. };
  12901. AbstractMesh.prototype._isSynchronized = function () {
  12902. if (this._isDirty) {
  12903. return false;
  12904. }
  12905. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12906. return false;
  12907. if (this._cache.pivotMatrixUpdated) {
  12908. return false;
  12909. }
  12910. if (this.infiniteDistance) {
  12911. return false;
  12912. }
  12913. if (!this._cache.position.equals(this.position))
  12914. return false;
  12915. if (this.rotationQuaternion) {
  12916. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12917. return false;
  12918. }
  12919. if (!this._cache.rotation.equals(this.rotation))
  12920. return false;
  12921. if (!this._cache.scaling.equals(this.scaling))
  12922. return false;
  12923. return true;
  12924. };
  12925. AbstractMesh.prototype._initCache = function () {
  12926. _super.prototype._initCache.call(this);
  12927. this._cache.localMatrixUpdated = false;
  12928. this._cache.position = BABYLON.Vector3.Zero();
  12929. this._cache.scaling = BABYLON.Vector3.Zero();
  12930. this._cache.rotation = BABYLON.Vector3.Zero();
  12931. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12932. this._cache.billboardMode = -1;
  12933. };
  12934. AbstractMesh.prototype.markAsDirty = function (property) {
  12935. if (property === "rotation") {
  12936. this.rotationQuaternion = null;
  12937. }
  12938. this._currentRenderId = Number.MAX_VALUE;
  12939. this._isDirty = true;
  12940. return this;
  12941. };
  12942. /**
  12943. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12944. * Returns the AbstractMesh.
  12945. */
  12946. AbstractMesh.prototype._updateBoundingInfo = function () {
  12947. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12948. this._boundingInfo.update(this.worldMatrixFromCache);
  12949. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12950. return this;
  12951. };
  12952. /**
  12953. * Update a mesh's children BoundingInfo objects only.
  12954. * Returns the AbstractMesh.
  12955. */
  12956. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12957. if (!this.subMeshes) {
  12958. return;
  12959. }
  12960. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12961. var subMesh = this.subMeshes[subIndex];
  12962. if (!subMesh.IsGlobal) {
  12963. subMesh.updateBoundingInfo(matrix);
  12964. }
  12965. }
  12966. return this;
  12967. };
  12968. /**
  12969. * Computes the mesh World matrix and returns it.
  12970. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12971. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12972. * If the parameter `force`is set to `true`, the actual computation is done.
  12973. * Returns the mesh World Matrix.
  12974. */
  12975. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12976. if (this._isWorldMatrixFrozen) {
  12977. return this._worldMatrix;
  12978. }
  12979. if (!force && this.isSynchronized(true)) {
  12980. this._currentRenderId = this.getScene().getRenderId();
  12981. return this._worldMatrix;
  12982. }
  12983. this._cache.position.copyFrom(this.position);
  12984. this._cache.scaling.copyFrom(this.scaling);
  12985. this._cache.pivotMatrixUpdated = false;
  12986. this._cache.billboardMode = this.billboardMode;
  12987. this._currentRenderId = this.getScene().getRenderId();
  12988. this._isDirty = false;
  12989. // Scaling
  12990. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12991. // Rotation
  12992. //rotate, if quaternion is set and rotation was used
  12993. if (this.rotationQuaternion) {
  12994. var len = this.rotation.length();
  12995. if (len) {
  12996. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12997. this.rotation.copyFromFloats(0, 0, 0);
  12998. }
  12999. }
  13000. if (this.rotationQuaternion) {
  13001. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13002. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13003. }
  13004. else {
  13005. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13006. this._cache.rotation.copyFrom(this.rotation);
  13007. }
  13008. // Translation
  13009. if (this.infiniteDistance && !this.parent) {
  13010. var camera = this.getScene().activeCamera;
  13011. if (camera) {
  13012. var cameraWorldMatrix = camera.getWorldMatrix();
  13013. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13014. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13015. }
  13016. }
  13017. else {
  13018. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13019. }
  13020. // Composing transformations
  13021. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13022. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13023. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13024. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13025. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13026. // Need to decompose each rotation here
  13027. var currentPosition = BABYLON.Tmp.Vector3[3];
  13028. if (this.parent && this.parent.getWorldMatrix) {
  13029. if (this._meshToBoneReferal) {
  13030. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13031. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13032. }
  13033. else {
  13034. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13035. }
  13036. }
  13037. else {
  13038. currentPosition.copyFrom(this.position);
  13039. }
  13040. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13041. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13042. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13043. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13044. }
  13045. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13046. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13047. }
  13048. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13049. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13050. }
  13051. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13052. }
  13053. else {
  13054. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13055. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13056. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13057. }
  13058. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13059. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13060. }
  13061. // Local world
  13062. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13063. // Parent
  13064. if (this.parent && this.parent.getWorldMatrix) {
  13065. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13066. if (this._meshToBoneReferal) {
  13067. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13068. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13069. }
  13070. else {
  13071. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13072. }
  13073. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13074. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13075. this._worldMatrix.copyFrom(this._localWorld);
  13076. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13077. }
  13078. else {
  13079. if (this._meshToBoneReferal) {
  13080. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13081. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13082. }
  13083. else {
  13084. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13085. }
  13086. }
  13087. this._markSyncedWithParent();
  13088. }
  13089. else {
  13090. this._worldMatrix.copyFrom(this._localWorld);
  13091. }
  13092. // Bounding info
  13093. this._updateBoundingInfo();
  13094. // Absolute position
  13095. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13096. // Callbacks
  13097. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13098. if (!this._poseMatrix) {
  13099. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13100. }
  13101. return this._worldMatrix;
  13102. };
  13103. /**
  13104. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13105. * @param func: callback function to add
  13106. *
  13107. * Returns the AbstractMesh.
  13108. */
  13109. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13110. this.onAfterWorldMatrixUpdateObservable.add(func);
  13111. return this;
  13112. };
  13113. /**
  13114. * Removes a registered callback function.
  13115. * Returns the AbstractMesh.
  13116. */
  13117. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13118. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13119. return this;
  13120. };
  13121. /**
  13122. * Sets the mesh position in its local space.
  13123. * Returns the AbstractMesh.
  13124. */
  13125. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13126. this.computeWorldMatrix();
  13127. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13128. return this;
  13129. };
  13130. /**
  13131. * Returns the mesh position in the local space from the current World matrix values.
  13132. * Returns a new Vector3.
  13133. */
  13134. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13135. this.computeWorldMatrix();
  13136. var invLocalWorldMatrix = this._localWorld.clone();
  13137. invLocalWorldMatrix.invert();
  13138. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13139. };
  13140. /**
  13141. * Translates the mesh along the passed Vector3 in its local space.
  13142. * Returns the AbstractMesh.
  13143. */
  13144. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13145. this.computeWorldMatrix(true);
  13146. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13147. return this;
  13148. };
  13149. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13150. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13151. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13152. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13153. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13154. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13155. /// <returns>Mesh oriented towards targetMesh</returns>
  13156. if (yawCor === void 0) { yawCor = 0; }
  13157. if (pitchCor === void 0) { pitchCor = 0; }
  13158. if (rollCor === void 0) { rollCor = 0; }
  13159. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13160. var dv = AbstractMesh._lookAtVectorCache;
  13161. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13162. targetPoint.subtractToRef(pos, dv);
  13163. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13164. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13165. var pitch = Math.atan2(dv.y, len);
  13166. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13167. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13168. return this;
  13169. };
  13170. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13171. this._meshToBoneReferal = affectedMesh;
  13172. this.parent = bone;
  13173. if (bone.getWorldMatrix().determinant() < 0) {
  13174. this.scalingDeterminant *= -1;
  13175. }
  13176. return this;
  13177. };
  13178. AbstractMesh.prototype.detachFromBone = function () {
  13179. if (this.parent.getWorldMatrix().determinant() < 0) {
  13180. this.scalingDeterminant *= -1;
  13181. }
  13182. this._meshToBoneReferal = null;
  13183. this.parent = null;
  13184. return this;
  13185. };
  13186. /**
  13187. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13188. * A mesh is in the frustum if its bounding box intersects the frustum.
  13189. * Boolean returned.
  13190. */
  13191. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13192. return this._boundingInfo.isInFrustum(frustumPlanes);
  13193. };
  13194. /**
  13195. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13196. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13197. * Boolean returned.
  13198. */
  13199. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13200. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13201. ;
  13202. };
  13203. /**
  13204. * True if the mesh intersects another mesh or a SolidParticle object.
  13205. * 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)
  13206. * Returns a boolean.
  13207. */
  13208. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13209. if (!this._boundingInfo || !mesh._boundingInfo) {
  13210. return false;
  13211. }
  13212. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13213. };
  13214. /**
  13215. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13216. * Returns a boolean.
  13217. */
  13218. AbstractMesh.prototype.intersectsPoint = function (point) {
  13219. if (!this._boundingInfo) {
  13220. return false;
  13221. }
  13222. return this._boundingInfo.intersectsPoint(point);
  13223. };
  13224. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13225. return this.physicsImpostor;
  13226. };
  13227. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13228. if (!camera) {
  13229. camera = this.getScene().activeCamera;
  13230. }
  13231. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13232. };
  13233. /**
  13234. * Returns the distance from the mesh to the active camera.
  13235. * Returns a float.
  13236. */
  13237. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13238. if (!camera) {
  13239. camera = this.getScene().activeCamera;
  13240. }
  13241. return this.absolutePosition.subtract(camera.position).length();
  13242. };
  13243. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13244. if (!this.physicsImpostor) {
  13245. return;
  13246. }
  13247. this.physicsImpostor.applyImpulse(force, contactPoint);
  13248. return this;
  13249. };
  13250. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13251. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13252. return;
  13253. }
  13254. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13255. mainPivot: pivot1,
  13256. connectedPivot: pivot2,
  13257. nativeParams: options
  13258. });
  13259. return this;
  13260. };
  13261. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13262. // Collisions
  13263. /**
  13264. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13265. * Default `false`.
  13266. */
  13267. get: function () {
  13268. return this._checkCollisions;
  13269. },
  13270. set: function (collisionEnabled) {
  13271. this._checkCollisions = collisionEnabled;
  13272. if (this.getScene().workerCollisions) {
  13273. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13274. }
  13275. },
  13276. enumerable: true,
  13277. configurable: true
  13278. });
  13279. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13280. var globalPosition = this.getAbsolutePosition();
  13281. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13282. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13283. if (!this._collider) {
  13284. this._collider = new BABYLON.Collider();
  13285. }
  13286. this._collider.radius = this.ellipsoid;
  13287. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13288. return this;
  13289. };
  13290. // Submeshes octree
  13291. /**
  13292. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13293. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13294. * Returns an Octree of submeshes.
  13295. */
  13296. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13297. if (maxCapacity === void 0) { maxCapacity = 64; }
  13298. if (maxDepth === void 0) { maxDepth = 2; }
  13299. if (!this._submeshesOctree) {
  13300. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13301. }
  13302. this.computeWorldMatrix(true);
  13303. // Update octree
  13304. var bbox = this.getBoundingInfo().boundingBox;
  13305. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13306. return this._submeshesOctree;
  13307. };
  13308. // Collisions
  13309. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13310. this._generatePointsArray();
  13311. // Transformation
  13312. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13313. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13314. subMesh._lastColliderWorldVertices = [];
  13315. subMesh._trianglePlanes = [];
  13316. var start = subMesh.verticesStart;
  13317. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13318. for (var i = start; i < end; i++) {
  13319. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13320. }
  13321. }
  13322. // Collide
  13323. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13324. if (collider.collisionFound) {
  13325. collider.collidedMesh = this;
  13326. }
  13327. return this;
  13328. };
  13329. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13330. var subMeshes;
  13331. var len;
  13332. // Octrees
  13333. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13334. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13335. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13336. len = intersections.length;
  13337. subMeshes = intersections.data;
  13338. }
  13339. else {
  13340. subMeshes = this.subMeshes;
  13341. len = subMeshes.length;
  13342. }
  13343. for (var index = 0; index < len; index++) {
  13344. var subMesh = subMeshes[index];
  13345. // Bounding test
  13346. if (len > 1 && !subMesh._checkCollision(collider))
  13347. continue;
  13348. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13349. }
  13350. return this;
  13351. };
  13352. AbstractMesh.prototype._checkCollision = function (collider) {
  13353. // Bounding box test
  13354. if (!this._boundingInfo._checkCollision(collider))
  13355. return this;
  13356. // Transformation matrix
  13357. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13358. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13359. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13360. return this;
  13361. };
  13362. // Picking
  13363. AbstractMesh.prototype._generatePointsArray = function () {
  13364. return false;
  13365. };
  13366. /**
  13367. * Checks if the passed Ray intersects with the mesh.
  13368. * Returns an object PickingInfo.
  13369. */
  13370. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13371. var pickingInfo = new BABYLON.PickingInfo();
  13372. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13373. return pickingInfo;
  13374. }
  13375. if (!this._generatePointsArray()) {
  13376. return pickingInfo;
  13377. }
  13378. var intersectInfo = null;
  13379. // Octrees
  13380. var subMeshes;
  13381. var len;
  13382. if (this._submeshesOctree && this.useOctreeForPicking) {
  13383. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13384. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13385. len = intersections.length;
  13386. subMeshes = intersections.data;
  13387. }
  13388. else {
  13389. subMeshes = this.subMeshes;
  13390. len = subMeshes.length;
  13391. }
  13392. for (var index = 0; index < len; index++) {
  13393. var subMesh = subMeshes[index];
  13394. // Bounding test
  13395. if (len > 1 && !subMesh.canIntersects(ray))
  13396. continue;
  13397. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13398. if (currentIntersectInfo) {
  13399. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13400. intersectInfo = currentIntersectInfo;
  13401. intersectInfo.subMeshId = index;
  13402. if (fastCheck) {
  13403. break;
  13404. }
  13405. }
  13406. }
  13407. }
  13408. if (intersectInfo) {
  13409. // Get picked point
  13410. var world = this.getWorldMatrix();
  13411. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13412. var direction = ray.direction.clone();
  13413. direction = direction.scale(intersectInfo.distance);
  13414. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13415. var pickedPoint = worldOrigin.add(worldDirection);
  13416. // Return result
  13417. pickingInfo.hit = true;
  13418. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13419. pickingInfo.pickedPoint = pickedPoint;
  13420. pickingInfo.pickedMesh = this;
  13421. pickingInfo.bu = intersectInfo.bu;
  13422. pickingInfo.bv = intersectInfo.bv;
  13423. pickingInfo.faceId = intersectInfo.faceId;
  13424. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13425. return pickingInfo;
  13426. }
  13427. return pickingInfo;
  13428. };
  13429. /**
  13430. * Clones the mesh, used by the class Mesh.
  13431. * Just returns `null` for an AbstractMesh.
  13432. */
  13433. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13434. return null;
  13435. };
  13436. /**
  13437. * Disposes all the mesh submeshes.
  13438. * Returns the AbstractMesh.
  13439. */
  13440. AbstractMesh.prototype.releaseSubMeshes = function () {
  13441. if (this.subMeshes) {
  13442. while (this.subMeshes.length) {
  13443. this.subMeshes[0].dispose();
  13444. }
  13445. }
  13446. else {
  13447. this.subMeshes = new Array();
  13448. }
  13449. return this;
  13450. };
  13451. /**
  13452. * Disposes the AbstractMesh.
  13453. * Some internal references are kept for further use.
  13454. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13455. * Returns nothing.
  13456. */
  13457. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13458. var _this = this;
  13459. var index;
  13460. // Action manager
  13461. if (this.actionManager) {
  13462. this.actionManager.dispose();
  13463. this.actionManager = null;
  13464. }
  13465. // Skeleton
  13466. this.skeleton = null;
  13467. // Animations
  13468. this.getScene().stopAnimation(this);
  13469. // Physics
  13470. if (this.physicsImpostor) {
  13471. this.physicsImpostor.dispose();
  13472. }
  13473. // Intersections in progress
  13474. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13475. var other = this._intersectionsInProgress[index];
  13476. var pos = other._intersectionsInProgress.indexOf(this);
  13477. other._intersectionsInProgress.splice(pos, 1);
  13478. }
  13479. this._intersectionsInProgress = [];
  13480. // Lights
  13481. var lights = this.getScene().lights;
  13482. lights.forEach(function (light) {
  13483. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13484. if (meshIndex !== -1) {
  13485. light.includedOnlyMeshes.splice(meshIndex, 1);
  13486. }
  13487. meshIndex = light.excludedMeshes.indexOf(_this);
  13488. if (meshIndex !== -1) {
  13489. light.excludedMeshes.splice(meshIndex, 1);
  13490. }
  13491. // Shadow generators
  13492. var generator = light.getShadowGenerator();
  13493. if (generator) {
  13494. var shadowMap = generator.getShadowMap();
  13495. meshIndex = shadowMap.renderList.indexOf(_this);
  13496. if (meshIndex !== -1) {
  13497. shadowMap.renderList.splice(meshIndex, 1);
  13498. }
  13499. }
  13500. });
  13501. // Edges
  13502. if (this._edgesRenderer) {
  13503. this._edgesRenderer.dispose();
  13504. this._edgesRenderer = null;
  13505. }
  13506. // SubMeshes
  13507. if (this.getClassName() !== "InstancedMesh") {
  13508. this.releaseSubMeshes();
  13509. }
  13510. // Octree
  13511. var sceneOctree = this.getScene().selectionOctree;
  13512. if (sceneOctree) {
  13513. var index = sceneOctree.dynamicContent.indexOf(this);
  13514. if (index !== -1) {
  13515. sceneOctree.dynamicContent.splice(index, 1);
  13516. }
  13517. }
  13518. // Query
  13519. var engine = this.getScene().getEngine();
  13520. if (this._occlusionQuery) {
  13521. engine.deleteQuery(this._occlusionQuery);
  13522. this._occlusionQuery = null;
  13523. }
  13524. // Engine
  13525. engine.wipeCaches();
  13526. // Remove from scene
  13527. this.getScene().removeMesh(this);
  13528. if (!doNotRecurse) {
  13529. // Particles
  13530. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13531. if (this.getScene().particleSystems[index].emitter === this) {
  13532. this.getScene().particleSystems[index].dispose();
  13533. index--;
  13534. }
  13535. }
  13536. // Children
  13537. var objects = this.getDescendants(true);
  13538. for (index = 0; index < objects.length; index++) {
  13539. objects[index].dispose();
  13540. }
  13541. }
  13542. else {
  13543. var childMeshes = this.getChildMeshes(true);
  13544. for (index = 0; index < childMeshes.length; index++) {
  13545. var child = childMeshes[index];
  13546. child.parent = null;
  13547. child.computeWorldMatrix(true);
  13548. }
  13549. }
  13550. // facet data
  13551. if (this._facetDataEnabled) {
  13552. this.disableFacetData();
  13553. }
  13554. this.onAfterWorldMatrixUpdateObservable.clear();
  13555. this.onCollideObservable.clear();
  13556. this.onCollisionPositionChangeObservable.clear();
  13557. this._isDisposed = true;
  13558. _super.prototype.dispose.call(this);
  13559. };
  13560. /**
  13561. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13562. * This Vector3 is expressed in the World space.
  13563. */
  13564. AbstractMesh.prototype.getDirection = function (localAxis) {
  13565. var result = BABYLON.Vector3.Zero();
  13566. this.getDirectionToRef(localAxis, result);
  13567. return result;
  13568. };
  13569. /**
  13570. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13571. * localAxis is expressed in the mesh local space.
  13572. * result is computed in the Wordl space from the mesh World matrix.
  13573. * Returns the AbstractMesh.
  13574. */
  13575. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13576. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13577. return this;
  13578. };
  13579. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13580. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13581. if (this.getScene().getRenderId() == 0) {
  13582. this.computeWorldMatrix(true);
  13583. }
  13584. var wm = this.getWorldMatrix();
  13585. if (space == BABYLON.Space.WORLD) {
  13586. var tmat = BABYLON.Tmp.Matrix[0];
  13587. wm.invertToRef(tmat);
  13588. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13589. }
  13590. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13591. this._pivotMatrix.m[12] = -point.x;
  13592. this._pivotMatrix.m[13] = -point.y;
  13593. this._pivotMatrix.m[14] = -point.z;
  13594. this._cache.pivotMatrixUpdated = true;
  13595. return this;
  13596. };
  13597. /**
  13598. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13599. */
  13600. AbstractMesh.prototype.getPivotPoint = function () {
  13601. var point = BABYLON.Vector3.Zero();
  13602. this.getPivotPointToRef(point);
  13603. return point;
  13604. };
  13605. /**
  13606. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13607. * Returns the AbstractMesh.
  13608. */
  13609. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13610. result.x = -this._pivotMatrix.m[12];
  13611. result.y = -this._pivotMatrix.m[13];
  13612. result.z = -this._pivotMatrix.m[14];
  13613. return this;
  13614. };
  13615. /**
  13616. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13617. */
  13618. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13619. var point = BABYLON.Vector3.Zero();
  13620. this.getAbsolutePivotPointToRef(point);
  13621. return point;
  13622. };
  13623. /**
  13624. * Defines the passed mesh as the parent of the current mesh.
  13625. * Returns the AbstractMesh.
  13626. */
  13627. AbstractMesh.prototype.setParent = function (mesh) {
  13628. var child = this;
  13629. var parent = mesh;
  13630. if (mesh == null) {
  13631. var rotation = BABYLON.Tmp.Quaternion[0];
  13632. var position = BABYLON.Tmp.Vector3[0];
  13633. var scale = BABYLON.Tmp.Vector3[1];
  13634. child.getWorldMatrix().decompose(scale, rotation, position);
  13635. if (child.rotationQuaternion) {
  13636. child.rotationQuaternion.copyFrom(rotation);
  13637. }
  13638. else {
  13639. rotation.toEulerAnglesToRef(child.rotation);
  13640. }
  13641. child.position.x = position.x;
  13642. child.position.y = position.y;
  13643. child.position.z = position.z;
  13644. }
  13645. else {
  13646. var rotation = BABYLON.Tmp.Quaternion[0];
  13647. var position = BABYLON.Tmp.Vector3[0];
  13648. var scale = BABYLON.Tmp.Vector3[1];
  13649. var m1 = BABYLON.Tmp.Matrix[0];
  13650. var m2 = BABYLON.Tmp.Matrix[1];
  13651. parent.getWorldMatrix().decompose(scale, rotation, position);
  13652. rotation.toRotationMatrix(m1);
  13653. m2.setTranslation(position);
  13654. m2.multiplyToRef(m1, m1);
  13655. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13656. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13657. m.decompose(scale, rotation, position);
  13658. if (child.rotationQuaternion) {
  13659. child.rotationQuaternion.copyFrom(rotation);
  13660. }
  13661. else {
  13662. rotation.toEulerAnglesToRef(child.rotation);
  13663. }
  13664. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13665. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13666. m.decompose(scale, rotation, position);
  13667. child.position.x = position.x;
  13668. child.position.y = position.y;
  13669. child.position.z = position.z;
  13670. }
  13671. child.parent = parent;
  13672. return this;
  13673. };
  13674. /**
  13675. * Adds the passed mesh as a child to the current mesh.
  13676. * Returns the AbstractMesh.
  13677. */
  13678. AbstractMesh.prototype.addChild = function (mesh) {
  13679. mesh.setParent(this);
  13680. return this;
  13681. };
  13682. /**
  13683. * Removes the passed mesh from the current mesh children list.
  13684. * Returns the AbstractMesh.
  13685. */
  13686. AbstractMesh.prototype.removeChild = function (mesh) {
  13687. mesh.setParent(null);
  13688. return this;
  13689. };
  13690. /**
  13691. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13692. * Returns the AbstractMesh.
  13693. */
  13694. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13695. result.x = this._pivotMatrix.m[12];
  13696. result.y = this._pivotMatrix.m[13];
  13697. result.z = this._pivotMatrix.m[14];
  13698. this.getPivotPointToRef(result);
  13699. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13700. return this;
  13701. };
  13702. // Facet data
  13703. /**
  13704. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13705. * Returns the AbstractMesh.
  13706. */
  13707. AbstractMesh.prototype._initFacetData = function () {
  13708. if (!this._facetNormals) {
  13709. this._facetNormals = new Array();
  13710. }
  13711. if (!this._facetPositions) {
  13712. this._facetPositions = new Array();
  13713. }
  13714. if (!this._facetPartitioning) {
  13715. this._facetPartitioning = new Array();
  13716. }
  13717. this._facetNb = this.getIndices().length / 3;
  13718. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13719. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13720. for (var f = 0; f < this._facetNb; f++) {
  13721. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13722. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13723. }
  13724. this._facetDataEnabled = true;
  13725. return this;
  13726. };
  13727. /**
  13728. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13729. * This method can be called within the render loop.
  13730. * 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.
  13731. * Returns the AbstractMesh.
  13732. */
  13733. AbstractMesh.prototype.updateFacetData = function () {
  13734. if (!this._facetDataEnabled) {
  13735. this._initFacetData();
  13736. }
  13737. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13738. var indices = this.getIndices();
  13739. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13740. var bInfo = this.getBoundingInfo();
  13741. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13742. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13743. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13744. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13745. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13746. this._subDiv.max = this._partitioningSubdivisions;
  13747. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13748. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13749. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13750. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13751. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13752. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13753. // set the parameters for ComputeNormals()
  13754. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13755. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13756. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13757. this._facetParameters.bInfo = bInfo;
  13758. this._facetParameters.bbSize = this._bbSize;
  13759. this._facetParameters.subDiv = this._subDiv;
  13760. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13761. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13762. return this;
  13763. };
  13764. /**
  13765. * Returns the facetLocalNormals array.
  13766. * The normals are expressed in the mesh local space.
  13767. */
  13768. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13769. if (!this._facetNormals) {
  13770. this.updateFacetData();
  13771. }
  13772. return this._facetNormals;
  13773. };
  13774. /**
  13775. * Returns the facetLocalPositions array.
  13776. * The facet positions are expressed in the mesh local space.
  13777. */
  13778. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13779. if (!this._facetPositions) {
  13780. this.updateFacetData();
  13781. }
  13782. return this._facetPositions;
  13783. };
  13784. /**
  13785. * Returns the facetLocalPartioning array.
  13786. */
  13787. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13788. if (!this._facetPartitioning) {
  13789. this.updateFacetData();
  13790. }
  13791. return this._facetPartitioning;
  13792. };
  13793. /**
  13794. * Returns the i-th facet position in the world system.
  13795. * This method allocates a new Vector3 per call.
  13796. */
  13797. AbstractMesh.prototype.getFacetPosition = function (i) {
  13798. var pos = BABYLON.Vector3.Zero();
  13799. this.getFacetPositionToRef(i, pos);
  13800. return pos;
  13801. };
  13802. /**
  13803. * Sets the reference Vector3 with the i-th facet position in the world system.
  13804. * Returns the AbstractMesh.
  13805. */
  13806. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13807. var localPos = (this.getFacetLocalPositions())[i];
  13808. var world = this.getWorldMatrix();
  13809. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13810. return this;
  13811. };
  13812. /**
  13813. * Returns the i-th facet normal in the world system.
  13814. * This method allocates a new Vector3 per call.
  13815. */
  13816. AbstractMesh.prototype.getFacetNormal = function (i) {
  13817. var norm = BABYLON.Vector3.Zero();
  13818. this.getFacetNormalToRef(i, norm);
  13819. return norm;
  13820. };
  13821. /**
  13822. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13823. * Returns the AbstractMesh.
  13824. */
  13825. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13826. var localNorm = (this.getFacetLocalNormals())[i];
  13827. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13828. return this;
  13829. };
  13830. /**
  13831. * 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).
  13832. */
  13833. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13834. var bInfo = this.getBoundingInfo();
  13835. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13836. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13837. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13838. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13839. return null;
  13840. }
  13841. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13842. };
  13843. /**
  13844. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13845. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13846. * 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.
  13847. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13848. * 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.
  13849. */
  13850. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13851. if (checkFace === void 0) { checkFace = false; }
  13852. if (facing === void 0) { facing = true; }
  13853. var world = this.getWorldMatrix();
  13854. var invMat = BABYLON.Tmp.Matrix[5];
  13855. world.invertToRef(invMat);
  13856. var invVect = BABYLON.Tmp.Vector3[8];
  13857. var closest = null;
  13858. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13859. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13860. if (projected) {
  13861. // tranform the local computed projected vector to world coordinates
  13862. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13863. }
  13864. return closest;
  13865. };
  13866. /**
  13867. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13868. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13869. * 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.
  13870. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13871. * 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.
  13872. */
  13873. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13874. if (checkFace === void 0) { checkFace = false; }
  13875. if (facing === void 0) { facing = true; }
  13876. var closest = null;
  13877. var tmpx = 0.0;
  13878. var tmpy = 0.0;
  13879. var tmpz = 0.0;
  13880. var d = 0.0; // tmp dot facet normal * facet position
  13881. var t0 = 0.0;
  13882. var projx = 0.0;
  13883. var projy = 0.0;
  13884. var projz = 0.0;
  13885. // Get all the facets in the same partitioning block than (x, y, z)
  13886. var facetPositions = this.getFacetLocalPositions();
  13887. var facetNormals = this.getFacetLocalNormals();
  13888. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13889. if (!facetsInBlock) {
  13890. return null;
  13891. }
  13892. // Get the closest facet to (x, y, z)
  13893. var shortest = Number.MAX_VALUE; // init distance vars
  13894. var tmpDistance = shortest;
  13895. var fib; // current facet in the block
  13896. var norm; // current facet normal
  13897. var p0; // current facet barycenter position
  13898. // loop on all the facets in the current partitioning block
  13899. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13900. fib = facetsInBlock[idx];
  13901. norm = facetNormals[fib];
  13902. p0 = facetPositions[fib];
  13903. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13904. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13905. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13906. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13907. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13908. projx = x + norm.x * t0;
  13909. projy = y + norm.y * t0;
  13910. projz = z + norm.z * t0;
  13911. tmpx = projx - x;
  13912. tmpy = projy - y;
  13913. tmpz = projz - z;
  13914. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13915. if (tmpDistance < shortest) {
  13916. shortest = tmpDistance;
  13917. closest = fib;
  13918. if (projected) {
  13919. projected.x = projx;
  13920. projected.y = projy;
  13921. projected.z = projz;
  13922. }
  13923. }
  13924. }
  13925. }
  13926. return closest;
  13927. };
  13928. /**
  13929. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13930. */
  13931. AbstractMesh.prototype.getFacetDataParameters = function () {
  13932. return this._facetParameters;
  13933. };
  13934. /**
  13935. * Disables the feature FacetData and frees the related memory.
  13936. * Returns the AbstractMesh.
  13937. */
  13938. AbstractMesh.prototype.disableFacetData = function () {
  13939. if (this._facetDataEnabled) {
  13940. this._facetDataEnabled = false;
  13941. this._facetPositions = null;
  13942. this._facetNormals = null;
  13943. this._facetPartitioning = null;
  13944. this._facetParameters = null;
  13945. }
  13946. return this;
  13947. };
  13948. /**
  13949. * Creates new normals data for the mesh.
  13950. * @param updatable.
  13951. */
  13952. AbstractMesh.prototype.createNormals = function (updatable) {
  13953. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13954. var indices = this.getIndices();
  13955. var normals;
  13956. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13957. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13958. }
  13959. else {
  13960. normals = [];
  13961. }
  13962. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13963. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13964. };
  13965. AbstractMesh.prototype.checkOcclusionQuery = function () {
  13966. var engine = this.getEngine();
  13967. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  13968. this._isOccluded = false;
  13969. return;
  13970. }
  13971. if (this.isOcclusionQueryInProgress) {
  13972. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  13973. if (isOcclusionQueryAvailable) {
  13974. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  13975. this._isOcclusionQueryInProgress = false;
  13976. this._occlusionInternalRetryCounter = 0;
  13977. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  13978. }
  13979. else {
  13980. this._occlusionInternalRetryCounter++;
  13981. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  13982. this._isOcclusionQueryInProgress = false;
  13983. this._occlusionInternalRetryCounter = 0;
  13984. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  13985. // if strict continue the last state of the object.
  13986. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  13987. }
  13988. else {
  13989. return;
  13990. }
  13991. }
  13992. }
  13993. var scene = this.getScene();
  13994. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  13995. if (!this._occlusionQuery) {
  13996. this._occlusionQuery = engine.createQuery();
  13997. }
  13998. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  13999. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14000. engine.endQuery(this.occlusionQueryAlgorithmType);
  14001. this._isOcclusionQueryInProgress = true;
  14002. };
  14003. // Statics
  14004. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14005. AbstractMesh._BILLBOARDMODE_X = 1;
  14006. AbstractMesh._BILLBOARDMODE_Y = 2;
  14007. AbstractMesh._BILLBOARDMODE_Z = 4;
  14008. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14009. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14010. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14011. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14012. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14013. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14014. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14015. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14016. return AbstractMesh;
  14017. }(BABYLON.Node));
  14018. BABYLON.AbstractMesh = AbstractMesh;
  14019. })(BABYLON || (BABYLON = {}));
  14020. //# sourceMappingURL=babylon.abstractMesh.js.map
  14021. var BABYLON;
  14022. (function (BABYLON) {
  14023. var Light = (function (_super) {
  14024. __extends(Light, _super);
  14025. /**
  14026. * Creates a Light object in the scene.
  14027. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14028. */
  14029. function Light(name, scene) {
  14030. var _this = _super.call(this, name, scene) || this;
  14031. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14032. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14033. _this.intensity = 1.0;
  14034. _this.range = Number.MAX_VALUE;
  14035. /**
  14036. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14037. * of light.
  14038. */
  14039. _this._photometricScale = 1.0;
  14040. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14041. _this._radius = 0.00001;
  14042. _this.renderPriority = 0;
  14043. /**
  14044. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14045. * the current shadow generator.
  14046. */
  14047. _this.shadowEnabled = true;
  14048. _this._excludeWithLayerMask = 0;
  14049. _this._includeOnlyWithLayerMask = 0;
  14050. _this._lightmapMode = 0;
  14051. _this._excludedMeshesIds = new Array();
  14052. _this._includedOnlyMeshesIds = new Array();
  14053. _this.getScene().addLight(_this);
  14054. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14055. _this._buildUniformLayout();
  14056. _this.includedOnlyMeshes = new Array();
  14057. _this.excludedMeshes = new Array();
  14058. _this._resyncMeshes();
  14059. return _this;
  14060. }
  14061. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14062. /**
  14063. * If every light affecting the material is in this lightmapMode,
  14064. * material.lightmapTexture adds or multiplies
  14065. * (depends on material.useLightmapAsShadowmap)
  14066. * after every other light calculations.
  14067. */
  14068. get: function () {
  14069. return Light._LIGHTMAP_DEFAULT;
  14070. },
  14071. enumerable: true,
  14072. configurable: true
  14073. });
  14074. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14075. /**
  14076. * material.lightmapTexture as only diffuse lighting from this light
  14077. * adds pnly specular lighting from this light
  14078. * adds dynamic shadows
  14079. */
  14080. get: function () {
  14081. return Light._LIGHTMAP_SPECULAR;
  14082. },
  14083. enumerable: true,
  14084. configurable: true
  14085. });
  14086. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14087. /**
  14088. * material.lightmapTexture as only lighting
  14089. * no light calculation from this light
  14090. * only adds dynamic shadows from this light
  14091. */
  14092. get: function () {
  14093. return Light._LIGHTMAP_SHADOWSONLY;
  14094. },
  14095. enumerable: true,
  14096. configurable: true
  14097. });
  14098. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14099. /**
  14100. * Each light type uses the default quantity according to its type:
  14101. * point/spot lights use luminous intensity
  14102. * directional lights use illuminance
  14103. */
  14104. get: function () {
  14105. return Light._INTENSITYMODE_AUTOMATIC;
  14106. },
  14107. enumerable: true,
  14108. configurable: true
  14109. });
  14110. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14111. /**
  14112. * lumen (lm)
  14113. */
  14114. get: function () {
  14115. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14116. },
  14117. enumerable: true,
  14118. configurable: true
  14119. });
  14120. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14121. /**
  14122. * candela (lm/sr)
  14123. */
  14124. get: function () {
  14125. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14126. },
  14127. enumerable: true,
  14128. configurable: true
  14129. });
  14130. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14131. /**
  14132. * lux (lm/m^2)
  14133. */
  14134. get: function () {
  14135. return Light._INTENSITYMODE_ILLUMINANCE;
  14136. },
  14137. enumerable: true,
  14138. configurable: true
  14139. });
  14140. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14141. /**
  14142. * nit (cd/m^2)
  14143. */
  14144. get: function () {
  14145. return Light._INTENSITYMODE_LUMINANCE;
  14146. },
  14147. enumerable: true,
  14148. configurable: true
  14149. });
  14150. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14151. /**
  14152. * Light type const id of the point light.
  14153. */
  14154. get: function () {
  14155. return Light._LIGHTTYPEID_POINTLIGHT;
  14156. },
  14157. enumerable: true,
  14158. configurable: true
  14159. });
  14160. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14161. /**
  14162. * Light type const id of the directional light.
  14163. */
  14164. get: function () {
  14165. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14166. },
  14167. enumerable: true,
  14168. configurable: true
  14169. });
  14170. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14171. /**
  14172. * Light type const id of the spot light.
  14173. */
  14174. get: function () {
  14175. return Light._LIGHTTYPEID_SPOTLIGHT;
  14176. },
  14177. enumerable: true,
  14178. configurable: true
  14179. });
  14180. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14181. /**
  14182. * Light type const id of the hemispheric light.
  14183. */
  14184. get: function () {
  14185. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14186. },
  14187. enumerable: true,
  14188. configurable: true
  14189. });
  14190. Object.defineProperty(Light.prototype, "intensityMode", {
  14191. /**
  14192. * Gets the photometric scale used to interpret the intensity.
  14193. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14194. */
  14195. get: function () {
  14196. return this._intensityMode;
  14197. },
  14198. /**
  14199. * Sets the photometric scale used to interpret the intensity.
  14200. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14201. */
  14202. set: function (value) {
  14203. this._intensityMode = value;
  14204. this._computePhotometricScale();
  14205. },
  14206. enumerable: true,
  14207. configurable: true
  14208. });
  14209. ;
  14210. ;
  14211. Object.defineProperty(Light.prototype, "radius", {
  14212. /**
  14213. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14214. */
  14215. get: function () {
  14216. return this._radius;
  14217. },
  14218. /**
  14219. * sets the light radius used by PBR Materials to simulate soft area lights.
  14220. */
  14221. set: function (value) {
  14222. this._radius = value;
  14223. this._computePhotometricScale();
  14224. },
  14225. enumerable: true,
  14226. configurable: true
  14227. });
  14228. ;
  14229. ;
  14230. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14231. get: function () {
  14232. return this._includedOnlyMeshes;
  14233. },
  14234. set: function (value) {
  14235. this._includedOnlyMeshes = value;
  14236. this._hookArrayForIncludedOnly(value);
  14237. },
  14238. enumerable: true,
  14239. configurable: true
  14240. });
  14241. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14242. get: function () {
  14243. return this._excludedMeshes;
  14244. },
  14245. set: function (value) {
  14246. this._excludedMeshes = value;
  14247. this._hookArrayForExcluded(value);
  14248. },
  14249. enumerable: true,
  14250. configurable: true
  14251. });
  14252. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14253. get: function () {
  14254. return this._excludeWithLayerMask;
  14255. },
  14256. set: function (value) {
  14257. this._excludeWithLayerMask = value;
  14258. this._resyncMeshes();
  14259. },
  14260. enumerable: true,
  14261. configurable: true
  14262. });
  14263. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14264. get: function () {
  14265. return this._includeOnlyWithLayerMask;
  14266. },
  14267. set: function (value) {
  14268. this._includeOnlyWithLayerMask = value;
  14269. this._resyncMeshes();
  14270. },
  14271. enumerable: true,
  14272. configurable: true
  14273. });
  14274. Object.defineProperty(Light.prototype, "lightmapMode", {
  14275. get: function () {
  14276. return this._lightmapMode;
  14277. },
  14278. set: function (value) {
  14279. if (this._lightmapMode === value) {
  14280. return;
  14281. }
  14282. this._lightmapMode = value;
  14283. this._markMeshesAsLightDirty();
  14284. },
  14285. enumerable: true,
  14286. configurable: true
  14287. });
  14288. Light.prototype._buildUniformLayout = function () {
  14289. // Overridden
  14290. };
  14291. /**
  14292. * Returns the string "Light".
  14293. */
  14294. Light.prototype.getClassName = function () {
  14295. return "Light";
  14296. };
  14297. /**
  14298. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14299. */
  14300. Light.prototype.toString = function (fullDetails) {
  14301. var ret = "Name: " + this.name;
  14302. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14303. if (this.animations) {
  14304. for (var i = 0; i < this.animations.length; i++) {
  14305. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14306. }
  14307. }
  14308. if (fullDetails) {
  14309. }
  14310. return ret;
  14311. };
  14312. /**
  14313. * Set the enabled state of this node.
  14314. * @param {boolean} value - the new enabled state
  14315. * @see isEnabled
  14316. */
  14317. Light.prototype.setEnabled = function (value) {
  14318. _super.prototype.setEnabled.call(this, value);
  14319. this._resyncMeshes();
  14320. };
  14321. /**
  14322. * Returns the Light associated shadow generator.
  14323. */
  14324. Light.prototype.getShadowGenerator = function () {
  14325. return this._shadowGenerator;
  14326. };
  14327. /**
  14328. * Returns a Vector3, the absolute light position in the World.
  14329. */
  14330. Light.prototype.getAbsolutePosition = function () {
  14331. return BABYLON.Vector3.Zero();
  14332. };
  14333. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14334. };
  14335. Light.prototype._getWorldMatrix = function () {
  14336. return BABYLON.Matrix.Identity();
  14337. };
  14338. /**
  14339. * Boolean : True if the light will affect the passed mesh.
  14340. */
  14341. Light.prototype.canAffectMesh = function (mesh) {
  14342. if (!mesh) {
  14343. return true;
  14344. }
  14345. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14346. return false;
  14347. }
  14348. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14349. return false;
  14350. }
  14351. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14352. return false;
  14353. }
  14354. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14355. return false;
  14356. }
  14357. return true;
  14358. };
  14359. /**
  14360. * Returns the light World matrix.
  14361. */
  14362. Light.prototype.getWorldMatrix = function () {
  14363. this._currentRenderId = this.getScene().getRenderId();
  14364. var worldMatrix = this._getWorldMatrix();
  14365. if (this.parent && this.parent.getWorldMatrix) {
  14366. if (!this._parentedWorldMatrix) {
  14367. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14368. }
  14369. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14370. this._markSyncedWithParent();
  14371. return this._parentedWorldMatrix;
  14372. }
  14373. return worldMatrix;
  14374. };
  14375. /**
  14376. * Sort function to order lights for rendering.
  14377. * @param a First Light object to compare to second.
  14378. * @param b Second Light object to compare first.
  14379. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14380. */
  14381. Light.compareLightsPriority = function (a, b) {
  14382. //shadow-casting lights have priority over non-shadow-casting lights
  14383. //the renderPrioirty is a secondary sort criterion
  14384. if (a.shadowEnabled !== b.shadowEnabled) {
  14385. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14386. }
  14387. return b.renderPriority - a.renderPriority;
  14388. };
  14389. /**
  14390. * Disposes the light.
  14391. */
  14392. Light.prototype.dispose = function () {
  14393. if (this._shadowGenerator) {
  14394. this._shadowGenerator.dispose();
  14395. this._shadowGenerator = null;
  14396. }
  14397. // Animations
  14398. this.getScene().stopAnimation(this);
  14399. // Remove from meshes
  14400. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14401. var mesh = _a[_i];
  14402. mesh._removeLightSource(this);
  14403. }
  14404. this._uniformBuffer.dispose();
  14405. // Remove from scene
  14406. this.getScene().removeLight(this);
  14407. _super.prototype.dispose.call(this);
  14408. };
  14409. /**
  14410. * Returns the light type ID (integer).
  14411. */
  14412. Light.prototype.getTypeID = function () {
  14413. return 0;
  14414. };
  14415. /**
  14416. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14417. */
  14418. Light.prototype.getScaledIntensity = function () {
  14419. return this._photometricScale * this.intensity;
  14420. };
  14421. /**
  14422. * Returns a new Light object, named "name", from the current one.
  14423. */
  14424. Light.prototype.clone = function (name) {
  14425. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14426. };
  14427. /**
  14428. * Serializes the current light into a Serialization object.
  14429. * Returns the serialized object.
  14430. */
  14431. Light.prototype.serialize = function () {
  14432. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14433. // Type
  14434. serializationObject.type = this.getTypeID();
  14435. // Parent
  14436. if (this.parent) {
  14437. serializationObject.parentId = this.parent.id;
  14438. }
  14439. // Inclusion / exclusions
  14440. if (this.excludedMeshes.length > 0) {
  14441. serializationObject.excludedMeshesIds = [];
  14442. this.excludedMeshes.forEach(function (mesh) {
  14443. serializationObject.excludedMeshesIds.push(mesh.id);
  14444. });
  14445. }
  14446. if (this.includedOnlyMeshes.length > 0) {
  14447. serializationObject.includedOnlyMeshesIds = [];
  14448. this.includedOnlyMeshes.forEach(function (mesh) {
  14449. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14450. });
  14451. }
  14452. // Animations
  14453. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14454. serializationObject.ranges = this.serializeAnimationRanges();
  14455. return serializationObject;
  14456. };
  14457. /**
  14458. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14459. * This new light is named "name" and added to the passed scene.
  14460. */
  14461. Light.GetConstructorFromName = function (type, name, scene) {
  14462. switch (type) {
  14463. case 0:
  14464. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14465. case 1:
  14466. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14467. case 2:
  14468. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14469. case 3:
  14470. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14471. }
  14472. };
  14473. /**
  14474. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14475. */
  14476. Light.Parse = function (parsedLight, scene) {
  14477. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14478. // Inclusion / exclusions
  14479. if (parsedLight.excludedMeshesIds) {
  14480. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14481. }
  14482. if (parsedLight.includedOnlyMeshesIds) {
  14483. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14484. }
  14485. // Parent
  14486. if (parsedLight.parentId) {
  14487. light._waitingParentId = parsedLight.parentId;
  14488. }
  14489. // Animations
  14490. if (parsedLight.animations) {
  14491. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14492. var parsedAnimation = parsedLight.animations[animationIndex];
  14493. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14494. }
  14495. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14496. }
  14497. if (parsedLight.autoAnimate) {
  14498. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14499. }
  14500. return light;
  14501. };
  14502. Light.prototype._hookArrayForExcluded = function (array) {
  14503. var _this = this;
  14504. var oldPush = array.push;
  14505. array.push = function () {
  14506. var items = [];
  14507. for (var _i = 0; _i < arguments.length; _i++) {
  14508. items[_i] = arguments[_i];
  14509. }
  14510. var result = oldPush.apply(array, items);
  14511. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14512. var item = items_1[_a];
  14513. item._resyncLighSource(_this);
  14514. }
  14515. return result;
  14516. };
  14517. var oldSplice = array.splice;
  14518. array.splice = function (index, deleteCount) {
  14519. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14520. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14521. var item = deleted_1[_i];
  14522. item._resyncLighSource(_this);
  14523. }
  14524. return deleted;
  14525. };
  14526. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14527. var item = array_1[_i];
  14528. item._resyncLighSource(this);
  14529. }
  14530. };
  14531. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14532. var _this = this;
  14533. var oldPush = array.push;
  14534. array.push = function () {
  14535. var items = [];
  14536. for (var _i = 0; _i < arguments.length; _i++) {
  14537. items[_i] = arguments[_i];
  14538. }
  14539. var result = oldPush.apply(array, items);
  14540. _this._resyncMeshes();
  14541. return result;
  14542. };
  14543. var oldSplice = array.splice;
  14544. array.splice = function (index, deleteCount) {
  14545. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14546. _this._resyncMeshes();
  14547. return deleted;
  14548. };
  14549. this._resyncMeshes();
  14550. };
  14551. Light.prototype._resyncMeshes = function () {
  14552. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14553. var mesh = _a[_i];
  14554. mesh._resyncLighSource(this);
  14555. }
  14556. };
  14557. Light.prototype._markMeshesAsLightDirty = function () {
  14558. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14559. var mesh = _a[_i];
  14560. if (mesh._lightSources.indexOf(this) !== -1) {
  14561. mesh._markSubMeshesAsLightDirty();
  14562. }
  14563. }
  14564. };
  14565. /**
  14566. * Recomputes the cached photometric scale if needed.
  14567. */
  14568. Light.prototype._computePhotometricScale = function () {
  14569. this._photometricScale = this._getPhotometricScale();
  14570. this.getScene().resetCachedMaterial();
  14571. };
  14572. /**
  14573. * Returns the Photometric Scale according to the light type and intensity mode.
  14574. */
  14575. Light.prototype._getPhotometricScale = function () {
  14576. var photometricScale = 0.0;
  14577. var lightTypeID = this.getTypeID();
  14578. //get photometric mode
  14579. var photometricMode = this.intensityMode;
  14580. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14581. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14582. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14583. }
  14584. else {
  14585. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14586. }
  14587. }
  14588. //compute photometric scale
  14589. switch (lightTypeID) {
  14590. case Light.LIGHTTYPEID_POINTLIGHT:
  14591. case Light.LIGHTTYPEID_SPOTLIGHT:
  14592. switch (photometricMode) {
  14593. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14594. photometricScale = 1.0 / (4.0 * Math.PI);
  14595. break;
  14596. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14597. photometricScale = 1.0;
  14598. break;
  14599. case Light.INTENSITYMODE_LUMINANCE:
  14600. photometricScale = this.radius * this.radius;
  14601. break;
  14602. }
  14603. break;
  14604. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14605. switch (photometricMode) {
  14606. case Light.INTENSITYMODE_ILLUMINANCE:
  14607. photometricScale = 1.0;
  14608. break;
  14609. case Light.INTENSITYMODE_LUMINANCE:
  14610. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14611. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14612. var apexAngleRadians = this.radius;
  14613. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14614. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14615. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14616. photometricScale = solidAngle;
  14617. break;
  14618. }
  14619. break;
  14620. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14621. // No fall off in hemisperic light.
  14622. photometricScale = 1.0;
  14623. break;
  14624. }
  14625. return photometricScale;
  14626. };
  14627. Light.prototype._reorderLightsInScene = function () {
  14628. var scene = this.getScene();
  14629. if (this.renderPriority != 0) {
  14630. scene.requireLightSorting = true;
  14631. }
  14632. this.getScene().sortLightsByPriority();
  14633. };
  14634. //lightmapMode Consts
  14635. Light._LIGHTMAP_DEFAULT = 0;
  14636. Light._LIGHTMAP_SPECULAR = 1;
  14637. Light._LIGHTMAP_SHADOWSONLY = 2;
  14638. // Intensity Mode Consts
  14639. Light._INTENSITYMODE_AUTOMATIC = 0;
  14640. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14641. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14642. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14643. Light._INTENSITYMODE_LUMINANCE = 4;
  14644. // Light types ids const.
  14645. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14646. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14647. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14648. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14649. __decorate([
  14650. BABYLON.serializeAsColor3()
  14651. ], Light.prototype, "diffuse", void 0);
  14652. __decorate([
  14653. BABYLON.serializeAsColor3()
  14654. ], Light.prototype, "specular", void 0);
  14655. __decorate([
  14656. BABYLON.serialize()
  14657. ], Light.prototype, "intensity", void 0);
  14658. __decorate([
  14659. BABYLON.serialize()
  14660. ], Light.prototype, "range", void 0);
  14661. __decorate([
  14662. BABYLON.serialize()
  14663. ], Light.prototype, "intensityMode", null);
  14664. __decorate([
  14665. BABYLON.serialize()
  14666. ], Light.prototype, "radius", null);
  14667. __decorate([
  14668. BABYLON.serialize()
  14669. ], Light.prototype, "_renderPriority", void 0);
  14670. __decorate([
  14671. BABYLON.expandToProperty("_reorderLightsInScene")
  14672. ], Light.prototype, "renderPriority", void 0);
  14673. __decorate([
  14674. BABYLON.serialize()
  14675. ], Light.prototype, "shadowEnabled", void 0);
  14676. __decorate([
  14677. BABYLON.serialize("excludeWithLayerMask")
  14678. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14679. __decorate([
  14680. BABYLON.serialize("includeOnlyWithLayerMask")
  14681. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14682. __decorate([
  14683. BABYLON.serialize("lightmapMode")
  14684. ], Light.prototype, "_lightmapMode", void 0);
  14685. return Light;
  14686. }(BABYLON.Node));
  14687. BABYLON.Light = Light;
  14688. })(BABYLON || (BABYLON = {}));
  14689. //# sourceMappingURL=babylon.light.js.map
  14690. var BABYLON;
  14691. (function (BABYLON) {
  14692. var Camera = (function (_super) {
  14693. __extends(Camera, _super);
  14694. function Camera(name, position, scene) {
  14695. var _this = _super.call(this, name, scene) || this;
  14696. _this.upVector = BABYLON.Vector3.Up();
  14697. _this.orthoLeft = null;
  14698. _this.orthoRight = null;
  14699. _this.orthoBottom = null;
  14700. _this.orthoTop = null;
  14701. _this.fov = 0.8;
  14702. _this.minZ = 1;
  14703. _this.maxZ = 10000.0;
  14704. _this.inertia = 0.9;
  14705. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14706. _this.isIntermediate = false;
  14707. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14708. _this.layerMask = 0x0FFFFFFF;
  14709. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14710. // Camera rig members
  14711. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14712. _this._rigCameras = new Array();
  14713. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14714. _this.customRenderTargets = new Array();
  14715. // Observables
  14716. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14717. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14718. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14719. // Cache
  14720. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14721. _this._projectionMatrix = new BABYLON.Matrix();
  14722. _this._doNotComputeProjectionMatrix = false;
  14723. _this._postProcesses = new Array();
  14724. _this._transformMatrix = BABYLON.Matrix.Zero();
  14725. _this._activeMeshes = new BABYLON.SmartArray(256);
  14726. _this._globalPosition = BABYLON.Vector3.Zero();
  14727. _this._refreshFrustumPlanes = true;
  14728. _this.getScene().addCamera(_this);
  14729. if (!_this.getScene().activeCamera) {
  14730. _this.getScene().activeCamera = _this;
  14731. }
  14732. _this.position = position;
  14733. return _this;
  14734. }
  14735. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14736. get: function () {
  14737. return Camera._PERSPECTIVE_CAMERA;
  14738. },
  14739. enumerable: true,
  14740. configurable: true
  14741. });
  14742. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14743. get: function () {
  14744. return Camera._ORTHOGRAPHIC_CAMERA;
  14745. },
  14746. enumerable: true,
  14747. configurable: true
  14748. });
  14749. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14750. get: function () {
  14751. return Camera._FOVMODE_VERTICAL_FIXED;
  14752. },
  14753. enumerable: true,
  14754. configurable: true
  14755. });
  14756. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14757. get: function () {
  14758. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14759. },
  14760. enumerable: true,
  14761. configurable: true
  14762. });
  14763. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14764. get: function () {
  14765. return Camera._RIG_MODE_NONE;
  14766. },
  14767. enumerable: true,
  14768. configurable: true
  14769. });
  14770. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14771. get: function () {
  14772. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14773. },
  14774. enumerable: true,
  14775. configurable: true
  14776. });
  14777. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14778. get: function () {
  14779. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14780. },
  14781. enumerable: true,
  14782. configurable: true
  14783. });
  14784. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14785. get: function () {
  14786. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14787. },
  14788. enumerable: true,
  14789. configurable: true
  14790. });
  14791. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14792. get: function () {
  14793. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14794. },
  14795. enumerable: true,
  14796. configurable: true
  14797. });
  14798. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14799. get: function () {
  14800. return Camera._RIG_MODE_VR;
  14801. },
  14802. enumerable: true,
  14803. configurable: true
  14804. });
  14805. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14806. get: function () {
  14807. return Camera._RIG_MODE_WEBVR;
  14808. },
  14809. enumerable: true,
  14810. configurable: true
  14811. });
  14812. Camera.prototype.getClassName = function () {
  14813. return "Camera";
  14814. };
  14815. /**
  14816. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14817. */
  14818. Camera.prototype.toString = function (fullDetails) {
  14819. var ret = "Name: " + this.name;
  14820. ret += ", type: " + this.getClassName();
  14821. if (this.animations) {
  14822. for (var i = 0; i < this.animations.length; i++) {
  14823. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14824. }
  14825. }
  14826. if (fullDetails) {
  14827. }
  14828. return ret;
  14829. };
  14830. Object.defineProperty(Camera.prototype, "globalPosition", {
  14831. get: function () {
  14832. return this._globalPosition;
  14833. },
  14834. enumerable: true,
  14835. configurable: true
  14836. });
  14837. Camera.prototype.getActiveMeshes = function () {
  14838. return this._activeMeshes;
  14839. };
  14840. Camera.prototype.isActiveMesh = function (mesh) {
  14841. return (this._activeMeshes.indexOf(mesh) !== -1);
  14842. };
  14843. //Cache
  14844. Camera.prototype._initCache = function () {
  14845. _super.prototype._initCache.call(this);
  14846. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14847. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14848. this._cache.mode = undefined;
  14849. this._cache.minZ = undefined;
  14850. this._cache.maxZ = undefined;
  14851. this._cache.fov = undefined;
  14852. this._cache.fovMode = undefined;
  14853. this._cache.aspectRatio = undefined;
  14854. this._cache.orthoLeft = undefined;
  14855. this._cache.orthoRight = undefined;
  14856. this._cache.orthoBottom = undefined;
  14857. this._cache.orthoTop = undefined;
  14858. this._cache.renderWidth = undefined;
  14859. this._cache.renderHeight = undefined;
  14860. };
  14861. Camera.prototype._updateCache = function (ignoreParentClass) {
  14862. if (!ignoreParentClass) {
  14863. _super.prototype._updateCache.call(this);
  14864. }
  14865. var engine = this.getEngine();
  14866. this._cache.position.copyFrom(this.position);
  14867. this._cache.upVector.copyFrom(this.upVector);
  14868. this._cache.mode = this.mode;
  14869. this._cache.minZ = this.minZ;
  14870. this._cache.maxZ = this.maxZ;
  14871. this._cache.fov = this.fov;
  14872. this._cache.fovMode = this.fovMode;
  14873. this._cache.aspectRatio = engine.getAspectRatio(this);
  14874. this._cache.orthoLeft = this.orthoLeft;
  14875. this._cache.orthoRight = this.orthoRight;
  14876. this._cache.orthoBottom = this.orthoBottom;
  14877. this._cache.orthoTop = this.orthoTop;
  14878. this._cache.renderWidth = engine.getRenderWidth();
  14879. this._cache.renderHeight = engine.getRenderHeight();
  14880. };
  14881. Camera.prototype._updateFromScene = function () {
  14882. this.updateCache();
  14883. this.update();
  14884. };
  14885. // Synchronized
  14886. Camera.prototype._isSynchronized = function () {
  14887. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14888. };
  14889. Camera.prototype._isSynchronizedViewMatrix = function () {
  14890. if (!_super.prototype._isSynchronized.call(this))
  14891. return false;
  14892. return this._cache.position.equals(this.position)
  14893. && this._cache.upVector.equals(this.upVector)
  14894. && this.isSynchronizedWithParent();
  14895. };
  14896. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14897. var check = this._cache.mode === this.mode
  14898. && this._cache.minZ === this.minZ
  14899. && this._cache.maxZ === this.maxZ;
  14900. if (!check) {
  14901. return false;
  14902. }
  14903. var engine = this.getEngine();
  14904. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14905. check = this._cache.fov === this.fov
  14906. && this._cache.fovMode === this.fovMode
  14907. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14908. }
  14909. else {
  14910. check = this._cache.orthoLeft === this.orthoLeft
  14911. && this._cache.orthoRight === this.orthoRight
  14912. && this._cache.orthoBottom === this.orthoBottom
  14913. && this._cache.orthoTop === this.orthoTop
  14914. && this._cache.renderWidth === engine.getRenderWidth()
  14915. && this._cache.renderHeight === engine.getRenderHeight();
  14916. }
  14917. return check;
  14918. };
  14919. // Controls
  14920. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14921. };
  14922. Camera.prototype.detachControl = function (element) {
  14923. };
  14924. Camera.prototype.update = function () {
  14925. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14926. this._updateRigCameras();
  14927. }
  14928. this._checkInputs();
  14929. };
  14930. Camera.prototype._checkInputs = function () {
  14931. this.onAfterCheckInputsObservable.notifyObservers(this);
  14932. };
  14933. Object.defineProperty(Camera.prototype, "rigCameras", {
  14934. get: function () {
  14935. return this._rigCameras;
  14936. },
  14937. enumerable: true,
  14938. configurable: true
  14939. });
  14940. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14941. get: function () {
  14942. return this._rigPostProcess;
  14943. },
  14944. enumerable: true,
  14945. configurable: true
  14946. });
  14947. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14948. // invalidate framebuffer
  14949. if (this._postProcesses.length > 0) {
  14950. this._postProcesses[0].markTextureDirty();
  14951. }
  14952. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14953. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14954. var cam = this._rigCameras[i];
  14955. var rigPostProcess = cam._rigPostProcess;
  14956. // for VR rig, there does not have to be a post process
  14957. if (rigPostProcess) {
  14958. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14959. if (isPass) {
  14960. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14961. cam.isIntermediate = this._postProcesses.length === 0;
  14962. }
  14963. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14964. rigPostProcess.markTextureDirty();
  14965. }
  14966. else {
  14967. cam._postProcesses = this._postProcesses.slice(0);
  14968. }
  14969. }
  14970. };
  14971. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14972. if (insertAt === void 0) { insertAt = null; }
  14973. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14974. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14975. return 0;
  14976. }
  14977. if (insertAt == null || insertAt < 0) {
  14978. this._postProcesses.push(postProcess);
  14979. }
  14980. else {
  14981. this._postProcesses.splice(insertAt, 0, postProcess);
  14982. }
  14983. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14984. return this._postProcesses.indexOf(postProcess);
  14985. };
  14986. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14987. if (atIndices === void 0) { atIndices = null; }
  14988. var result = [];
  14989. var i;
  14990. var index;
  14991. if (!atIndices) {
  14992. var idx = this._postProcesses.indexOf(postProcess);
  14993. if (idx !== -1) {
  14994. this._postProcesses.splice(idx, 1);
  14995. }
  14996. }
  14997. else {
  14998. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14999. // iterate descending, so can just splice as we go
  15000. for (i = atIndices.length - 1; i >= 0; i--) {
  15001. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15002. result.push(i);
  15003. continue;
  15004. }
  15005. index = atIndices[i];
  15006. this._postProcesses.splice(index, 1);
  15007. }
  15008. }
  15009. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15010. return result;
  15011. };
  15012. Camera.prototype.getWorldMatrix = function () {
  15013. if (!this._worldMatrix) {
  15014. this._worldMatrix = BABYLON.Matrix.Identity();
  15015. }
  15016. var viewMatrix = this.getViewMatrix();
  15017. viewMatrix.invertToRef(this._worldMatrix);
  15018. return this._worldMatrix;
  15019. };
  15020. Camera.prototype._getViewMatrix = function () {
  15021. return BABYLON.Matrix.Identity();
  15022. };
  15023. Camera.prototype.getViewMatrix = function (force) {
  15024. if (!force && this._isSynchronizedViewMatrix()) {
  15025. return this._computedViewMatrix;
  15026. }
  15027. this._computedViewMatrix = this._getViewMatrix();
  15028. this._currentRenderId = this.getScene().getRenderId();
  15029. this._refreshFrustumPlanes = true;
  15030. if (!this.parent || !this.parent.getWorldMatrix) {
  15031. this._globalPosition.copyFrom(this.position);
  15032. }
  15033. else {
  15034. if (!this._worldMatrix) {
  15035. this._worldMatrix = BABYLON.Matrix.Identity();
  15036. }
  15037. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15038. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15039. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15040. this._computedViewMatrix.invert();
  15041. this._markSyncedWithParent();
  15042. }
  15043. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15044. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15045. }
  15046. this.onViewMatrixChangedObservable.notifyObservers(this);
  15047. return this._computedViewMatrix;
  15048. };
  15049. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15050. this._doNotComputeProjectionMatrix = true;
  15051. if (projection !== undefined) {
  15052. this._projectionMatrix = projection;
  15053. }
  15054. };
  15055. ;
  15056. Camera.prototype.unfreezeProjectionMatrix = function () {
  15057. this._doNotComputeProjectionMatrix = false;
  15058. };
  15059. ;
  15060. Camera.prototype.getProjectionMatrix = function (force) {
  15061. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15062. return this._projectionMatrix;
  15063. }
  15064. this._refreshFrustumPlanes = true;
  15065. var engine = this.getEngine();
  15066. var scene = this.getScene();
  15067. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15068. if (this.minZ <= 0) {
  15069. this.minZ = 0.1;
  15070. }
  15071. if (scene.useRightHandedSystem) {
  15072. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15073. }
  15074. else {
  15075. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15076. }
  15077. }
  15078. else {
  15079. var halfWidth = engine.getRenderWidth() / 2.0;
  15080. var halfHeight = engine.getRenderHeight() / 2.0;
  15081. if (scene.useRightHandedSystem) {
  15082. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15083. }
  15084. else {
  15085. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15086. }
  15087. }
  15088. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15089. return this._projectionMatrix;
  15090. };
  15091. Camera.prototype.getTranformationMatrix = function () {
  15092. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15093. return this._transformMatrix;
  15094. };
  15095. Camera.prototype.updateFrustumPlanes = function () {
  15096. if (!this._refreshFrustumPlanes) {
  15097. return;
  15098. }
  15099. this.getTranformationMatrix();
  15100. if (!this._frustumPlanes) {
  15101. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15102. }
  15103. else {
  15104. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15105. }
  15106. this._refreshFrustumPlanes = false;
  15107. };
  15108. Camera.prototype.isInFrustum = function (target) {
  15109. this.updateFrustumPlanes();
  15110. return target.isInFrustum(this._frustumPlanes);
  15111. };
  15112. Camera.prototype.isCompletelyInFrustum = function (target) {
  15113. this.updateFrustumPlanes();
  15114. return target.isCompletelyInFrustum(this._frustumPlanes);
  15115. };
  15116. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15117. if (length === void 0) { length = 100; }
  15118. if (!transform) {
  15119. transform = this.getWorldMatrix();
  15120. }
  15121. if (!origin) {
  15122. origin = this.position;
  15123. }
  15124. var forward = new BABYLON.Vector3(0, 0, 1);
  15125. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15126. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15127. return new BABYLON.Ray(origin, direction, length);
  15128. };
  15129. Camera.prototype.dispose = function () {
  15130. // Observables
  15131. this.onViewMatrixChangedObservable.clear();
  15132. this.onProjectionMatrixChangedObservable.clear();
  15133. this.onAfterCheckInputsObservable.clear();
  15134. // Inputs
  15135. if (this.inputs) {
  15136. this.inputs.clear();
  15137. }
  15138. // Animations
  15139. this.getScene().stopAnimation(this);
  15140. // Remove from scene
  15141. this.getScene().removeCamera(this);
  15142. while (this._rigCameras.length > 0) {
  15143. this._rigCameras.pop().dispose();
  15144. }
  15145. // Postprocesses
  15146. var i = this._postProcesses.length;
  15147. while (--i >= 0) {
  15148. this._postProcesses[i].dispose(this);
  15149. }
  15150. // Render targets
  15151. var i = this.customRenderTargets.length;
  15152. while (--i >= 0) {
  15153. this.customRenderTargets[i].dispose();
  15154. }
  15155. this.customRenderTargets = [];
  15156. // Active Meshes
  15157. this._activeMeshes.dispose();
  15158. _super.prototype.dispose.call(this);
  15159. };
  15160. Object.defineProperty(Camera.prototype, "leftCamera", {
  15161. // ---- Camera rigs section ----
  15162. get: function () {
  15163. if (this._rigCameras.length < 1) {
  15164. return undefined;
  15165. }
  15166. return this._rigCameras[0];
  15167. },
  15168. enumerable: true,
  15169. configurable: true
  15170. });
  15171. Object.defineProperty(Camera.prototype, "rightCamera", {
  15172. get: function () {
  15173. if (this._rigCameras.length < 2) {
  15174. return undefined;
  15175. }
  15176. return this._rigCameras[1];
  15177. },
  15178. enumerable: true,
  15179. configurable: true
  15180. });
  15181. Camera.prototype.getLeftTarget = function () {
  15182. if (this._rigCameras.length < 1) {
  15183. return undefined;
  15184. }
  15185. return this._rigCameras[0].getTarget();
  15186. };
  15187. Camera.prototype.getRightTarget = function () {
  15188. if (this._rigCameras.length < 2) {
  15189. return undefined;
  15190. }
  15191. return this._rigCameras[1].getTarget();
  15192. };
  15193. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15194. while (this._rigCameras.length > 0) {
  15195. this._rigCameras.pop().dispose();
  15196. }
  15197. this.cameraRigMode = mode;
  15198. this._cameraRigParams = {};
  15199. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15200. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15201. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15202. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15203. // create the rig cameras, unless none
  15204. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15205. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15206. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15207. }
  15208. switch (this.cameraRigMode) {
  15209. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15210. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15211. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15212. break;
  15213. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15214. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15215. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15216. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15217. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15218. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15219. break;
  15220. case Camera.RIG_MODE_VR:
  15221. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15222. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15223. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15224. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15225. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15226. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15227. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15228. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15229. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15230. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15231. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15232. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15233. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15234. if (metrics.compensateDistortion) {
  15235. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15236. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15237. }
  15238. break;
  15239. case Camera.RIG_MODE_WEBVR:
  15240. if (rigParams.vrDisplay) {
  15241. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15242. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15243. //Left eye
  15244. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15245. this._rigCameras[0].setCameraRigParameter("left", true);
  15246. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15247. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15248. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15249. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15250. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15251. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15252. this._rigCameras[0].parent = this;
  15253. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15254. //Right eye
  15255. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15256. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15257. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15258. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15259. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15260. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15261. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15262. this._rigCameras[1].parent = this;
  15263. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15264. }
  15265. break;
  15266. }
  15267. this._cascadePostProcessesToRigCams();
  15268. this.
  15269. update();
  15270. };
  15271. Camera.prototype._getVRProjectionMatrix = function () {
  15272. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15273. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15274. return this._projectionMatrix;
  15275. };
  15276. Camera.prototype._updateCameraRotationMatrix = function () {
  15277. //Here for WebVR
  15278. };
  15279. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15280. //Here for WebVR
  15281. };
  15282. /**
  15283. * This function MUST be overwritten by the different WebVR cameras available.
  15284. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15285. */
  15286. Camera.prototype._getWebVRProjectionMatrix = function () {
  15287. return BABYLON.Matrix.Identity();
  15288. };
  15289. /**
  15290. * This function MUST be overwritten by the different WebVR cameras available.
  15291. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15292. */
  15293. Camera.prototype._getWebVRViewMatrix = function () {
  15294. return BABYLON.Matrix.Identity();
  15295. };
  15296. Camera.prototype.setCameraRigParameter = function (name, value) {
  15297. if (!this._cameraRigParams) {
  15298. this._cameraRigParams = {};
  15299. }
  15300. this._cameraRigParams[name] = value;
  15301. //provisionnally:
  15302. if (name === "interaxialDistance") {
  15303. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15304. }
  15305. };
  15306. /**
  15307. * needs to be overridden by children so sub has required properties to be copied
  15308. */
  15309. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15310. return null;
  15311. };
  15312. /**
  15313. * May need to be overridden by children
  15314. */
  15315. Camera.prototype._updateRigCameras = function () {
  15316. for (var i = 0; i < this._rigCameras.length; i++) {
  15317. this._rigCameras[i].minZ = this.minZ;
  15318. this._rigCameras[i].maxZ = this.maxZ;
  15319. this._rigCameras[i].fov = this.fov;
  15320. }
  15321. // only update viewport when ANAGLYPH
  15322. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15323. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15324. }
  15325. };
  15326. Camera.prototype._setupInputs = function () {
  15327. };
  15328. Camera.prototype.serialize = function () {
  15329. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15330. // Type
  15331. serializationObject.type = this.getClassName();
  15332. // Parent
  15333. if (this.parent) {
  15334. serializationObject.parentId = this.parent.id;
  15335. }
  15336. if (this.inputs) {
  15337. this.inputs.serialize(serializationObject);
  15338. }
  15339. // Animations
  15340. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15341. serializationObject.ranges = this.serializeAnimationRanges();
  15342. return serializationObject;
  15343. };
  15344. Camera.prototype.clone = function (name) {
  15345. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15346. };
  15347. Camera.prototype.getDirection = function (localAxis) {
  15348. var result = BABYLON.Vector3.Zero();
  15349. this.getDirectionToRef(localAxis, result);
  15350. return result;
  15351. };
  15352. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15353. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15354. };
  15355. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15356. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15357. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15358. switch (type) {
  15359. case "ArcRotateCamera":
  15360. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15361. case "DeviceOrientationCamera":
  15362. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15363. case "FollowCamera":
  15364. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15365. case "ArcFollowCamera":
  15366. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15367. case "GamepadCamera":
  15368. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15369. case "TouchCamera":
  15370. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15371. case "VirtualJoysticksCamera":
  15372. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15373. case "WebVRFreeCamera":
  15374. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15375. case "WebVRGamepadCamera":
  15376. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15377. case "VRDeviceOrientationFreeCamera":
  15378. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15379. case "VRDeviceOrientationGamepadCamera":
  15380. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15381. case "AnaglyphArcRotateCamera":
  15382. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15383. case "AnaglyphFreeCamera":
  15384. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15385. case "AnaglyphGamepadCamera":
  15386. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15387. case "AnaglyphUniversalCamera":
  15388. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15389. case "StereoscopicArcRotateCamera":
  15390. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15391. case "StereoscopicFreeCamera":
  15392. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15393. case "StereoscopicGamepadCamera":
  15394. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15395. case "StereoscopicUniversalCamera":
  15396. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15397. case "FreeCamera":// Forcing Universal here
  15398. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15399. default:// Universal Camera is the default value
  15400. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15401. }
  15402. };
  15403. Camera.Parse = function (parsedCamera, scene) {
  15404. var type = parsedCamera.type;
  15405. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15406. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15407. // Parent
  15408. if (parsedCamera.parentId) {
  15409. camera._waitingParentId = parsedCamera.parentId;
  15410. }
  15411. //If camera has an input manager, let it parse inputs settings
  15412. if (camera.inputs) {
  15413. camera.inputs.parse(parsedCamera);
  15414. camera._setupInputs();
  15415. }
  15416. if (camera.setPosition) {
  15417. camera.position.copyFromFloats(0, 0, 0);
  15418. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15419. }
  15420. // Target
  15421. if (parsedCamera.target) {
  15422. if (camera.setTarget) {
  15423. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15424. }
  15425. }
  15426. // Apply 3d rig, when found
  15427. if (parsedCamera.cameraRigMode) {
  15428. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15429. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15430. }
  15431. // Animations
  15432. if (parsedCamera.animations) {
  15433. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15434. var parsedAnimation = parsedCamera.animations[animationIndex];
  15435. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15436. }
  15437. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15438. }
  15439. if (parsedCamera.autoAnimate) {
  15440. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15441. }
  15442. return camera;
  15443. };
  15444. // Statics
  15445. Camera._PERSPECTIVE_CAMERA = 0;
  15446. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15447. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15448. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15449. Camera._RIG_MODE_NONE = 0;
  15450. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15451. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15452. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15453. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15454. Camera._RIG_MODE_VR = 20;
  15455. Camera._RIG_MODE_WEBVR = 21;
  15456. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15457. __decorate([
  15458. BABYLON.serializeAsVector3()
  15459. ], Camera.prototype, "position", void 0);
  15460. __decorate([
  15461. BABYLON.serializeAsVector3()
  15462. ], Camera.prototype, "upVector", void 0);
  15463. __decorate([
  15464. BABYLON.serialize()
  15465. ], Camera.prototype, "orthoLeft", void 0);
  15466. __decorate([
  15467. BABYLON.serialize()
  15468. ], Camera.prototype, "orthoRight", void 0);
  15469. __decorate([
  15470. BABYLON.serialize()
  15471. ], Camera.prototype, "orthoBottom", void 0);
  15472. __decorate([
  15473. BABYLON.serialize()
  15474. ], Camera.prototype, "orthoTop", void 0);
  15475. __decorate([
  15476. BABYLON.serialize()
  15477. ], Camera.prototype, "fov", void 0);
  15478. __decorate([
  15479. BABYLON.serialize()
  15480. ], Camera.prototype, "minZ", void 0);
  15481. __decorate([
  15482. BABYLON.serialize()
  15483. ], Camera.prototype, "maxZ", void 0);
  15484. __decorate([
  15485. BABYLON.serialize()
  15486. ], Camera.prototype, "inertia", void 0);
  15487. __decorate([
  15488. BABYLON.serialize()
  15489. ], Camera.prototype, "mode", void 0);
  15490. __decorate([
  15491. BABYLON.serialize()
  15492. ], Camera.prototype, "layerMask", void 0);
  15493. __decorate([
  15494. BABYLON.serialize()
  15495. ], Camera.prototype, "fovMode", void 0);
  15496. __decorate([
  15497. BABYLON.serialize()
  15498. ], Camera.prototype, "cameraRigMode", void 0);
  15499. __decorate([
  15500. BABYLON.serialize()
  15501. ], Camera.prototype, "interaxialDistance", void 0);
  15502. __decorate([
  15503. BABYLON.serialize()
  15504. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15505. return Camera;
  15506. }(BABYLON.Node));
  15507. BABYLON.Camera = Camera;
  15508. })(BABYLON || (BABYLON = {}));
  15509. //# sourceMappingURL=babylon.camera.js.map
  15510. var BABYLON;
  15511. (function (BABYLON) {
  15512. var RenderingManager = (function () {
  15513. function RenderingManager(scene) {
  15514. this._renderingGroups = new Array();
  15515. this._autoClearDepthStencil = {};
  15516. this._customOpaqueSortCompareFn = {};
  15517. this._customAlphaTestSortCompareFn = {};
  15518. this._customTransparentSortCompareFn = {};
  15519. this._renderinGroupInfo = null;
  15520. this._scene = scene;
  15521. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15522. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15523. }
  15524. }
  15525. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15526. if (depth === void 0) { depth = true; }
  15527. if (stencil === void 0) { stencil = true; }
  15528. if (this._depthStencilBufferAlreadyCleaned) {
  15529. return;
  15530. }
  15531. this._scene.getEngine().clear(null, false, depth, stencil);
  15532. this._depthStencilBufferAlreadyCleaned = true;
  15533. };
  15534. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15535. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15536. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15537. var info = null;
  15538. if (observable) {
  15539. if (!this._renderinGroupInfo) {
  15540. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15541. }
  15542. info = this._renderinGroupInfo;
  15543. info.scene = this._scene;
  15544. info.camera = this._scene.activeCamera;
  15545. }
  15546. // Dispatch sprites
  15547. if (renderSprites) {
  15548. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15549. var manager = this._scene.spriteManagers[index];
  15550. this.dispatchSprites(manager);
  15551. }
  15552. }
  15553. // Render
  15554. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15555. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15556. var renderingGroup = this._renderingGroups[index];
  15557. if (!renderingGroup && !observable)
  15558. continue;
  15559. this._currentIndex = index;
  15560. var renderingGroupMask = 0;
  15561. // Fire PRECLEAR stage
  15562. if (observable) {
  15563. renderingGroupMask = Math.pow(2, index);
  15564. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15565. info.renderingGroupId = index;
  15566. observable.notifyObservers(info, renderingGroupMask);
  15567. }
  15568. // Clear depth/stencil if needed
  15569. if (RenderingManager.AUTOCLEAR) {
  15570. var autoClear = this._autoClearDepthStencil[index];
  15571. if (autoClear && autoClear.autoClear) {
  15572. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15573. }
  15574. }
  15575. if (observable) {
  15576. // Fire PREOPAQUE stage
  15577. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15578. observable.notifyObservers(info, renderingGroupMask);
  15579. // Fire PRETRANSPARENT stage
  15580. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15581. observable.notifyObservers(info, renderingGroupMask);
  15582. }
  15583. if (renderingGroup)
  15584. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15585. // Fire POSTTRANSPARENT stage
  15586. if (observable) {
  15587. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15588. observable.notifyObservers(info, renderingGroupMask);
  15589. }
  15590. }
  15591. };
  15592. RenderingManager.prototype.reset = function () {
  15593. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15594. var renderingGroup = this._renderingGroups[index];
  15595. if (renderingGroup) {
  15596. renderingGroup.prepare();
  15597. }
  15598. }
  15599. };
  15600. RenderingManager.prototype.dispose = function () {
  15601. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15602. var renderingGroup = this._renderingGroups[index];
  15603. if (renderingGroup) {
  15604. renderingGroup.dispose();
  15605. }
  15606. }
  15607. this._renderingGroups.length = 0;
  15608. };
  15609. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15610. if (!this._renderingGroups[renderingGroupId]) {
  15611. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15612. }
  15613. };
  15614. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15615. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15616. this._prepareRenderingGroup(renderingGroupId);
  15617. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15618. };
  15619. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15620. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15621. this._prepareRenderingGroup(renderingGroupId);
  15622. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15623. };
  15624. RenderingManager.prototype.dispatch = function (subMesh) {
  15625. var mesh = subMesh.getMesh();
  15626. var renderingGroupId = mesh.renderingGroupId || 0;
  15627. this._prepareRenderingGroup(renderingGroupId);
  15628. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15629. };
  15630. /**
  15631. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15632. * This allowed control for front to back rendering or reversly depending of the special needs.
  15633. *
  15634. * @param renderingGroupId The rendering group id corresponding to its index
  15635. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15636. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15637. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15638. */
  15639. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15640. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15641. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15642. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15643. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15644. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15645. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15646. if (this._renderingGroups[renderingGroupId]) {
  15647. var group = this._renderingGroups[renderingGroupId];
  15648. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15649. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15650. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15651. }
  15652. };
  15653. /**
  15654. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15655. *
  15656. * @param renderingGroupId The rendering group id corresponding to its index
  15657. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15658. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15659. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15660. */
  15661. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15662. if (depth === void 0) { depth = true; }
  15663. if (stencil === void 0) { stencil = true; }
  15664. this._autoClearDepthStencil[renderingGroupId] = {
  15665. autoClear: autoClearDepthStencil,
  15666. depth: depth,
  15667. stencil: stencil
  15668. };
  15669. };
  15670. /**
  15671. * The max id used for rendering groups (not included)
  15672. */
  15673. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15674. /**
  15675. * The min id used for rendering groups (included)
  15676. */
  15677. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15678. /**
  15679. * Used to globally prevent autoclearing scenes.
  15680. */
  15681. RenderingManager.AUTOCLEAR = true;
  15682. return RenderingManager;
  15683. }());
  15684. BABYLON.RenderingManager = RenderingManager;
  15685. })(BABYLON || (BABYLON = {}));
  15686. //# sourceMappingURL=babylon.renderingManager.js.map
  15687. var BABYLON;
  15688. (function (BABYLON) {
  15689. var RenderingGroup = (function () {
  15690. /**
  15691. * Creates a new rendering group.
  15692. * @param index The rendering group index
  15693. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15694. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15695. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15696. */
  15697. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15698. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15699. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15700. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15701. this.index = index;
  15702. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15703. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15704. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15705. this._particleSystems = new BABYLON.SmartArray(256);
  15706. this._spriteManagers = new BABYLON.SmartArray(256);
  15707. this._edgesRenderers = new BABYLON.SmartArray(16);
  15708. this._scene = scene;
  15709. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15710. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15711. this.transparentSortCompareFn = transparentSortCompareFn;
  15712. }
  15713. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15714. /**
  15715. * Set the opaque sort comparison function.
  15716. * If null the sub meshes will be render in the order they were created
  15717. */
  15718. set: function (value) {
  15719. this._opaqueSortCompareFn = value;
  15720. if (value) {
  15721. this._renderOpaque = this.renderOpaqueSorted;
  15722. }
  15723. else {
  15724. this._renderOpaque = RenderingGroup.renderUnsorted;
  15725. }
  15726. },
  15727. enumerable: true,
  15728. configurable: true
  15729. });
  15730. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15731. /**
  15732. * Set the alpha test sort comparison function.
  15733. * If null the sub meshes will be render in the order they were created
  15734. */
  15735. set: function (value) {
  15736. this._alphaTestSortCompareFn = value;
  15737. if (value) {
  15738. this._renderAlphaTest = this.renderAlphaTestSorted;
  15739. }
  15740. else {
  15741. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15742. }
  15743. },
  15744. enumerable: true,
  15745. configurable: true
  15746. });
  15747. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15748. /**
  15749. * Set the transparent sort comparison function.
  15750. * If null the sub meshes will be render in the order they were created
  15751. */
  15752. set: function (value) {
  15753. if (value) {
  15754. this._transparentSortCompareFn = value;
  15755. }
  15756. else {
  15757. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15758. }
  15759. this._renderTransparent = this.renderTransparentSorted;
  15760. },
  15761. enumerable: true,
  15762. configurable: true
  15763. });
  15764. /**
  15765. * Render all the sub meshes contained in the group.
  15766. * @param customRenderFunction Used to override the default render behaviour of the group.
  15767. * @returns true if rendered some submeshes.
  15768. */
  15769. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15770. if (customRenderFunction) {
  15771. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15772. return;
  15773. }
  15774. var engine = this._scene.getEngine();
  15775. // Opaque
  15776. if (this._opaqueSubMeshes.length !== 0) {
  15777. this._renderOpaque(this._opaqueSubMeshes);
  15778. }
  15779. // Alpha test
  15780. if (this._alphaTestSubMeshes.length !== 0) {
  15781. engine.setAlphaTesting(true);
  15782. this._renderAlphaTest(this._alphaTestSubMeshes);
  15783. engine.setAlphaTesting(false);
  15784. }
  15785. var stencilState = engine.getStencilBuffer();
  15786. engine.setStencilBuffer(false);
  15787. // Sprites
  15788. if (renderSprites) {
  15789. this._renderSprites();
  15790. }
  15791. // Particles
  15792. if (renderParticles) {
  15793. this._renderParticles(activeMeshes);
  15794. }
  15795. if (this.onBeforeTransparentRendering) {
  15796. this.onBeforeTransparentRendering();
  15797. }
  15798. // Transparent
  15799. if (this._transparentSubMeshes.length !== 0) {
  15800. this._renderTransparent(this._transparentSubMeshes);
  15801. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15802. }
  15803. // Set back stencil to false in case it changes before the edge renderer.
  15804. engine.setStencilBuffer(false);
  15805. // Edges
  15806. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15807. this._edgesRenderers.data[edgesRendererIndex].render();
  15808. }
  15809. // Restore Stencil state.
  15810. engine.setStencilBuffer(stencilState);
  15811. };
  15812. /**
  15813. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15814. * @param subMeshes The submeshes to render
  15815. */
  15816. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15817. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15818. };
  15819. /**
  15820. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15821. * @param subMeshes The submeshes to render
  15822. */
  15823. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15824. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15825. };
  15826. /**
  15827. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15828. * @param subMeshes The submeshes to render
  15829. */
  15830. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15831. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15832. };
  15833. /**
  15834. * Renders the submeshes in a specified order.
  15835. * @param subMeshes The submeshes to sort before render
  15836. * @param sortCompareFn The comparison function use to sort
  15837. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15838. * @param transparent Specifies to activate blending if true
  15839. */
  15840. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15841. var subIndex = 0;
  15842. var subMesh;
  15843. for (; subIndex < subMeshes.length; subIndex++) {
  15844. subMesh = subMeshes.data[subIndex];
  15845. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15846. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15847. }
  15848. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15849. sortedArray.sort(sortCompareFn);
  15850. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15851. subMesh = sortedArray[subIndex];
  15852. subMesh.render(transparent);
  15853. }
  15854. };
  15855. /**
  15856. * Renders the submeshes in the order they were dispatched (no sort applied).
  15857. * @param subMeshes The submeshes to render
  15858. */
  15859. RenderingGroup.renderUnsorted = function (subMeshes) {
  15860. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15861. var submesh = subMeshes.data[subIndex];
  15862. submesh.render(false);
  15863. }
  15864. };
  15865. /**
  15866. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15867. * are rendered back to front if in the same alpha index.
  15868. *
  15869. * @param a The first submesh
  15870. * @param b The second submesh
  15871. * @returns The result of the comparison
  15872. */
  15873. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15874. // Alpha index first
  15875. if (a._alphaIndex > b._alphaIndex) {
  15876. return 1;
  15877. }
  15878. if (a._alphaIndex < b._alphaIndex) {
  15879. return -1;
  15880. }
  15881. // Then distance to camera
  15882. return RenderingGroup.backToFrontSortCompare(a, b);
  15883. };
  15884. /**
  15885. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15886. * are rendered back to front.
  15887. *
  15888. * @param a The first submesh
  15889. * @param b The second submesh
  15890. * @returns The result of the comparison
  15891. */
  15892. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15893. // Then distance to camera
  15894. if (a._distanceToCamera < b._distanceToCamera) {
  15895. return 1;
  15896. }
  15897. if (a._distanceToCamera > b._distanceToCamera) {
  15898. return -1;
  15899. }
  15900. return 0;
  15901. };
  15902. /**
  15903. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15904. * are rendered front to back (prevent overdraw).
  15905. *
  15906. * @param a The first submesh
  15907. * @param b The second submesh
  15908. * @returns The result of the comparison
  15909. */
  15910. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15911. // Then distance to camera
  15912. if (a._distanceToCamera < b._distanceToCamera) {
  15913. return -1;
  15914. }
  15915. if (a._distanceToCamera > b._distanceToCamera) {
  15916. return 1;
  15917. }
  15918. return 0;
  15919. };
  15920. /**
  15921. * Resets the different lists of submeshes to prepare a new frame.
  15922. */
  15923. RenderingGroup.prototype.prepare = function () {
  15924. this._opaqueSubMeshes.reset();
  15925. this._transparentSubMeshes.reset();
  15926. this._alphaTestSubMeshes.reset();
  15927. this._particleSystems.reset();
  15928. this._spriteManagers.reset();
  15929. this._edgesRenderers.reset();
  15930. };
  15931. RenderingGroup.prototype.dispose = function () {
  15932. this._opaqueSubMeshes.dispose();
  15933. this._transparentSubMeshes.dispose();
  15934. this._alphaTestSubMeshes.dispose();
  15935. this._particleSystems.dispose();
  15936. this._spriteManagers.dispose();
  15937. this._edgesRenderers.dispose();
  15938. };
  15939. /**
  15940. * Inserts the submesh in its correct queue depending on its material.
  15941. * @param subMesh The submesh to dispatch
  15942. */
  15943. RenderingGroup.prototype.dispatch = function (subMesh) {
  15944. var material = subMesh.getMaterial();
  15945. var mesh = subMesh.getMesh();
  15946. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15947. this._transparentSubMeshes.push(subMesh);
  15948. }
  15949. else if (material.needAlphaTesting()) {
  15950. this._alphaTestSubMeshes.push(subMesh);
  15951. }
  15952. else {
  15953. this._opaqueSubMeshes.push(subMesh); // Opaque
  15954. }
  15955. if (mesh._edgesRenderer) {
  15956. this._edgesRenderers.push(mesh._edgesRenderer);
  15957. }
  15958. };
  15959. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15960. this._spriteManagers.push(spriteManager);
  15961. };
  15962. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15963. this._particleSystems.push(particleSystem);
  15964. };
  15965. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15966. if (this._particleSystems.length === 0) {
  15967. return;
  15968. }
  15969. // Particles
  15970. var activeCamera = this._scene.activeCamera;
  15971. this._scene._particlesDuration.beginMonitoring();
  15972. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15973. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15974. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15975. continue;
  15976. }
  15977. var emitter = particleSystem.emitter;
  15978. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  15979. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15980. }
  15981. }
  15982. this._scene._particlesDuration.endMonitoring(false);
  15983. };
  15984. RenderingGroup.prototype._renderSprites = function () {
  15985. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15986. return;
  15987. }
  15988. // Sprites
  15989. var activeCamera = this._scene.activeCamera;
  15990. this._scene._spritesDuration.beginMonitoring();
  15991. for (var id = 0; id < this._spriteManagers.length; id++) {
  15992. var spriteManager = this._spriteManagers.data[id];
  15993. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15994. spriteManager.render();
  15995. }
  15996. }
  15997. this._scene._spritesDuration.endMonitoring(false);
  15998. };
  15999. return RenderingGroup;
  16000. }());
  16001. BABYLON.RenderingGroup = RenderingGroup;
  16002. })(BABYLON || (BABYLON = {}));
  16003. //# sourceMappingURL=babylon.renderingGroup.js.map
  16004. var BABYLON;
  16005. (function (BABYLON) {
  16006. var ClickInfo = (function () {
  16007. function ClickInfo() {
  16008. this._singleClick = false;
  16009. this._doubleClick = false;
  16010. this._hasSwiped = false;
  16011. this._ignore = false;
  16012. }
  16013. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16014. get: function () {
  16015. return this._singleClick;
  16016. },
  16017. set: function (b) {
  16018. this._singleClick = b;
  16019. },
  16020. enumerable: true,
  16021. configurable: true
  16022. });
  16023. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16024. get: function () {
  16025. return this._doubleClick;
  16026. },
  16027. set: function (b) {
  16028. this._doubleClick = b;
  16029. },
  16030. enumerable: true,
  16031. configurable: true
  16032. });
  16033. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16034. get: function () {
  16035. return this._hasSwiped;
  16036. },
  16037. set: function (b) {
  16038. this._hasSwiped = b;
  16039. },
  16040. enumerable: true,
  16041. configurable: true
  16042. });
  16043. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16044. get: function () {
  16045. return this._ignore;
  16046. },
  16047. set: function (b) {
  16048. this._ignore = b;
  16049. },
  16050. enumerable: true,
  16051. configurable: true
  16052. });
  16053. return ClickInfo;
  16054. }());
  16055. var PointerEventTypes = (function () {
  16056. function PointerEventTypes() {
  16057. }
  16058. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16059. get: function () {
  16060. return PointerEventTypes._POINTERDOWN;
  16061. },
  16062. enumerable: true,
  16063. configurable: true
  16064. });
  16065. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16066. get: function () {
  16067. return PointerEventTypes._POINTERUP;
  16068. },
  16069. enumerable: true,
  16070. configurable: true
  16071. });
  16072. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16073. get: function () {
  16074. return PointerEventTypes._POINTERMOVE;
  16075. },
  16076. enumerable: true,
  16077. configurable: true
  16078. });
  16079. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16080. get: function () {
  16081. return PointerEventTypes._POINTERWHEEL;
  16082. },
  16083. enumerable: true,
  16084. configurable: true
  16085. });
  16086. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16087. get: function () {
  16088. return PointerEventTypes._POINTERPICK;
  16089. },
  16090. enumerable: true,
  16091. configurable: true
  16092. });
  16093. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  16094. get: function () {
  16095. return PointerEventTypes._POINTERTAP;
  16096. },
  16097. enumerable: true,
  16098. configurable: true
  16099. });
  16100. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  16101. get: function () {
  16102. return PointerEventTypes._POINTERDOUBLETAP;
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. PointerEventTypes._POINTERDOWN = 0x01;
  16108. PointerEventTypes._POINTERUP = 0x02;
  16109. PointerEventTypes._POINTERMOVE = 0x04;
  16110. PointerEventTypes._POINTERWHEEL = 0x08;
  16111. PointerEventTypes._POINTERPICK = 0x10;
  16112. PointerEventTypes._POINTERTAP = 0x20;
  16113. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  16114. return PointerEventTypes;
  16115. }());
  16116. BABYLON.PointerEventTypes = PointerEventTypes;
  16117. var PointerInfoBase = (function () {
  16118. function PointerInfoBase(type, event) {
  16119. this.type = type;
  16120. this.event = event;
  16121. }
  16122. return PointerInfoBase;
  16123. }());
  16124. BABYLON.PointerInfoBase = PointerInfoBase;
  16125. /**
  16126. * This class is used to store pointer related info for the onPrePointerObservable event.
  16127. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16128. */
  16129. var PointerInfoPre = (function (_super) {
  16130. __extends(PointerInfoPre, _super);
  16131. function PointerInfoPre(type, event, localX, localY) {
  16132. var _this = _super.call(this, type, event) || this;
  16133. _this.skipOnPointerObservable = false;
  16134. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16135. return _this;
  16136. }
  16137. return PointerInfoPre;
  16138. }(PointerInfoBase));
  16139. BABYLON.PointerInfoPre = PointerInfoPre;
  16140. /**
  16141. * This type contains all the data related to a pointer event in Babylon.js.
  16142. * 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.
  16143. */
  16144. var PointerInfo = (function (_super) {
  16145. __extends(PointerInfo, _super);
  16146. function PointerInfo(type, event, pickInfo) {
  16147. var _this = _super.call(this, type, event) || this;
  16148. _this.pickInfo = pickInfo;
  16149. return _this;
  16150. }
  16151. return PointerInfo;
  16152. }(PointerInfoBase));
  16153. BABYLON.PointerInfo = PointerInfo;
  16154. /**
  16155. * This class is used by the onRenderingGroupObservable
  16156. */
  16157. var RenderingGroupInfo = (function () {
  16158. function RenderingGroupInfo() {
  16159. }
  16160. /**
  16161. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16162. * This stage will be fired no matter what
  16163. */
  16164. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16165. /**
  16166. * Called before opaque object are rendered.
  16167. * This stage will be fired only if there's 3D Opaque content to render
  16168. */
  16169. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16170. /**
  16171. * Called after the opaque objects are rendered and before the transparent ones
  16172. * This stage will be fired only if there's 3D transparent content to render
  16173. */
  16174. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16175. /**
  16176. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16177. * This stage will be fired no matter what
  16178. */
  16179. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16180. return RenderingGroupInfo;
  16181. }());
  16182. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16183. /**
  16184. * Represents a scene to be rendered by the engine.
  16185. * @see http://doc.babylonjs.com/page.php?p=21911
  16186. */
  16187. var Scene = (function () {
  16188. /**
  16189. * @constructor
  16190. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16191. */
  16192. function Scene(engine) {
  16193. // Members
  16194. this.autoClear = true;
  16195. this.autoClearDepthAndStencil = true;
  16196. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16197. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16198. this.forceWireframe = false;
  16199. this._forcePointsCloud = false;
  16200. this.forceShowBoundingBoxes = false;
  16201. this.animationsEnabled = true;
  16202. this.constantlyUpdateMeshUnderPointer = false;
  16203. this.hoverCursor = "pointer";
  16204. this.defaultCursor = "";
  16205. // Metadata
  16206. this.metadata = null;
  16207. // Events
  16208. /**
  16209. * An event triggered when the scene is disposed.
  16210. * @type {BABYLON.Observable}
  16211. */
  16212. this.onDisposeObservable = new BABYLON.Observable();
  16213. /**
  16214. * An event triggered before rendering the scene
  16215. * @type {BABYLON.Observable}
  16216. */
  16217. this.onBeforeRenderObservable = new BABYLON.Observable();
  16218. /**
  16219. * An event triggered after rendering the scene
  16220. * @type {BABYLON.Observable}
  16221. */
  16222. this.onAfterRenderObservable = new BABYLON.Observable();
  16223. /**
  16224. * An event triggered when the scene is ready
  16225. * @type {BABYLON.Observable}
  16226. */
  16227. this.onReadyObservable = new BABYLON.Observable();
  16228. /**
  16229. * An event triggered before rendering a camera
  16230. * @type {BABYLON.Observable}
  16231. */
  16232. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16233. /**
  16234. * An event triggered after rendering a camera
  16235. * @type {BABYLON.Observable}
  16236. */
  16237. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16238. /**
  16239. * An event triggered when a camera is created
  16240. * @type {BABYLON.Observable}
  16241. */
  16242. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16243. /**
  16244. * An event triggered when a camera is removed
  16245. * @type {BABYLON.Observable}
  16246. */
  16247. this.onCameraRemovedObservable = new BABYLON.Observable();
  16248. /**
  16249. * An event triggered when a light is created
  16250. * @type {BABYLON.Observable}
  16251. */
  16252. this.onNewLightAddedObservable = new BABYLON.Observable();
  16253. /**
  16254. * An event triggered when a light is removed
  16255. * @type {BABYLON.Observable}
  16256. */
  16257. this.onLightRemovedObservable = new BABYLON.Observable();
  16258. /**
  16259. * An event triggered when a geometry is created
  16260. * @type {BABYLON.Observable}
  16261. */
  16262. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16263. /**
  16264. * An event triggered when a geometry is removed
  16265. * @type {BABYLON.Observable}
  16266. */
  16267. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16268. /**
  16269. * An event triggered when a mesh is created
  16270. * @type {BABYLON.Observable}
  16271. */
  16272. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16273. /**
  16274. * An event triggered when a mesh is removed
  16275. * @type {BABYLON.Observable}
  16276. */
  16277. this.onMeshRemovedObservable = new BABYLON.Observable();
  16278. /**
  16279. * An event triggered before calculating deterministic simulation step
  16280. * @type {BABYLON.Observable}
  16281. */
  16282. this.onBeforeStepObservable = new BABYLON.Observable();
  16283. /**
  16284. * An event triggered after calculating deterministic simulation step
  16285. * @type {BABYLON.Observable}
  16286. */
  16287. this.onAfterStepObservable = new BABYLON.Observable();
  16288. /**
  16289. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16290. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16291. * 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)
  16292. */
  16293. this.onRenderingGroupObservable = new BABYLON.Observable();
  16294. // Animations
  16295. this.animations = [];
  16296. /**
  16297. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  16298. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16299. */
  16300. this.onPrePointerObservable = new BABYLON.Observable();
  16301. /**
  16302. * Observable event triggered each time an input event is received from the rendering canvas
  16303. */
  16304. this.onPointerObservable = new BABYLON.Observable();
  16305. this._meshPickProceed = false;
  16306. this._previousHasSwiped = false;
  16307. this._currentPickResult = null;
  16308. this._previousPickResult = null;
  16309. this._isButtonPressed = false;
  16310. this._doubleClickOccured = false;
  16311. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16312. this.cameraToUseForPointers = null;
  16313. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16314. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16315. this._startingPointerTime = 0;
  16316. this._previousStartingPointerTime = 0;
  16317. // Deterministic lockstep
  16318. this._timeAccumulator = 0;
  16319. this._currentStepId = 0;
  16320. this._currentInternalStep = 0;
  16321. // Coordinate system
  16322. /**
  16323. * use right-handed coordinate system on this scene.
  16324. * @type {boolean}
  16325. */
  16326. this._useRightHandedSystem = false;
  16327. // Fog
  16328. this._fogEnabled = true;
  16329. this._fogMode = Scene.FOGMODE_NONE;
  16330. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16331. this.fogDensity = 0.1;
  16332. this.fogStart = 0;
  16333. this.fogEnd = 1000.0;
  16334. // Lights
  16335. /**
  16336. * is shadow enabled on this scene.
  16337. * @type {boolean}
  16338. */
  16339. this._shadowsEnabled = true;
  16340. /**
  16341. * is light enabled on this scene.
  16342. * @type {boolean}
  16343. */
  16344. this._lightsEnabled = true;
  16345. /**
  16346. * All of the lights added to this scene.
  16347. * @see BABYLON.Light
  16348. * @type {BABYLON.Light[]}
  16349. */
  16350. this.lights = new Array();
  16351. // Cameras
  16352. /** All of the cameras added to this scene. */
  16353. this.cameras = new Array();
  16354. /** All of the active cameras added to this scene. */
  16355. this.activeCameras = new Array();
  16356. // Meshes
  16357. /**
  16358. * All of the (abstract) meshes added to this scene.
  16359. * @see BABYLON.AbstractMesh
  16360. * @type {BABYLON.AbstractMesh[]}
  16361. */
  16362. this.meshes = new Array();
  16363. // Geometries
  16364. this._geometries = new Array();
  16365. this.materials = new Array();
  16366. this.multiMaterials = new Array();
  16367. // Textures
  16368. this._texturesEnabled = true;
  16369. this.textures = new Array();
  16370. // Particles
  16371. this.particlesEnabled = true;
  16372. this.particleSystems = new Array();
  16373. // Sprites
  16374. this.spritesEnabled = true;
  16375. this.spriteManagers = new Array();
  16376. // Layers
  16377. this.layers = new Array();
  16378. this.highlightLayers = new Array();
  16379. // Skeletons
  16380. this._skeletonsEnabled = true;
  16381. this.skeletons = new Array();
  16382. // Morph targets
  16383. this.morphTargetManagers = new Array();
  16384. // Lens flares
  16385. this.lensFlaresEnabled = true;
  16386. this.lensFlareSystems = new Array();
  16387. // Collisions
  16388. this.collisionsEnabled = true;
  16389. /** Defines the gravity applied to this scene */
  16390. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16391. // Postprocesses
  16392. this.postProcessesEnabled = true;
  16393. // Customs render targets
  16394. this.renderTargetsEnabled = true;
  16395. this.dumpNextRenderTargets = false;
  16396. this.customRenderTargets = new Array();
  16397. // Imported meshes
  16398. this.importedMeshesFiles = new Array();
  16399. // Probes
  16400. this.probesEnabled = true;
  16401. this.reflectionProbes = new Array();
  16402. this._actionManagers = new Array();
  16403. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16404. // Procedural textures
  16405. this.proceduralTexturesEnabled = true;
  16406. this._proceduralTextures = new Array();
  16407. this.soundTracks = new Array();
  16408. this._audioEnabled = true;
  16409. this._headphone = false;
  16410. // Performance counters
  16411. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16412. this._totalLightsCounter = new BABYLON.PerfCounter();
  16413. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16414. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16415. this._totalVertices = new BABYLON.PerfCounter();
  16416. this._activeIndices = new BABYLON.PerfCounter();
  16417. this._activeParticles = new BABYLON.PerfCounter();
  16418. this._lastFrameDuration = new BABYLON.PerfCounter();
  16419. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16420. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16421. this._particlesDuration = new BABYLON.PerfCounter();
  16422. this._renderDuration = new BABYLON.PerfCounter();
  16423. this._spritesDuration = new BABYLON.PerfCounter();
  16424. this._activeBones = new BABYLON.PerfCounter();
  16425. this._animationTime = 0;
  16426. this.animationTimeScale = 1;
  16427. this._renderId = 0;
  16428. this._executeWhenReadyTimeoutId = -1;
  16429. this._intermediateRendering = false;
  16430. this._viewUpdateFlag = -1;
  16431. this._projectionUpdateFlag = -1;
  16432. this._toBeDisposed = new BABYLON.SmartArray(256);
  16433. this._pendingData = []; //ANY
  16434. this._activeMeshes = new BABYLON.SmartArray(256);
  16435. this._processedMaterials = new BABYLON.SmartArray(256);
  16436. this._renderTargets = new BABYLON.SmartArray(256);
  16437. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16438. this._activeSkeletons = new BABYLON.SmartArray(32);
  16439. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16440. this._activeAnimatables = new Array();
  16441. this._transformMatrix = BABYLON.Matrix.Zero();
  16442. this.requireLightSorting = false;
  16443. this._uniqueIdCounter = 0;
  16444. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16445. this._engine.scenes.push(this);
  16446. this._uid = null;
  16447. this._renderingManager = new BABYLON.RenderingManager(this);
  16448. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16449. if (BABYLON.OutlineRenderer) {
  16450. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16451. }
  16452. this.attachControl();
  16453. if (BABYLON.SoundTrack) {
  16454. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16455. }
  16456. //simplification queue
  16457. if (BABYLON.SimplificationQueue) {
  16458. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16459. }
  16460. //collision coordinator initialization. For now legacy per default.
  16461. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16462. // Uniform Buffer
  16463. this._createUbo();
  16464. // Default Image processing definition.
  16465. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16466. }
  16467. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16468. /** The fog is deactivated */
  16469. get: function () {
  16470. return Scene._FOGMODE_NONE;
  16471. },
  16472. enumerable: true,
  16473. configurable: true
  16474. });
  16475. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16476. /** The fog density is following an exponential function */
  16477. get: function () {
  16478. return Scene._FOGMODE_EXP;
  16479. },
  16480. enumerable: true,
  16481. configurable: true
  16482. });
  16483. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16484. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16485. get: function () {
  16486. return Scene._FOGMODE_EXP2;
  16487. },
  16488. enumerable: true,
  16489. configurable: true
  16490. });
  16491. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16492. /** The fog density is following a linear function. */
  16493. get: function () {
  16494. return Scene._FOGMODE_LINEAR;
  16495. },
  16496. enumerable: true,
  16497. configurable: true
  16498. });
  16499. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16500. /**
  16501. * Texture used in all pbr material as the reflection texture.
  16502. * As in the majority of the scene they are the same (exception for multi room and so on),
  16503. * this is easier to reference from here than from all the materials.
  16504. */
  16505. get: function () {
  16506. return this._environmentTexture;
  16507. },
  16508. /**
  16509. * Texture used in all pbr material as the reflection texture.
  16510. * As in the majority of the scene they are the same (exception for multi room and so on),
  16511. * this is easier to set here than in all the materials.
  16512. */
  16513. set: function (value) {
  16514. this._environmentTexture = value;
  16515. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16516. },
  16517. enumerable: true,
  16518. configurable: true
  16519. });
  16520. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16521. /**
  16522. * Default image processing configuration used either in the rendering
  16523. * Forward main pass or through the imageProcessingPostProcess if present.
  16524. * As in the majority of the scene they are the same (exception for multi camera),
  16525. * this is easier to reference from here than from all the materials and post process.
  16526. *
  16527. * No setter as we it is a shared configuration, you can set the values instead.
  16528. */
  16529. get: function () {
  16530. return this._imageProcessingConfiguration;
  16531. },
  16532. enumerable: true,
  16533. configurable: true
  16534. });
  16535. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16536. get: function () {
  16537. return this._forcePointsCloud;
  16538. },
  16539. set: function (value) {
  16540. if (this._forcePointsCloud === value) {
  16541. return;
  16542. }
  16543. this._forcePointsCloud = value;
  16544. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16545. },
  16546. enumerable: true,
  16547. configurable: true
  16548. });
  16549. Object.defineProperty(Scene.prototype, "onDispose", {
  16550. /** A function to be executed when this scene is disposed. */
  16551. set: function (callback) {
  16552. if (this._onDisposeObserver) {
  16553. this.onDisposeObservable.remove(this._onDisposeObserver);
  16554. }
  16555. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16556. },
  16557. enumerable: true,
  16558. configurable: true
  16559. });
  16560. Object.defineProperty(Scene.prototype, "beforeRender", {
  16561. /** A function to be executed before rendering this scene */
  16562. set: function (callback) {
  16563. if (this._onBeforeRenderObserver) {
  16564. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16565. }
  16566. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16567. },
  16568. enumerable: true,
  16569. configurable: true
  16570. });
  16571. Object.defineProperty(Scene.prototype, "afterRender", {
  16572. /** A function to be executed after rendering this scene */
  16573. set: function (callback) {
  16574. if (this._onAfterRenderObserver) {
  16575. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16576. }
  16577. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16578. },
  16579. enumerable: true,
  16580. configurable: true
  16581. });
  16582. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16583. set: function (callback) {
  16584. if (this._onBeforeCameraRenderObserver) {
  16585. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16586. }
  16587. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16588. },
  16589. enumerable: true,
  16590. configurable: true
  16591. });
  16592. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16593. set: function (callback) {
  16594. if (this._onAfterCameraRenderObserver) {
  16595. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16596. }
  16597. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16598. },
  16599. enumerable: true,
  16600. configurable: true
  16601. });
  16602. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16603. get: function () {
  16604. if (!this._gamepadManager) {
  16605. this._gamepadManager = new BABYLON.GamepadManager();
  16606. }
  16607. return this._gamepadManager;
  16608. },
  16609. enumerable: true,
  16610. configurable: true
  16611. });
  16612. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16613. get: function () {
  16614. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16615. },
  16616. enumerable: true,
  16617. configurable: true
  16618. });
  16619. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16620. get: function () {
  16621. return this._useRightHandedSystem;
  16622. },
  16623. set: function (value) {
  16624. if (this._useRightHandedSystem === value) {
  16625. return;
  16626. }
  16627. this._useRightHandedSystem = value;
  16628. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16629. },
  16630. enumerable: true,
  16631. configurable: true
  16632. });
  16633. Scene.prototype.setStepId = function (newStepId) {
  16634. this._currentStepId = newStepId;
  16635. };
  16636. ;
  16637. Scene.prototype.getStepId = function () {
  16638. return this._currentStepId;
  16639. };
  16640. ;
  16641. Scene.prototype.getInternalStep = function () {
  16642. return this._currentInternalStep;
  16643. };
  16644. ;
  16645. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16646. get: function () {
  16647. return this._fogEnabled;
  16648. },
  16649. /**
  16650. * is fog enabled on this scene.
  16651. */
  16652. set: function (value) {
  16653. if (this._fogEnabled === value) {
  16654. return;
  16655. }
  16656. this._fogEnabled = value;
  16657. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16658. },
  16659. enumerable: true,
  16660. configurable: true
  16661. });
  16662. Object.defineProperty(Scene.prototype, "fogMode", {
  16663. get: function () {
  16664. return this._fogMode;
  16665. },
  16666. set: function (value) {
  16667. if (this._fogMode === value) {
  16668. return;
  16669. }
  16670. this._fogMode = value;
  16671. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16672. },
  16673. enumerable: true,
  16674. configurable: true
  16675. });
  16676. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16677. get: function () {
  16678. return this._shadowsEnabled;
  16679. },
  16680. set: function (value) {
  16681. if (this._shadowsEnabled === value) {
  16682. return;
  16683. }
  16684. this._shadowsEnabled = value;
  16685. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16686. },
  16687. enumerable: true,
  16688. configurable: true
  16689. });
  16690. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16691. get: function () {
  16692. return this._lightsEnabled;
  16693. },
  16694. set: function (value) {
  16695. if (this._lightsEnabled === value) {
  16696. return;
  16697. }
  16698. this._lightsEnabled = value;
  16699. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16700. },
  16701. enumerable: true,
  16702. configurable: true
  16703. });
  16704. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16705. /** The default material used on meshes when no material is affected */
  16706. get: function () {
  16707. if (!this._defaultMaterial) {
  16708. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16709. }
  16710. return this._defaultMaterial;
  16711. },
  16712. /** The default material used on meshes when no material is affected */
  16713. set: function (value) {
  16714. this._defaultMaterial = value;
  16715. },
  16716. enumerable: true,
  16717. configurable: true
  16718. });
  16719. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16720. get: function () {
  16721. return this._texturesEnabled;
  16722. },
  16723. set: function (value) {
  16724. if (this._texturesEnabled === value) {
  16725. return;
  16726. }
  16727. this._texturesEnabled = value;
  16728. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16729. },
  16730. enumerable: true,
  16731. configurable: true
  16732. });
  16733. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16734. get: function () {
  16735. return this._skeletonsEnabled;
  16736. },
  16737. set: function (value) {
  16738. if (this._skeletonsEnabled === value) {
  16739. return;
  16740. }
  16741. this._skeletonsEnabled = value;
  16742. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16743. },
  16744. enumerable: true,
  16745. configurable: true
  16746. });
  16747. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16748. get: function () {
  16749. if (!this._postProcessRenderPipelineManager) {
  16750. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16751. }
  16752. return this._postProcessRenderPipelineManager;
  16753. },
  16754. enumerable: true,
  16755. configurable: true
  16756. });
  16757. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16758. get: function () {
  16759. return this._frustumPlanes;
  16760. },
  16761. enumerable: true,
  16762. configurable: true
  16763. });
  16764. Object.defineProperty(Scene.prototype, "debugLayer", {
  16765. // Properties
  16766. get: function () {
  16767. if (!this._debugLayer) {
  16768. this._debugLayer = new BABYLON.DebugLayer(this);
  16769. }
  16770. return this._debugLayer;
  16771. },
  16772. enumerable: true,
  16773. configurable: true
  16774. });
  16775. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16776. get: function () {
  16777. return this._workerCollisions;
  16778. },
  16779. set: function (enabled) {
  16780. if (!BABYLON.CollisionCoordinatorLegacy) {
  16781. return;
  16782. }
  16783. enabled = (enabled && !!Worker);
  16784. this._workerCollisions = enabled;
  16785. if (this.collisionCoordinator) {
  16786. this.collisionCoordinator.destroy();
  16787. }
  16788. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16789. this.collisionCoordinator.init(this);
  16790. },
  16791. enumerable: true,
  16792. configurable: true
  16793. });
  16794. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16795. get: function () {
  16796. return this._selectionOctree;
  16797. },
  16798. enumerable: true,
  16799. configurable: true
  16800. });
  16801. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16802. /**
  16803. * The mesh that is currently under the pointer.
  16804. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16805. */
  16806. get: function () {
  16807. return this._pointerOverMesh;
  16808. },
  16809. enumerable: true,
  16810. configurable: true
  16811. });
  16812. Object.defineProperty(Scene.prototype, "pointerX", {
  16813. /**
  16814. * Current on-screen X position of the pointer
  16815. * @return {number} X position of the pointer
  16816. */
  16817. get: function () {
  16818. return this._pointerX;
  16819. },
  16820. enumerable: true,
  16821. configurable: true
  16822. });
  16823. Object.defineProperty(Scene.prototype, "pointerY", {
  16824. /**
  16825. * Current on-screen Y position of the pointer
  16826. * @return {number} Y position of the pointer
  16827. */
  16828. get: function () {
  16829. return this._pointerY;
  16830. },
  16831. enumerable: true,
  16832. configurable: true
  16833. });
  16834. Scene.prototype.getCachedMaterial = function () {
  16835. return this._cachedMaterial;
  16836. };
  16837. Scene.prototype.getCachedEffect = function () {
  16838. return this._cachedEffect;
  16839. };
  16840. Scene.prototype.getCachedVisibility = function () {
  16841. return this._cachedVisibility;
  16842. };
  16843. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  16844. if (visibility === void 0) { visibility = 1; }
  16845. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16846. };
  16847. Scene.prototype.getBoundingBoxRenderer = function () {
  16848. if (!this._boundingBoxRenderer) {
  16849. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16850. }
  16851. return this._boundingBoxRenderer;
  16852. };
  16853. Scene.prototype.getOutlineRenderer = function () {
  16854. return this._outlineRenderer;
  16855. };
  16856. Scene.prototype.getEngine = function () {
  16857. return this._engine;
  16858. };
  16859. Scene.prototype.getTotalVertices = function () {
  16860. return this._totalVertices.current;
  16861. };
  16862. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16863. get: function () {
  16864. return this._totalVertices;
  16865. },
  16866. enumerable: true,
  16867. configurable: true
  16868. });
  16869. Scene.prototype.getActiveIndices = function () {
  16870. return this._activeIndices.current;
  16871. };
  16872. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16873. get: function () {
  16874. return this._activeIndices;
  16875. },
  16876. enumerable: true,
  16877. configurable: true
  16878. });
  16879. Scene.prototype.getActiveParticles = function () {
  16880. return this._activeParticles.current;
  16881. };
  16882. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16883. get: function () {
  16884. return this._activeParticles;
  16885. },
  16886. enumerable: true,
  16887. configurable: true
  16888. });
  16889. Scene.prototype.getActiveBones = function () {
  16890. return this._activeBones.current;
  16891. };
  16892. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16893. get: function () {
  16894. return this._activeBones;
  16895. },
  16896. enumerable: true,
  16897. configurable: true
  16898. });
  16899. // Stats
  16900. Scene.prototype.getLastFrameDuration = function () {
  16901. return this._lastFrameDuration.current;
  16902. };
  16903. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16904. get: function () {
  16905. return this._lastFrameDuration;
  16906. },
  16907. enumerable: true,
  16908. configurable: true
  16909. });
  16910. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16911. return this._evaluateActiveMeshesDuration.current;
  16912. };
  16913. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16914. get: function () {
  16915. return this._evaluateActiveMeshesDuration;
  16916. },
  16917. enumerable: true,
  16918. configurable: true
  16919. });
  16920. Scene.prototype.getActiveMeshes = function () {
  16921. return this._activeMeshes;
  16922. };
  16923. Scene.prototype.getRenderTargetsDuration = function () {
  16924. return this._renderTargetsDuration.current;
  16925. };
  16926. Scene.prototype.getRenderDuration = function () {
  16927. return this._renderDuration.current;
  16928. };
  16929. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16930. get: function () {
  16931. return this._renderDuration;
  16932. },
  16933. enumerable: true,
  16934. configurable: true
  16935. });
  16936. Scene.prototype.getParticlesDuration = function () {
  16937. return this._particlesDuration.current;
  16938. };
  16939. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16940. get: function () {
  16941. return this._particlesDuration;
  16942. },
  16943. enumerable: true,
  16944. configurable: true
  16945. });
  16946. Scene.prototype.getSpritesDuration = function () {
  16947. return this._spritesDuration.current;
  16948. };
  16949. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16950. get: function () {
  16951. return this._spritesDuration;
  16952. },
  16953. enumerable: true,
  16954. configurable: true
  16955. });
  16956. Scene.prototype.getAnimationRatio = function () {
  16957. return this._animationRatio;
  16958. };
  16959. Scene.prototype.getRenderId = function () {
  16960. return this._renderId;
  16961. };
  16962. Scene.prototype.incrementRenderId = function () {
  16963. this._renderId++;
  16964. };
  16965. Scene.prototype._updatePointerPosition = function (evt) {
  16966. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16967. this._pointerX = evt.clientX - canvasRect.left;
  16968. this._pointerY = evt.clientY - canvasRect.top;
  16969. this._unTranslatedPointerX = this._pointerX;
  16970. this._unTranslatedPointerY = this._pointerY;
  16971. };
  16972. Scene.prototype._createUbo = function () {
  16973. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16974. this._sceneUbo.addUniform("viewProjection", 16);
  16975. this._sceneUbo.addUniform("view", 16);
  16976. };
  16977. // Pointers handling
  16978. /**
  16979. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16980. * @param attachUp defines if you want to attach events to pointerup
  16981. * @param attachDown defines if you want to attach events to pointerdown
  16982. * @param attachMove defines if you want to attach events to pointermove
  16983. */
  16984. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16985. var _this = this;
  16986. if (attachUp === void 0) { attachUp = true; }
  16987. if (attachDown === void 0) { attachDown = true; }
  16988. if (attachMove === void 0) { attachMove = true; }
  16989. this._initActionManager = function (act, clickInfo) {
  16990. if (!_this._meshPickProceed) {
  16991. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16992. _this._currentPickResult = pickResult;
  16993. if (pickResult) {
  16994. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16995. }
  16996. _this._meshPickProceed = true;
  16997. }
  16998. return act;
  16999. };
  17000. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17001. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17002. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17003. btn !== _this._previousButtonPressed) {
  17004. _this._doubleClickOccured = false;
  17005. clickInfo.singleClick = true;
  17006. clickInfo.ignore = false;
  17007. cb(clickInfo, _this._currentPickResult);
  17008. }
  17009. };
  17010. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17011. var clickInfo = new ClickInfo();
  17012. _this._currentPickResult = null;
  17013. var act;
  17014. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  17015. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  17016. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17017. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17018. act = _this._initActionManager(act, clickInfo);
  17019. if (act)
  17020. checkPicking = act.hasPickTriggers;
  17021. }
  17022. if (checkPicking) {
  17023. var btn = evt.button;
  17024. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17025. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17026. if (!clickInfo.hasSwiped) {
  17027. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17028. if (!checkSingleClickImmediately) {
  17029. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  17030. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17031. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17032. act = _this._initActionManager(act, clickInfo);
  17033. if (act)
  17034. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17035. }
  17036. }
  17037. if (checkSingleClickImmediately) {
  17038. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17039. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17040. btn !== _this._previousButtonPressed) {
  17041. clickInfo.singleClick = true;
  17042. cb(clickInfo, _this._currentPickResult);
  17043. }
  17044. }
  17045. else {
  17046. // wait that no double click has been raised during the double click delay
  17047. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17048. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17049. }
  17050. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  17051. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17052. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17053. act = _this._initActionManager(act, clickInfo);
  17054. if (act)
  17055. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17056. }
  17057. if (checkDoubleClick) {
  17058. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17059. if (btn === _this._previousButtonPressed &&
  17060. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17061. !_this._doubleClickOccured) {
  17062. // pointer has not moved for 2 clicks, it's a double click
  17063. if (!clickInfo.hasSwiped &&
  17064. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17065. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17066. _this._previousStartingPointerTime = 0;
  17067. _this._doubleClickOccured = true;
  17068. clickInfo.doubleClick = true;
  17069. clickInfo.ignore = false;
  17070. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17071. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17072. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17073. cb(clickInfo, _this._currentPickResult);
  17074. }
  17075. else {
  17076. _this._doubleClickOccured = false;
  17077. _this._previousStartingPointerTime = _this._startingPointerTime;
  17078. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17079. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17080. _this._previousButtonPressed = btn;
  17081. _this._previousHasSwiped = clickInfo.hasSwiped;
  17082. if (Scene.ExclusiveDoubleClickMode) {
  17083. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17084. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17085. }
  17086. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17087. cb(clickInfo, _this._previousPickResult);
  17088. }
  17089. else {
  17090. cb(clickInfo, _this._currentPickResult);
  17091. }
  17092. }
  17093. }
  17094. else {
  17095. _this._doubleClickOccured = false;
  17096. _this._previousStartingPointerTime = _this._startingPointerTime;
  17097. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17098. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17099. _this._previousButtonPressed = btn;
  17100. _this._previousHasSwiped = clickInfo.hasSwiped;
  17101. }
  17102. }
  17103. }
  17104. }
  17105. clickInfo.ignore = true;
  17106. cb(clickInfo, _this._currentPickResult);
  17107. };
  17108. var spritePredicate = function (sprite) {
  17109. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17110. };
  17111. this._onPointerMove = function (evt) {
  17112. _this._updatePointerPosition(evt);
  17113. // PreObservable support
  17114. if (_this.onPrePointerObservable.hasObservers()) {
  17115. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17116. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17117. _this.onPrePointerObservable.notifyObservers(pi, type);
  17118. if (pi.skipOnPointerObservable) {
  17119. return;
  17120. }
  17121. }
  17122. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17123. return;
  17124. }
  17125. var canvas = _this._engine.getRenderingCanvas();
  17126. if (!_this.pointerMovePredicate) {
  17127. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17128. }
  17129. // Meshes
  17130. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17131. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17132. _this.setPointerOverSprite(null);
  17133. _this.setPointerOverMesh(pickResult.pickedMesh);
  17134. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17135. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17136. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17137. }
  17138. else {
  17139. canvas.style.cursor = _this.hoverCursor;
  17140. }
  17141. }
  17142. else {
  17143. canvas.style.cursor = _this.defaultCursor;
  17144. }
  17145. }
  17146. else {
  17147. _this.setPointerOverMesh(null);
  17148. // Sprites
  17149. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17150. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17151. _this.setPointerOverSprite(pickResult.pickedSprite);
  17152. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17153. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17154. }
  17155. else {
  17156. canvas.style.cursor = _this.hoverCursor;
  17157. }
  17158. }
  17159. else {
  17160. _this.setPointerOverSprite(null);
  17161. // Restore pointer
  17162. canvas.style.cursor = _this.defaultCursor;
  17163. }
  17164. }
  17165. if (_this.onPointerMove) {
  17166. _this.onPointerMove(evt, pickResult);
  17167. }
  17168. if (_this.onPointerObservable.hasObservers()) {
  17169. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17170. var pi = new PointerInfo(type, evt, pickResult);
  17171. _this.onPointerObservable.notifyObservers(pi, type);
  17172. }
  17173. };
  17174. this._onPointerDown = function (evt) {
  17175. _this._isButtonPressed = true;
  17176. _this._pickedDownMesh = null;
  17177. _this._meshPickProceed = false;
  17178. _this._updatePointerPosition(evt);
  17179. // PreObservable support
  17180. if (_this.onPrePointerObservable.hasObservers()) {
  17181. var type = PointerEventTypes.POINTERDOWN;
  17182. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17183. _this.onPrePointerObservable.notifyObservers(pi, type);
  17184. if (pi.skipOnPointerObservable) {
  17185. return;
  17186. }
  17187. }
  17188. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17189. return;
  17190. }
  17191. _this._startingPointerPosition.x = _this._pointerX;
  17192. _this._startingPointerPosition.y = _this._pointerY;
  17193. _this._startingPointerTime = new Date().getTime();
  17194. if (!_this.pointerDownPredicate) {
  17195. _this.pointerDownPredicate = function (mesh) {
  17196. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17197. };
  17198. }
  17199. // Meshes
  17200. _this._pickedDownMesh = null;
  17201. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17202. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17203. _this._pickedDownMesh = pickResult.pickedMesh;
  17204. var actionManager = pickResult.pickedMesh.actionManager;
  17205. if (actionManager) {
  17206. if (actionManager.hasPickTriggers) {
  17207. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17208. switch (evt.button) {
  17209. case 0:
  17210. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17211. break;
  17212. case 1:
  17213. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17214. break;
  17215. case 2:
  17216. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17217. break;
  17218. }
  17219. }
  17220. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17221. window.setTimeout((function () {
  17222. var _this = this;
  17223. 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);
  17224. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17225. if (this._isButtonPressed &&
  17226. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17227. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17228. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17229. this._startingPointerTime = 0;
  17230. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17231. }
  17232. }
  17233. }).bind(_this), Scene.LongPressDelay);
  17234. }
  17235. }
  17236. }
  17237. if (_this.onPointerDown) {
  17238. _this.onPointerDown(evt, pickResult);
  17239. }
  17240. if (_this.onPointerObservable.hasObservers()) {
  17241. var type = PointerEventTypes.POINTERDOWN;
  17242. var pi = new PointerInfo(type, evt, pickResult);
  17243. _this.onPointerObservable.notifyObservers(pi, type);
  17244. }
  17245. // Sprites
  17246. _this._pickedDownSprite = null;
  17247. if (_this.spriteManagers.length > 0) {
  17248. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17249. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17250. if (pickResult.pickedSprite.actionManager) {
  17251. _this._pickedDownSprite = pickResult.pickedSprite;
  17252. switch (evt.button) {
  17253. case 0:
  17254. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17255. break;
  17256. case 1:
  17257. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17258. break;
  17259. case 2:
  17260. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17261. break;
  17262. }
  17263. if (pickResult.pickedSprite.actionManager) {
  17264. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17265. }
  17266. }
  17267. }
  17268. }
  17269. };
  17270. this._onPointerUp = function (evt) {
  17271. _this._isButtonPressed = false;
  17272. _this._pickedUpMesh = null;
  17273. _this._meshPickProceed = false;
  17274. _this._updatePointerPosition(evt);
  17275. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17276. // PreObservable support
  17277. if (this.onPrePointerObservable.hasObservers()) {
  17278. if (!clickInfo.ignore) {
  17279. if (!clickInfo.hasSwiped) {
  17280. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17281. var type = PointerEventTypes.POINTERTAP;
  17282. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17283. this.onPrePointerObservable.notifyObservers(pi, type);
  17284. if (pi.skipOnPointerObservable) {
  17285. return;
  17286. }
  17287. }
  17288. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17289. var type = PointerEventTypes.POINTERDOUBLETAP;
  17290. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17291. this.onPrePointerObservable.notifyObservers(pi, type);
  17292. if (pi.skipOnPointerObservable) {
  17293. return;
  17294. }
  17295. }
  17296. }
  17297. }
  17298. else {
  17299. var type = PointerEventTypes.POINTERUP;
  17300. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17301. this.onPrePointerObservable.notifyObservers(pi, type);
  17302. if (pi.skipOnPointerObservable) {
  17303. return;
  17304. }
  17305. }
  17306. }
  17307. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17308. return;
  17309. }
  17310. if (!this.pointerUpPredicate) {
  17311. this.pointerUpPredicate = function (mesh) {
  17312. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17313. };
  17314. }
  17315. // Meshes
  17316. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17317. this._initActionManager(null, clickInfo);
  17318. }
  17319. if (!pickResult) {
  17320. pickResult = this._currentPickResult;
  17321. }
  17322. if (pickResult && pickResult && pickResult.pickedMesh) {
  17323. this._pickedUpMesh = pickResult.pickedMesh;
  17324. if (this._pickedDownMesh === this._pickedUpMesh) {
  17325. if (this.onPointerPick) {
  17326. this.onPointerPick(evt, pickResult);
  17327. }
  17328. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17329. var type = PointerEventTypes.POINTERPICK;
  17330. var pi = new PointerInfo(type, evt, pickResult);
  17331. this.onPointerObservable.notifyObservers(pi, type);
  17332. }
  17333. }
  17334. if (pickResult.pickedMesh.actionManager) {
  17335. if (clickInfo.ignore) {
  17336. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17337. }
  17338. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17339. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17340. }
  17341. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17342. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17343. }
  17344. }
  17345. }
  17346. if (this._pickedDownMesh &&
  17347. this._pickedDownMesh.actionManager &&
  17348. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17349. this._pickedDownMesh !== this._pickedUpMesh) {
  17350. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17351. }
  17352. if (this.onPointerUp) {
  17353. this.onPointerUp(evt, pickResult);
  17354. }
  17355. if (this.onPointerObservable.hasObservers()) {
  17356. if (!clickInfo.ignore) {
  17357. if (!clickInfo.hasSwiped) {
  17358. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17359. var type = PointerEventTypes.POINTERTAP;
  17360. var pi = new PointerInfo(type, evt, pickResult);
  17361. this.onPointerObservable.notifyObservers(pi, type);
  17362. }
  17363. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17364. var type = PointerEventTypes.POINTERDOUBLETAP;
  17365. var pi = new PointerInfo(type, evt, pickResult);
  17366. this.onPointerObservable.notifyObservers(pi, type);
  17367. }
  17368. }
  17369. }
  17370. else {
  17371. var type = PointerEventTypes.POINTERUP;
  17372. var pi = new PointerInfo(type, evt, pickResult);
  17373. this.onPointerObservable.notifyObservers(pi, type);
  17374. }
  17375. }
  17376. // Sprites
  17377. if (this.spriteManagers.length > 0) {
  17378. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17379. if (pickResult.hit && pickResult.pickedSprite) {
  17380. if (pickResult.pickedSprite.actionManager) {
  17381. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17382. if (pickResult.pickedSprite.actionManager) {
  17383. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17384. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17385. }
  17386. }
  17387. }
  17388. }
  17389. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17390. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17391. }
  17392. }
  17393. this._previousPickResult = this._currentPickResult;
  17394. }).bind(_this));
  17395. };
  17396. this._onKeyDown = function (evt) {
  17397. if (_this.actionManager) {
  17398. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17399. }
  17400. };
  17401. this._onKeyUp = function (evt) {
  17402. if (_this.actionManager) {
  17403. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17404. }
  17405. };
  17406. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17407. var canvas = this._engine.getRenderingCanvas();
  17408. if (attachMove) {
  17409. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17410. // Wheel
  17411. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17412. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17413. }
  17414. if (attachDown) {
  17415. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17416. }
  17417. if (attachUp) {
  17418. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17419. }
  17420. canvas.tabIndex = 1;
  17421. canvas.addEventListener("keydown", this._onKeyDown, false);
  17422. canvas.addEventListener("keyup", this._onKeyUp, false);
  17423. };
  17424. Scene.prototype.detachControl = function () {
  17425. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17426. var canvas = this._engine.getRenderingCanvas();
  17427. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17428. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17429. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17430. // Wheel
  17431. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17432. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17433. canvas.removeEventListener("keydown", this._onKeyDown);
  17434. canvas.removeEventListener("keyup", this._onKeyUp);
  17435. };
  17436. // Ready
  17437. Scene.prototype.isReady = function () {
  17438. if (this._pendingData.length > 0) {
  17439. return false;
  17440. }
  17441. var index;
  17442. // Geometries
  17443. for (index = 0; index < this._geometries.length; index++) {
  17444. var geometry = this._geometries[index];
  17445. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17446. return false;
  17447. }
  17448. }
  17449. // Meshes
  17450. for (index = 0; index < this.meshes.length; index++) {
  17451. var mesh = this.meshes[index];
  17452. if (!mesh.isEnabled()) {
  17453. continue;
  17454. }
  17455. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17456. continue;
  17457. }
  17458. if (!mesh.isReady()) {
  17459. return false;
  17460. }
  17461. var mat = mesh.material;
  17462. if (mat) {
  17463. if (!mat.isReady(mesh)) {
  17464. return false;
  17465. }
  17466. }
  17467. }
  17468. return true;
  17469. };
  17470. Scene.prototype.resetCachedMaterial = function () {
  17471. this._cachedMaterial = null;
  17472. this._cachedEffect = null;
  17473. this._cachedVisibility = null;
  17474. };
  17475. Scene.prototype.registerBeforeRender = function (func) {
  17476. this.onBeforeRenderObservable.add(func);
  17477. };
  17478. Scene.prototype.unregisterBeforeRender = function (func) {
  17479. this.onBeforeRenderObservable.removeCallback(func);
  17480. };
  17481. Scene.prototype.registerAfterRender = function (func) {
  17482. this.onAfterRenderObservable.add(func);
  17483. };
  17484. Scene.prototype.unregisterAfterRender = function (func) {
  17485. this.onAfterRenderObservable.removeCallback(func);
  17486. };
  17487. Scene.prototype._addPendingData = function (data) {
  17488. this._pendingData.push(data);
  17489. };
  17490. Scene.prototype._removePendingData = function (data) {
  17491. var index = this._pendingData.indexOf(data);
  17492. if (index !== -1) {
  17493. this._pendingData.splice(index, 1);
  17494. }
  17495. };
  17496. Scene.prototype.getWaitingItemsCount = function () {
  17497. return this._pendingData.length;
  17498. };
  17499. /**
  17500. * Registers a function to be executed when the scene is ready.
  17501. * @param {Function} func - the function to be executed.
  17502. */
  17503. Scene.prototype.executeWhenReady = function (func) {
  17504. var _this = this;
  17505. this.onReadyObservable.add(func);
  17506. if (this._executeWhenReadyTimeoutId !== -1) {
  17507. return;
  17508. }
  17509. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17510. _this._checkIsReady();
  17511. }, 150);
  17512. };
  17513. Scene.prototype._checkIsReady = function () {
  17514. var _this = this;
  17515. if (this.isReady()) {
  17516. this.onReadyObservable.notifyObservers(this);
  17517. this.onReadyObservable.clear();
  17518. this._executeWhenReadyTimeoutId = -1;
  17519. return;
  17520. }
  17521. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17522. _this._checkIsReady();
  17523. }, 150);
  17524. };
  17525. // Animations
  17526. /**
  17527. * Will start the animation sequence of a given target
  17528. * @param target - the target
  17529. * @param {number} from - from which frame should animation start
  17530. * @param {number} to - till which frame should animation run.
  17531. * @param {boolean} [loop] - should the animation loop
  17532. * @param {number} [speedRatio] - the speed in which to run the animation
  17533. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17534. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17535. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17536. * See BABYLON.Animatable
  17537. */
  17538. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17539. if (speedRatio === void 0) { speedRatio = 1.0; }
  17540. if (from > to && speedRatio > 0) {
  17541. speedRatio *= -1;
  17542. }
  17543. this.stopAnimation(target);
  17544. if (!animatable) {
  17545. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17546. }
  17547. // Local animations
  17548. if (target.animations) {
  17549. animatable.appendAnimations(target, target.animations);
  17550. }
  17551. // Children animations
  17552. if (target.getAnimatables) {
  17553. var animatables = target.getAnimatables();
  17554. for (var index = 0; index < animatables.length; index++) {
  17555. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17556. }
  17557. }
  17558. animatable.reset();
  17559. return animatable;
  17560. };
  17561. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17562. if (speedRatio === undefined) {
  17563. speedRatio = 1.0;
  17564. }
  17565. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17566. return animatable;
  17567. };
  17568. Scene.prototype.getAnimatableByTarget = function (target) {
  17569. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17570. if (this._activeAnimatables[index].target === target) {
  17571. return this._activeAnimatables[index];
  17572. }
  17573. }
  17574. return null;
  17575. };
  17576. Object.defineProperty(Scene.prototype, "Animatables", {
  17577. get: function () {
  17578. return this._activeAnimatables;
  17579. },
  17580. enumerable: true,
  17581. configurable: true
  17582. });
  17583. /**
  17584. * Will stop the animation of the given target
  17585. * @param target - the target
  17586. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17587. * @see beginAnimation
  17588. */
  17589. Scene.prototype.stopAnimation = function (target, animationName) {
  17590. var animatable = this.getAnimatableByTarget(target);
  17591. if (animatable) {
  17592. animatable.stop(animationName);
  17593. }
  17594. };
  17595. Scene.prototype._animate = function () {
  17596. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17597. return;
  17598. }
  17599. // Getting time
  17600. var now = BABYLON.Tools.Now;
  17601. if (!this._animationTimeLast) {
  17602. if (this._pendingData.length > 0) {
  17603. return;
  17604. }
  17605. this._animationTimeLast = now;
  17606. }
  17607. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17608. this._animationTime += deltaTime;
  17609. this._animationTimeLast = now;
  17610. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17611. this._activeAnimatables[index]._animate(this._animationTime);
  17612. }
  17613. };
  17614. // Matrix
  17615. Scene.prototype.getViewMatrix = function () {
  17616. return this._viewMatrix;
  17617. };
  17618. Scene.prototype.getProjectionMatrix = function () {
  17619. return this._projectionMatrix;
  17620. };
  17621. Scene.prototype.getTransformMatrix = function () {
  17622. return this._transformMatrix;
  17623. };
  17624. Scene.prototype.setTransformMatrix = function (view, projection) {
  17625. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17626. return;
  17627. }
  17628. this._viewUpdateFlag = view.updateFlag;
  17629. this._projectionUpdateFlag = projection.updateFlag;
  17630. this._viewMatrix = view;
  17631. this._projectionMatrix = projection;
  17632. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17633. // Update frustum
  17634. if (!this._frustumPlanes) {
  17635. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17636. }
  17637. else {
  17638. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17639. }
  17640. if (this._sceneUbo.useUbo) {
  17641. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17642. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17643. this._sceneUbo.update();
  17644. }
  17645. };
  17646. Scene.prototype.getSceneUniformBuffer = function () {
  17647. return this._sceneUbo;
  17648. };
  17649. // Methods
  17650. Scene.prototype.getUniqueId = function () {
  17651. var result = this._uniqueIdCounter;
  17652. this._uniqueIdCounter++;
  17653. return result;
  17654. };
  17655. Scene.prototype.addMesh = function (newMesh) {
  17656. newMesh.uniqueId = this.getUniqueId();
  17657. var position = this.meshes.push(newMesh);
  17658. //notify the collision coordinator
  17659. if (this.collisionCoordinator) {
  17660. this.collisionCoordinator.onMeshAdded(newMesh);
  17661. }
  17662. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17663. };
  17664. Scene.prototype.removeMesh = function (toRemove) {
  17665. var index = this.meshes.indexOf(toRemove);
  17666. if (index !== -1) {
  17667. // Remove from the scene if mesh found
  17668. this.meshes.splice(index, 1);
  17669. }
  17670. //notify the collision coordinator
  17671. if (this.collisionCoordinator) {
  17672. this.collisionCoordinator.onMeshRemoved(toRemove);
  17673. }
  17674. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17675. return index;
  17676. };
  17677. Scene.prototype.removeSkeleton = function (toRemove) {
  17678. var index = this.skeletons.indexOf(toRemove);
  17679. if (index !== -1) {
  17680. // Remove from the scene if found
  17681. this.skeletons.splice(index, 1);
  17682. }
  17683. return index;
  17684. };
  17685. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17686. var index = this.morphTargetManagers.indexOf(toRemove);
  17687. if (index !== -1) {
  17688. // Remove from the scene if found
  17689. this.morphTargetManagers.splice(index, 1);
  17690. }
  17691. return index;
  17692. };
  17693. Scene.prototype.removeLight = function (toRemove) {
  17694. var index = this.lights.indexOf(toRemove);
  17695. if (index !== -1) {
  17696. // Remove from the scene if mesh found
  17697. this.lights.splice(index, 1);
  17698. this.sortLightsByPriority();
  17699. }
  17700. this.onLightRemovedObservable.notifyObservers(toRemove);
  17701. return index;
  17702. };
  17703. Scene.prototype.removeCamera = function (toRemove) {
  17704. var index = this.cameras.indexOf(toRemove);
  17705. if (index !== -1) {
  17706. // Remove from the scene if mesh found
  17707. this.cameras.splice(index, 1);
  17708. }
  17709. // Remove from activeCameras
  17710. var index2 = this.activeCameras.indexOf(toRemove);
  17711. if (index2 !== -1) {
  17712. // Remove from the scene if mesh found
  17713. this.activeCameras.splice(index2, 1);
  17714. }
  17715. // Reset the activeCamera
  17716. if (this.activeCamera === toRemove) {
  17717. if (this.cameras.length > 0) {
  17718. this.activeCamera = this.cameras[0];
  17719. }
  17720. else {
  17721. this.activeCamera = null;
  17722. }
  17723. }
  17724. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17725. return index;
  17726. };
  17727. Scene.prototype.addLight = function (newLight) {
  17728. newLight.uniqueId = this.getUniqueId();
  17729. this.lights.push(newLight);
  17730. this.sortLightsByPriority();
  17731. this.onNewLightAddedObservable.notifyObservers(newLight);
  17732. };
  17733. Scene.prototype.sortLightsByPriority = function () {
  17734. if (this.requireLightSorting) {
  17735. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17736. }
  17737. };
  17738. Scene.prototype.addCamera = function (newCamera) {
  17739. newCamera.uniqueId = this.getUniqueId();
  17740. var position = this.cameras.push(newCamera);
  17741. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17742. };
  17743. /**
  17744. * Switch active camera
  17745. * @param {Camera} newCamera - new active camera
  17746. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17747. */
  17748. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17749. if (attachControl === void 0) { attachControl = true; }
  17750. var canvas = this._engine.getRenderingCanvas();
  17751. this.activeCamera.detachControl(canvas);
  17752. this.activeCamera = newCamera;
  17753. if (attachControl) {
  17754. newCamera.attachControl(canvas);
  17755. }
  17756. };
  17757. /**
  17758. * sets the active camera of the scene using its ID
  17759. * @param {string} id - the camera's ID
  17760. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17761. * @see activeCamera
  17762. */
  17763. Scene.prototype.setActiveCameraByID = function (id) {
  17764. var camera = this.getCameraByID(id);
  17765. if (camera) {
  17766. this.activeCamera = camera;
  17767. return camera;
  17768. }
  17769. return null;
  17770. };
  17771. /**
  17772. * sets the active camera of the scene using its name
  17773. * @param {string} name - the camera's name
  17774. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17775. * @see activeCamera
  17776. */
  17777. Scene.prototype.setActiveCameraByName = function (name) {
  17778. var camera = this.getCameraByName(name);
  17779. if (camera) {
  17780. this.activeCamera = camera;
  17781. return camera;
  17782. }
  17783. return null;
  17784. };
  17785. /**
  17786. * get a material using its id
  17787. * @param {string} the material's ID
  17788. * @return {BABYLON.Material|null} the material or null if none found.
  17789. */
  17790. Scene.prototype.getMaterialByID = function (id) {
  17791. for (var index = 0; index < this.materials.length; index++) {
  17792. if (this.materials[index].id === id) {
  17793. return this.materials[index];
  17794. }
  17795. }
  17796. return null;
  17797. };
  17798. /**
  17799. * get a material using its name
  17800. * @param {string} the material's name
  17801. * @return {BABYLON.Material|null} the material or null if none found.
  17802. */
  17803. Scene.prototype.getMaterialByName = function (name) {
  17804. for (var index = 0; index < this.materials.length; index++) {
  17805. if (this.materials[index].name === name) {
  17806. return this.materials[index];
  17807. }
  17808. }
  17809. return null;
  17810. };
  17811. Scene.prototype.getLensFlareSystemByName = function (name) {
  17812. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17813. if (this.lensFlareSystems[index].name === name) {
  17814. return this.lensFlareSystems[index];
  17815. }
  17816. }
  17817. return null;
  17818. };
  17819. Scene.prototype.getLensFlareSystemByID = function (id) {
  17820. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17821. if (this.lensFlareSystems[index].id === id) {
  17822. return this.lensFlareSystems[index];
  17823. }
  17824. }
  17825. return null;
  17826. };
  17827. Scene.prototype.getCameraByID = function (id) {
  17828. for (var index = 0; index < this.cameras.length; index++) {
  17829. if (this.cameras[index].id === id) {
  17830. return this.cameras[index];
  17831. }
  17832. }
  17833. return null;
  17834. };
  17835. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17836. for (var index = 0; index < this.cameras.length; index++) {
  17837. if (this.cameras[index].uniqueId === uniqueId) {
  17838. return this.cameras[index];
  17839. }
  17840. }
  17841. return null;
  17842. };
  17843. /**
  17844. * get a camera using its name
  17845. * @param {string} the camera's name
  17846. * @return {BABYLON.Camera|null} the camera or null if none found.
  17847. */
  17848. Scene.prototype.getCameraByName = function (name) {
  17849. for (var index = 0; index < this.cameras.length; index++) {
  17850. if (this.cameras[index].name === name) {
  17851. return this.cameras[index];
  17852. }
  17853. }
  17854. return null;
  17855. };
  17856. /**
  17857. * get a bone using its id
  17858. * @param {string} the bone's id
  17859. * @return {BABYLON.Bone|null} the bone or null if not found
  17860. */
  17861. Scene.prototype.getBoneByID = function (id) {
  17862. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17863. var skeleton = this.skeletons[skeletonIndex];
  17864. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17865. if (skeleton.bones[boneIndex].id === id) {
  17866. return skeleton.bones[boneIndex];
  17867. }
  17868. }
  17869. }
  17870. return null;
  17871. };
  17872. /**
  17873. * get a bone using its id
  17874. * @param {string} the bone's name
  17875. * @return {BABYLON.Bone|null} the bone or null if not found
  17876. */
  17877. Scene.prototype.getBoneByName = function (name) {
  17878. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17879. var skeleton = this.skeletons[skeletonIndex];
  17880. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17881. if (skeleton.bones[boneIndex].name === name) {
  17882. return skeleton.bones[boneIndex];
  17883. }
  17884. }
  17885. }
  17886. return null;
  17887. };
  17888. /**
  17889. * get a light node using its name
  17890. * @param {string} the light's name
  17891. * @return {BABYLON.Light|null} the light or null if none found.
  17892. */
  17893. Scene.prototype.getLightByName = function (name) {
  17894. for (var index = 0; index < this.lights.length; index++) {
  17895. if (this.lights[index].name === name) {
  17896. return this.lights[index];
  17897. }
  17898. }
  17899. return null;
  17900. };
  17901. /**
  17902. * get a light node using its ID
  17903. * @param {string} the light's id
  17904. * @return {BABYLON.Light|null} the light or null if none found.
  17905. */
  17906. Scene.prototype.getLightByID = function (id) {
  17907. for (var index = 0; index < this.lights.length; index++) {
  17908. if (this.lights[index].id === id) {
  17909. return this.lights[index];
  17910. }
  17911. }
  17912. return null;
  17913. };
  17914. /**
  17915. * get a light node using its scene-generated unique ID
  17916. * @param {number} the light's unique id
  17917. * @return {BABYLON.Light|null} the light or null if none found.
  17918. */
  17919. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17920. for (var index = 0; index < this.lights.length; index++) {
  17921. if (this.lights[index].uniqueId === uniqueId) {
  17922. return this.lights[index];
  17923. }
  17924. }
  17925. return null;
  17926. };
  17927. /**
  17928. * get a particle system by id
  17929. * @param id {number} the particle system id
  17930. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  17931. */
  17932. Scene.prototype.getParticleSystemByID = function (id) {
  17933. for (var index = 0; index < this.particleSystems.length; index++) {
  17934. if (this.particleSystems[index].id === id) {
  17935. return this.particleSystems[index];
  17936. }
  17937. }
  17938. return null;
  17939. };
  17940. /**
  17941. * get a geometry using its ID
  17942. * @param {string} the geometry's id
  17943. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17944. */
  17945. Scene.prototype.getGeometryByID = function (id) {
  17946. for (var index = 0; index < this._geometries.length; index++) {
  17947. if (this._geometries[index].id === id) {
  17948. return this._geometries[index];
  17949. }
  17950. }
  17951. return null;
  17952. };
  17953. /**
  17954. * add a new geometry to this scene.
  17955. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17956. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17957. * @return {boolean} was the geometry added or not
  17958. */
  17959. Scene.prototype.pushGeometry = function (geometry, force) {
  17960. if (!force && this.getGeometryByID(geometry.id)) {
  17961. return false;
  17962. }
  17963. this._geometries.push(geometry);
  17964. //notify the collision coordinator
  17965. if (this.collisionCoordinator) {
  17966. this.collisionCoordinator.onGeometryAdded(geometry);
  17967. }
  17968. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17969. return true;
  17970. };
  17971. /**
  17972. * Removes an existing geometry
  17973. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17974. * @return {boolean} was the geometry removed or not
  17975. */
  17976. Scene.prototype.removeGeometry = function (geometry) {
  17977. var index = this._geometries.indexOf(geometry);
  17978. if (index > -1) {
  17979. this._geometries.splice(index, 1);
  17980. //notify the collision coordinator
  17981. if (this.collisionCoordinator) {
  17982. this.collisionCoordinator.onGeometryDeleted(geometry);
  17983. }
  17984. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17985. return true;
  17986. }
  17987. return false;
  17988. };
  17989. Scene.prototype.getGeometries = function () {
  17990. return this._geometries;
  17991. };
  17992. /**
  17993. * Get the first added mesh found of a given ID
  17994. * @param {string} id - the id to search for
  17995. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17996. */
  17997. Scene.prototype.getMeshByID = function (id) {
  17998. for (var index = 0; index < this.meshes.length; index++) {
  17999. if (this.meshes[index].id === id) {
  18000. return this.meshes[index];
  18001. }
  18002. }
  18003. return null;
  18004. };
  18005. Scene.prototype.getMeshesByID = function (id) {
  18006. return this.meshes.filter(function (m) {
  18007. return m.id === id;
  18008. });
  18009. };
  18010. /**
  18011. * Get a mesh with its auto-generated unique id
  18012. * @param {number} uniqueId - the unique id to search for
  18013. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18014. */
  18015. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18016. for (var index = 0; index < this.meshes.length; index++) {
  18017. if (this.meshes[index].uniqueId === uniqueId) {
  18018. return this.meshes[index];
  18019. }
  18020. }
  18021. return null;
  18022. };
  18023. /**
  18024. * Get a the last added mesh found of a given ID
  18025. * @param {string} id - the id to search for
  18026. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18027. */
  18028. Scene.prototype.getLastMeshByID = function (id) {
  18029. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18030. if (this.meshes[index].id === id) {
  18031. return this.meshes[index];
  18032. }
  18033. }
  18034. return null;
  18035. };
  18036. /**
  18037. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18038. * @param {string} id - the id to search for
  18039. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18040. */
  18041. Scene.prototype.getLastEntryByID = function (id) {
  18042. var index;
  18043. for (index = this.meshes.length - 1; index >= 0; index--) {
  18044. if (this.meshes[index].id === id) {
  18045. return this.meshes[index];
  18046. }
  18047. }
  18048. for (index = this.cameras.length - 1; index >= 0; index--) {
  18049. if (this.cameras[index].id === id) {
  18050. return this.cameras[index];
  18051. }
  18052. }
  18053. for (index = this.lights.length - 1; index >= 0; index--) {
  18054. if (this.lights[index].id === id) {
  18055. return this.lights[index];
  18056. }
  18057. }
  18058. return null;
  18059. };
  18060. Scene.prototype.getNodeByID = function (id) {
  18061. var mesh = this.getMeshByID(id);
  18062. if (mesh) {
  18063. return mesh;
  18064. }
  18065. var light = this.getLightByID(id);
  18066. if (light) {
  18067. return light;
  18068. }
  18069. var camera = this.getCameraByID(id);
  18070. if (camera) {
  18071. return camera;
  18072. }
  18073. var bone = this.getBoneByID(id);
  18074. return bone;
  18075. };
  18076. Scene.prototype.getNodeByName = function (name) {
  18077. var mesh = this.getMeshByName(name);
  18078. if (mesh) {
  18079. return mesh;
  18080. }
  18081. var light = this.getLightByName(name);
  18082. if (light) {
  18083. return light;
  18084. }
  18085. var camera = this.getCameraByName(name);
  18086. if (camera) {
  18087. return camera;
  18088. }
  18089. var bone = this.getBoneByName(name);
  18090. return bone;
  18091. };
  18092. Scene.prototype.getMeshByName = function (name) {
  18093. for (var index = 0; index < this.meshes.length; index++) {
  18094. if (this.meshes[index].name === name) {
  18095. return this.meshes[index];
  18096. }
  18097. }
  18098. return null;
  18099. };
  18100. Scene.prototype.getSoundByName = function (name) {
  18101. var index;
  18102. if (BABYLON.AudioEngine) {
  18103. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18104. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18105. return this.mainSoundTrack.soundCollection[index];
  18106. }
  18107. }
  18108. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18109. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18110. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18111. return this.soundTracks[sdIndex].soundCollection[index];
  18112. }
  18113. }
  18114. }
  18115. }
  18116. return null;
  18117. };
  18118. Scene.prototype.getLastSkeletonByID = function (id) {
  18119. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18120. if (this.skeletons[index].id === id) {
  18121. return this.skeletons[index];
  18122. }
  18123. }
  18124. return null;
  18125. };
  18126. Scene.prototype.getSkeletonById = function (id) {
  18127. for (var index = 0; index < this.skeletons.length; index++) {
  18128. if (this.skeletons[index].id === id) {
  18129. return this.skeletons[index];
  18130. }
  18131. }
  18132. return null;
  18133. };
  18134. Scene.prototype.getSkeletonByName = function (name) {
  18135. for (var index = 0; index < this.skeletons.length; index++) {
  18136. if (this.skeletons[index].name === name) {
  18137. return this.skeletons[index];
  18138. }
  18139. }
  18140. return null;
  18141. };
  18142. Scene.prototype.getMorphTargetManagerById = function (id) {
  18143. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18144. if (this.morphTargetManagers[index].uniqueId === id) {
  18145. return this.morphTargetManagers[index];
  18146. }
  18147. }
  18148. return null;
  18149. };
  18150. Scene.prototype.isActiveMesh = function (mesh) {
  18151. return (this._activeMeshes.indexOf(mesh) !== -1);
  18152. };
  18153. /**
  18154. * Return a the first highlight layer of the scene with a given name.
  18155. * @param name The name of the highlight layer to look for.
  18156. * @return The highlight layer if found otherwise null.
  18157. */
  18158. Scene.prototype.getHighlightLayerByName = function (name) {
  18159. for (var index = 0; index < this.highlightLayers.length; index++) {
  18160. if (this.highlightLayers[index].name === name) {
  18161. return this.highlightLayers[index];
  18162. }
  18163. }
  18164. return null;
  18165. };
  18166. Object.defineProperty(Scene.prototype, "uid", {
  18167. /**
  18168. * Return a unique id as a string which can serve as an identifier for the scene
  18169. */
  18170. get: function () {
  18171. if (!this._uid) {
  18172. this._uid = BABYLON.Tools.RandomId();
  18173. }
  18174. return this._uid;
  18175. },
  18176. enumerable: true,
  18177. configurable: true
  18178. });
  18179. /**
  18180. * Add an externaly attached data from its key.
  18181. * This method call will fail and return false, if such key already exists.
  18182. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18183. * @param key the unique key that identifies the data
  18184. * @param data the data object to associate to the key for this Engine instance
  18185. * @return true if no such key were already present and the data was added successfully, false otherwise
  18186. */
  18187. Scene.prototype.addExternalData = function (key, data) {
  18188. if (!this._externalData) {
  18189. this._externalData = new BABYLON.StringDictionary();
  18190. }
  18191. return this._externalData.add(key, data);
  18192. };
  18193. /**
  18194. * Get an externaly attached data from its key
  18195. * @param key the unique key that identifies the data
  18196. * @return the associated data, if present (can be null), or undefined if not present
  18197. */
  18198. Scene.prototype.getExternalData = function (key) {
  18199. if (!this._externalData) {
  18200. return null;
  18201. }
  18202. return this._externalData.get(key);
  18203. };
  18204. /**
  18205. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18206. * @param key the unique key that identifies the data
  18207. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18208. * @return the associated data, can be null if the factory returned null.
  18209. */
  18210. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18211. if (!this._externalData) {
  18212. this._externalData = new BABYLON.StringDictionary();
  18213. }
  18214. return this._externalData.getOrAddWithFactory(key, factory);
  18215. };
  18216. /**
  18217. * Remove an externaly attached data from the Engine instance
  18218. * @param key the unique key that identifies the data
  18219. * @return true if the data was successfully removed, false if it doesn't exist
  18220. */
  18221. Scene.prototype.removeExternalData = function (key) {
  18222. return this._externalData.remove(key);
  18223. };
  18224. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18225. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18226. var material = subMesh.getMaterial();
  18227. if (mesh.showSubMeshesBoundingBox) {
  18228. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18229. }
  18230. if (material) {
  18231. // Render targets
  18232. if (material.getRenderTargetTextures) {
  18233. if (this._processedMaterials.indexOf(material) === -1) {
  18234. this._processedMaterials.push(material);
  18235. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18236. }
  18237. }
  18238. // Dispatch
  18239. this._activeIndices.addCount(subMesh.indexCount, false);
  18240. this._renderingManager.dispatch(subMesh);
  18241. }
  18242. }
  18243. };
  18244. Scene.prototype._isInIntermediateRendering = function () {
  18245. return this._intermediateRendering;
  18246. };
  18247. Scene.prototype._evaluateActiveMeshes = function () {
  18248. this.activeCamera._activeMeshes.reset();
  18249. this._activeMeshes.reset();
  18250. this._renderingManager.reset();
  18251. this._processedMaterials.reset();
  18252. this._activeParticleSystems.reset();
  18253. this._activeSkeletons.reset();
  18254. this._softwareSkinnedMeshes.reset();
  18255. if (this._boundingBoxRenderer) {
  18256. this._boundingBoxRenderer.reset();
  18257. }
  18258. // Meshes
  18259. var meshes;
  18260. var len;
  18261. if (this._selectionOctree) {
  18262. var selection = this._selectionOctree.select(this._frustumPlanes);
  18263. meshes = selection.data;
  18264. len = selection.length;
  18265. }
  18266. else {
  18267. len = this.meshes.length;
  18268. meshes = this.meshes;
  18269. }
  18270. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18271. var mesh = meshes[meshIndex];
  18272. if (mesh.isBlocked) {
  18273. continue;
  18274. }
  18275. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18276. if (!mesh.isReady() || !mesh.isEnabled()) {
  18277. continue;
  18278. }
  18279. mesh.computeWorldMatrix();
  18280. // Intersections
  18281. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18282. this._meshesForIntersections.pushNoDuplicate(mesh);
  18283. }
  18284. // Switch to current LOD
  18285. var meshLOD = mesh.getLOD(this.activeCamera);
  18286. if (!meshLOD) {
  18287. continue;
  18288. }
  18289. mesh._preActivate();
  18290. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18291. this._activeMeshes.push(mesh);
  18292. this.activeCamera._activeMeshes.push(mesh);
  18293. mesh._activate(this._renderId);
  18294. if (meshLOD !== mesh) {
  18295. meshLOD._activate(this._renderId);
  18296. }
  18297. this._activeMesh(mesh, meshLOD);
  18298. }
  18299. }
  18300. // Particle systems
  18301. this._particlesDuration.beginMonitoring();
  18302. var beforeParticlesDate = BABYLON.Tools.Now;
  18303. if (this.particlesEnabled) {
  18304. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18305. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18306. var particleSystem = this.particleSystems[particleIndex];
  18307. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18308. continue;
  18309. }
  18310. var emitter = particleSystem.emitter;
  18311. if (!emitter.position || emitter.isEnabled()) {
  18312. this._activeParticleSystems.push(particleSystem);
  18313. particleSystem.animate();
  18314. this._renderingManager.dispatchParticles(particleSystem);
  18315. }
  18316. }
  18317. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18318. }
  18319. this._particlesDuration.endMonitoring(false);
  18320. };
  18321. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18322. if (mesh.skeleton && this.skeletonsEnabled) {
  18323. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18324. mesh.skeleton.prepare();
  18325. }
  18326. if (!mesh.computeBonesUsingShaders) {
  18327. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18328. }
  18329. }
  18330. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18331. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18332. }
  18333. if (mesh && mesh.subMeshes) {
  18334. // Submeshes Octrees
  18335. var len;
  18336. var subMeshes;
  18337. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18338. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18339. len = intersections.length;
  18340. subMeshes = intersections.data;
  18341. }
  18342. else {
  18343. subMeshes = mesh.subMeshes;
  18344. len = subMeshes.length;
  18345. }
  18346. for (var subIndex = 0; subIndex < len; subIndex++) {
  18347. var subMesh = subMeshes[subIndex];
  18348. this._evaluateSubMesh(subMesh, mesh);
  18349. }
  18350. }
  18351. };
  18352. Scene.prototype.updateTransformMatrix = function (force) {
  18353. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18354. };
  18355. Scene.prototype._renderForCamera = function (camera) {
  18356. var engine = this._engine;
  18357. var startTime = BABYLON.Tools.Now;
  18358. this.activeCamera = camera;
  18359. if (!this.activeCamera)
  18360. throw new Error("Active camera not set");
  18361. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18362. // Viewport
  18363. engine.setViewport(this.activeCamera.viewport);
  18364. // Camera
  18365. this.resetCachedMaterial();
  18366. this._renderId++;
  18367. this.updateTransformMatrix();
  18368. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18369. // Meshes
  18370. this._evaluateActiveMeshesDuration.beginMonitoring();
  18371. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18372. this._evaluateActiveMeshes();
  18373. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18374. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18375. // Software skinning
  18376. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18377. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18378. mesh.applySkeleton(mesh.skeleton);
  18379. }
  18380. // Render targets
  18381. this._renderTargetsDuration.beginMonitoring();
  18382. var needsRestoreFrameBuffer = false;
  18383. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18384. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18385. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18386. }
  18387. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18388. this._intermediateRendering = true;
  18389. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18390. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18391. var renderTarget = this._renderTargets.data[renderIndex];
  18392. if (renderTarget._shouldRender()) {
  18393. this._renderId++;
  18394. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18395. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18396. }
  18397. }
  18398. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18399. this._intermediateRendering = false;
  18400. this._renderId++;
  18401. needsRestoreFrameBuffer = true; // Restore back buffer
  18402. }
  18403. // Render HighlightLayer Texture
  18404. var stencilState = this._engine.getStencilBuffer();
  18405. var renderhighlights = false;
  18406. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18407. this._intermediateRendering = true;
  18408. for (var i = 0; i < this.highlightLayers.length; i++) {
  18409. var highlightLayer = this.highlightLayers[i];
  18410. if (highlightLayer.shouldRender() &&
  18411. (!highlightLayer.camera ||
  18412. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18413. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18414. renderhighlights = true;
  18415. var renderTarget = highlightLayer._mainTexture;
  18416. if (renderTarget._shouldRender()) {
  18417. this._renderId++;
  18418. renderTarget.render(false, false);
  18419. needsRestoreFrameBuffer = true;
  18420. }
  18421. }
  18422. }
  18423. this._intermediateRendering = false;
  18424. this._renderId++;
  18425. }
  18426. if (needsRestoreFrameBuffer) {
  18427. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18428. }
  18429. this._renderTargetsDuration.endMonitoring(false);
  18430. // Prepare Frame
  18431. this.postProcessManager._prepareFrame();
  18432. this._renderDuration.beginMonitoring();
  18433. // Backgrounds
  18434. var layerIndex;
  18435. var layer;
  18436. if (this.layers.length) {
  18437. engine.setDepthBuffer(false);
  18438. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18439. layer = this.layers[layerIndex];
  18440. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18441. layer.render();
  18442. }
  18443. }
  18444. engine.setDepthBuffer(true);
  18445. }
  18446. // Render
  18447. BABYLON.Tools.StartPerformanceCounter("Main render");
  18448. // Activate HighlightLayer stencil
  18449. if (renderhighlights) {
  18450. this._engine.setStencilBuffer(true);
  18451. }
  18452. this._renderingManager.render(null, null, true, true);
  18453. // Restore HighlightLayer stencil
  18454. if (renderhighlights) {
  18455. this._engine.setStencilBuffer(stencilState);
  18456. }
  18457. BABYLON.Tools.EndPerformanceCounter("Main render");
  18458. // Bounding boxes
  18459. if (this._boundingBoxRenderer) {
  18460. this._boundingBoxRenderer.render();
  18461. }
  18462. // Lens flares
  18463. if (this.lensFlaresEnabled) {
  18464. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18465. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18466. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18467. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18468. lensFlareSystem.render();
  18469. }
  18470. }
  18471. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18472. }
  18473. // Foregrounds
  18474. if (this.layers.length) {
  18475. engine.setDepthBuffer(false);
  18476. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18477. layer = this.layers[layerIndex];
  18478. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18479. layer.render();
  18480. }
  18481. }
  18482. engine.setDepthBuffer(true);
  18483. }
  18484. // Highlight Layer
  18485. if (renderhighlights) {
  18486. engine.setDepthBuffer(false);
  18487. for (var i = 0; i < this.highlightLayers.length; i++) {
  18488. if (this.highlightLayers[i].shouldRender()) {
  18489. this.highlightLayers[i].render();
  18490. }
  18491. }
  18492. engine.setDepthBuffer(true);
  18493. }
  18494. this._renderDuration.endMonitoring(false);
  18495. // Finalize frame
  18496. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18497. // Update camera
  18498. this.activeCamera._updateFromScene();
  18499. // Reset some special arrays
  18500. this._renderTargets.reset();
  18501. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18502. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18503. };
  18504. Scene.prototype._processSubCameras = function (camera) {
  18505. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18506. this._renderForCamera(camera);
  18507. return;
  18508. }
  18509. // rig cameras
  18510. for (var index = 0; index < camera._rigCameras.length; index++) {
  18511. this._renderForCamera(camera._rigCameras[index]);
  18512. }
  18513. this.activeCamera = camera;
  18514. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18515. // Update camera
  18516. this.activeCamera._updateFromScene();
  18517. };
  18518. Scene.prototype._checkIntersections = function () {
  18519. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18520. var sourceMesh = this._meshesForIntersections.data[index];
  18521. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18522. var action = sourceMesh.actionManager.actions[actionIndex];
  18523. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18524. var parameters = action.getTriggerParameter();
  18525. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18526. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18527. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18528. if (areIntersecting && currentIntersectionInProgress === -1) {
  18529. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18530. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18531. sourceMesh._intersectionsInProgress.push(otherMesh);
  18532. }
  18533. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18534. sourceMesh._intersectionsInProgress.push(otherMesh);
  18535. }
  18536. }
  18537. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18538. //They intersected, and now they don't.
  18539. //is this trigger an exit trigger? execute an event.
  18540. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18541. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18542. }
  18543. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18544. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18545. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18546. }
  18547. }
  18548. }
  18549. }
  18550. }
  18551. };
  18552. Scene.prototype.render = function () {
  18553. if (this.isDisposed) {
  18554. return;
  18555. }
  18556. this._lastFrameDuration.beginMonitoring();
  18557. this._particlesDuration.fetchNewFrame();
  18558. this._spritesDuration.fetchNewFrame();
  18559. this._activeParticles.fetchNewFrame();
  18560. this._renderDuration.fetchNewFrame();
  18561. this._renderTargetsDuration.fetchNewFrame();
  18562. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18563. this._totalVertices.fetchNewFrame();
  18564. this._activeIndices.fetchNewFrame();
  18565. this._activeBones.fetchNewFrame();
  18566. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18567. this._meshesForIntersections.reset();
  18568. this.resetCachedMaterial();
  18569. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18570. // Actions
  18571. if (this.actionManager) {
  18572. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18573. }
  18574. //Simplification Queue
  18575. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18576. this.simplificationQueue.executeNext();
  18577. }
  18578. if (this._engine.isDeterministicLockStep()) {
  18579. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18580. var defaultTimeStep = (60.0 / 1000.0);
  18581. if (this._physicsEngine) {
  18582. defaultTimeStep = this._physicsEngine.getTimeStep();
  18583. }
  18584. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18585. this._timeAccumulator += deltaTime;
  18586. // compute the amount of fixed steps we should have taken since the last step
  18587. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18588. internalSteps = Math.min(internalSteps, maxSubSteps);
  18589. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18590. this.onBeforeStepObservable.notifyObservers(this);
  18591. // Animations
  18592. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18593. this._animate();
  18594. // Physics
  18595. if (this._physicsEngine) {
  18596. BABYLON.Tools.StartPerformanceCounter("Physics");
  18597. this._physicsEngine._step(defaultTimeStep);
  18598. BABYLON.Tools.EndPerformanceCounter("Physics");
  18599. }
  18600. this._timeAccumulator -= defaultTimeStep;
  18601. this.onAfterStepObservable.notifyObservers(this);
  18602. this._currentStepId++;
  18603. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18604. // Q: can this be optimized by putting some code in the afterStep callback?
  18605. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18606. // would return incorrect positions for internal stepIds (non-rendered steps)
  18607. this._evaluateActiveMeshes();
  18608. }
  18609. }
  18610. }
  18611. else {
  18612. // Animations
  18613. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18614. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18615. this._animate();
  18616. // Physics
  18617. if (this._physicsEngine) {
  18618. BABYLON.Tools.StartPerformanceCounter("Physics");
  18619. this._physicsEngine._step(deltaTime / 1000.0);
  18620. BABYLON.Tools.EndPerformanceCounter("Physics");
  18621. }
  18622. }
  18623. // Before render
  18624. this.onBeforeRenderObservable.notifyObservers(this);
  18625. // Customs render targets
  18626. this._renderTargetsDuration.beginMonitoring();
  18627. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18628. var engine = this.getEngine();
  18629. var currentActiveCamera = this.activeCamera;
  18630. if (this.renderTargetsEnabled) {
  18631. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18632. this._intermediateRendering = true;
  18633. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18634. var renderTarget = this.customRenderTargets[customIndex];
  18635. if (renderTarget._shouldRender()) {
  18636. this._renderId++;
  18637. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18638. if (!this.activeCamera)
  18639. throw new Error("Active camera not set");
  18640. // Viewport
  18641. engine.setViewport(this.activeCamera.viewport);
  18642. // Camera
  18643. this.updateTransformMatrix();
  18644. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18645. }
  18646. }
  18647. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18648. this._intermediateRendering = false;
  18649. this._renderId++;
  18650. }
  18651. // Restore back buffer
  18652. if (this.customRenderTargets.length > 0) {
  18653. engine.restoreDefaultFramebuffer();
  18654. }
  18655. this._renderTargetsDuration.endMonitoring();
  18656. this.activeCamera = currentActiveCamera;
  18657. // Procedural textures
  18658. if (this.proceduralTexturesEnabled) {
  18659. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18660. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18661. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18662. if (proceduralTexture._shouldRender()) {
  18663. proceduralTexture.render();
  18664. }
  18665. }
  18666. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18667. }
  18668. // Clear
  18669. if (this.autoClearDepthAndStencil || this.autoClear) {
  18670. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18671. }
  18672. // Shadows
  18673. if (this.shadowsEnabled) {
  18674. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18675. var light = this.lights[lightIndex];
  18676. var shadowGenerator = light.getShadowGenerator();
  18677. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18678. var shadowMap = shadowGenerator.getShadowMap();
  18679. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18680. this._renderTargets.push(shadowMap);
  18681. }
  18682. }
  18683. }
  18684. }
  18685. // Depth renderer
  18686. if (this._depthRenderer) {
  18687. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18688. }
  18689. // Geometry renderer
  18690. if (this._geometryBufferRenderer) {
  18691. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18692. }
  18693. // RenderPipeline
  18694. if (this._postProcessRenderPipelineManager) {
  18695. this._postProcessRenderPipelineManager.update();
  18696. }
  18697. // Multi-cameras?
  18698. if (this.activeCameras.length > 0) {
  18699. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18700. if (cameraIndex > 0) {
  18701. this._engine.clear(null, false, true, true);
  18702. }
  18703. this._processSubCameras(this.activeCameras[cameraIndex]);
  18704. }
  18705. }
  18706. else {
  18707. if (!this.activeCamera) {
  18708. throw new Error("No camera defined");
  18709. }
  18710. this._processSubCameras(this.activeCamera);
  18711. }
  18712. // Intersection checks
  18713. this._checkIntersections();
  18714. // Update the audio listener attached to the camera
  18715. if (BABYLON.AudioEngine) {
  18716. this._updateAudioParameters();
  18717. }
  18718. // After render
  18719. if (this.afterRender) {
  18720. this.afterRender();
  18721. }
  18722. this.onAfterRenderObservable.notifyObservers(this);
  18723. // Cleaning
  18724. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18725. this._toBeDisposed.data[index].dispose();
  18726. this._toBeDisposed[index] = null;
  18727. }
  18728. this._toBeDisposed.reset();
  18729. if (this.dumpNextRenderTargets) {
  18730. this.dumpNextRenderTargets = false;
  18731. }
  18732. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18733. this._lastFrameDuration.endMonitoring();
  18734. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18735. this._totalLightsCounter.addCount(this.lights.length, true);
  18736. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18737. this._totalTexturesCounter.addCount(this.textures.length, true);
  18738. this._activeBones.addCount(0, true);
  18739. this._activeIndices.addCount(0, true);
  18740. this._activeParticles.addCount(0, true);
  18741. };
  18742. Scene.prototype._updateAudioParameters = function () {
  18743. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18744. return;
  18745. }
  18746. var listeningCamera;
  18747. var audioEngine = BABYLON.Engine.audioEngine;
  18748. if (this.activeCameras.length > 0) {
  18749. listeningCamera = this.activeCameras[0];
  18750. }
  18751. else {
  18752. listeningCamera = this.activeCamera;
  18753. }
  18754. if (listeningCamera && audioEngine.canUseWebAudio) {
  18755. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18756. // for VR cameras
  18757. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18758. listeningCamera = listeningCamera.rigCameras[0];
  18759. }
  18760. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18761. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18762. cameraDirection.normalize();
  18763. // To avoid some errors on GearVR
  18764. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18765. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18766. }
  18767. var i;
  18768. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18769. var sound = this.mainSoundTrack.soundCollection[i];
  18770. if (sound.useCustomAttenuation) {
  18771. sound.updateDistanceFromListener();
  18772. }
  18773. }
  18774. for (i = 0; i < this.soundTracks.length; i++) {
  18775. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18776. sound = this.soundTracks[i].soundCollection[j];
  18777. if (sound.useCustomAttenuation) {
  18778. sound.updateDistanceFromListener();
  18779. }
  18780. }
  18781. }
  18782. }
  18783. };
  18784. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18785. // Audio
  18786. get: function () {
  18787. return this._audioEnabled;
  18788. },
  18789. set: function (value) {
  18790. this._audioEnabled = value;
  18791. if (BABYLON.AudioEngine) {
  18792. if (this._audioEnabled) {
  18793. this._enableAudio();
  18794. }
  18795. else {
  18796. this._disableAudio();
  18797. }
  18798. }
  18799. },
  18800. enumerable: true,
  18801. configurable: true
  18802. });
  18803. Scene.prototype._disableAudio = function () {
  18804. var i;
  18805. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18806. this.mainSoundTrack.soundCollection[i].pause();
  18807. }
  18808. for (i = 0; i < this.soundTracks.length; i++) {
  18809. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18810. this.soundTracks[i].soundCollection[j].pause();
  18811. }
  18812. }
  18813. };
  18814. Scene.prototype._enableAudio = function () {
  18815. var i;
  18816. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18817. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18818. this.mainSoundTrack.soundCollection[i].play();
  18819. }
  18820. }
  18821. for (i = 0; i < this.soundTracks.length; i++) {
  18822. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18823. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18824. this.soundTracks[i].soundCollection[j].play();
  18825. }
  18826. }
  18827. }
  18828. };
  18829. Object.defineProperty(Scene.prototype, "headphone", {
  18830. get: function () {
  18831. return this._headphone;
  18832. },
  18833. set: function (value) {
  18834. this._headphone = value;
  18835. if (BABYLON.AudioEngine) {
  18836. if (this._headphone) {
  18837. this._switchAudioModeForHeadphones();
  18838. }
  18839. else {
  18840. this._switchAudioModeForNormalSpeakers();
  18841. }
  18842. }
  18843. },
  18844. enumerable: true,
  18845. configurable: true
  18846. });
  18847. Scene.prototype._switchAudioModeForHeadphones = function () {
  18848. this.mainSoundTrack.switchPanningModelToHRTF();
  18849. for (var i = 0; i < this.soundTracks.length; i++) {
  18850. this.soundTracks[i].switchPanningModelToHRTF();
  18851. }
  18852. };
  18853. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18854. this.mainSoundTrack.switchPanningModelToEqualPower();
  18855. for (var i = 0; i < this.soundTracks.length; i++) {
  18856. this.soundTracks[i].switchPanningModelToEqualPower();
  18857. }
  18858. };
  18859. Scene.prototype.enableDepthRenderer = function () {
  18860. if (this._depthRenderer) {
  18861. return this._depthRenderer;
  18862. }
  18863. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18864. return this._depthRenderer;
  18865. };
  18866. Scene.prototype.disableDepthRenderer = function () {
  18867. if (!this._depthRenderer) {
  18868. return;
  18869. }
  18870. this._depthRenderer.dispose();
  18871. this._depthRenderer = null;
  18872. };
  18873. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18874. if (ratio === void 0) { ratio = 1; }
  18875. if (this._geometryBufferRenderer) {
  18876. return this._geometryBufferRenderer;
  18877. }
  18878. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18879. if (!this._geometryBufferRenderer.isSupported) {
  18880. this._geometryBufferRenderer = null;
  18881. }
  18882. return this._geometryBufferRenderer;
  18883. };
  18884. Scene.prototype.disableGeometryBufferRenderer = function () {
  18885. if (!this._geometryBufferRenderer) {
  18886. return;
  18887. }
  18888. this._geometryBufferRenderer.dispose();
  18889. this._geometryBufferRenderer = null;
  18890. };
  18891. Scene.prototype.freezeMaterials = function () {
  18892. for (var i = 0; i < this.materials.length; i++) {
  18893. this.materials[i].freeze();
  18894. }
  18895. };
  18896. Scene.prototype.unfreezeMaterials = function () {
  18897. for (var i = 0; i < this.materials.length; i++) {
  18898. this.materials[i].unfreeze();
  18899. }
  18900. };
  18901. Scene.prototype.dispose = function () {
  18902. this.beforeRender = null;
  18903. this.afterRender = null;
  18904. this.skeletons = [];
  18905. this.morphTargetManagers = [];
  18906. this.importedMeshesFiles = new Array();
  18907. this.resetCachedMaterial();
  18908. if (this._depthRenderer) {
  18909. this._depthRenderer.dispose();
  18910. }
  18911. if (this._gamepadManager) {
  18912. this._gamepadManager.dispose();
  18913. this._gamepadManager = null;
  18914. }
  18915. // Smart arrays
  18916. if (this.activeCamera) {
  18917. this.activeCamera._activeMeshes.dispose();
  18918. this.activeCamera = null;
  18919. }
  18920. this._activeMeshes.dispose();
  18921. this._renderingManager.dispose();
  18922. this._processedMaterials.dispose();
  18923. this._activeParticleSystems.dispose();
  18924. this._activeSkeletons.dispose();
  18925. this._softwareSkinnedMeshes.dispose();
  18926. this._renderTargets.dispose();
  18927. if (this._boundingBoxRenderer) {
  18928. this._boundingBoxRenderer.dispose();
  18929. }
  18930. this._meshesForIntersections.dispose();
  18931. this._toBeDisposed.dispose();
  18932. // Debug layer
  18933. if (this._debugLayer) {
  18934. this._debugLayer.hide();
  18935. }
  18936. // Events
  18937. this.onDisposeObservable.notifyObservers(this);
  18938. this.onDisposeObservable.clear();
  18939. this.onBeforeRenderObservable.clear();
  18940. this.onAfterRenderObservable.clear();
  18941. this.detachControl();
  18942. // Release sounds & sounds tracks
  18943. if (BABYLON.AudioEngine) {
  18944. this.disposeSounds();
  18945. }
  18946. // VR Helper
  18947. if (this.VRHelper) {
  18948. this.VRHelper.dispose();
  18949. }
  18950. // Detach cameras
  18951. var canvas = this._engine.getRenderingCanvas();
  18952. var index;
  18953. for (index = 0; index < this.cameras.length; index++) {
  18954. this.cameras[index].detachControl(canvas);
  18955. }
  18956. // Release lights
  18957. while (this.lights.length) {
  18958. this.lights[0].dispose();
  18959. }
  18960. // Release meshes
  18961. while (this.meshes.length) {
  18962. this.meshes[0].dispose(true);
  18963. }
  18964. // Release cameras
  18965. while (this.cameras.length) {
  18966. this.cameras[0].dispose();
  18967. }
  18968. // Release materials
  18969. if (this.defaultMaterial) {
  18970. this.defaultMaterial.dispose();
  18971. }
  18972. while (this.multiMaterials.length) {
  18973. this.multiMaterials[0].dispose();
  18974. }
  18975. while (this.materials.length) {
  18976. this.materials[0].dispose();
  18977. }
  18978. // Release particles
  18979. while (this.particleSystems.length) {
  18980. this.particleSystems[0].dispose();
  18981. }
  18982. // Release sprites
  18983. while (this.spriteManagers.length) {
  18984. this.spriteManagers[0].dispose();
  18985. }
  18986. // Release layers
  18987. while (this.layers.length) {
  18988. this.layers[0].dispose();
  18989. }
  18990. while (this.highlightLayers.length) {
  18991. this.highlightLayers[0].dispose();
  18992. }
  18993. // Release textures
  18994. while (this.textures.length) {
  18995. this.textures[0].dispose();
  18996. }
  18997. // Release UBO
  18998. this._sceneUbo.dispose();
  18999. // Post-processes
  19000. this.postProcessManager.dispose();
  19001. // Physics
  19002. if (this._physicsEngine) {
  19003. this.disablePhysicsEngine();
  19004. }
  19005. // Remove from engine
  19006. index = this._engine.scenes.indexOf(this);
  19007. if (index > -1) {
  19008. this._engine.scenes.splice(index, 1);
  19009. }
  19010. this._engine.wipeCaches();
  19011. this._engine = null;
  19012. this.defaultMaterial = null;
  19013. this.multiMaterials = null;
  19014. this.materials = null;
  19015. };
  19016. Object.defineProperty(Scene.prototype, "isDisposed", {
  19017. get: function () {
  19018. return !this._engine;
  19019. },
  19020. enumerable: true,
  19021. configurable: true
  19022. });
  19023. // Release sounds & sounds tracks
  19024. Scene.prototype.disposeSounds = function () {
  19025. this.mainSoundTrack.dispose();
  19026. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19027. this.soundTracks[scIndex].dispose();
  19028. }
  19029. };
  19030. // Octrees
  19031. Scene.prototype.getWorldExtends = function () {
  19032. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19033. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19034. for (var index = 0; index < this.meshes.length; index++) {
  19035. var mesh = this.meshes[index];
  19036. mesh.computeWorldMatrix(true);
  19037. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19038. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19039. BABYLON.Tools.CheckExtends(minBox, min, max);
  19040. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19041. }
  19042. return {
  19043. min: min,
  19044. max: max
  19045. };
  19046. };
  19047. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19048. if (maxCapacity === void 0) { maxCapacity = 64; }
  19049. if (maxDepth === void 0) { maxDepth = 2; }
  19050. if (!this._selectionOctree) {
  19051. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19052. }
  19053. var worldExtends = this.getWorldExtends();
  19054. // Update octree
  19055. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19056. return this._selectionOctree;
  19057. };
  19058. // Picking
  19059. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19060. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19061. var engine = this._engine;
  19062. if (!camera) {
  19063. if (!this.activeCamera)
  19064. throw new Error("Active camera not set");
  19065. camera = this.activeCamera;
  19066. }
  19067. var cameraViewport = camera.viewport;
  19068. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19069. // Moving coordinates to local viewport world
  19070. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19071. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19072. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19073. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19074. };
  19075. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19076. if (!BABYLON.PickingInfo) {
  19077. return null;
  19078. }
  19079. var engine = this._engine;
  19080. if (!camera) {
  19081. if (!this.activeCamera)
  19082. throw new Error("Active camera not set");
  19083. camera = this.activeCamera;
  19084. }
  19085. var cameraViewport = camera.viewport;
  19086. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19087. var identity = BABYLON.Matrix.Identity();
  19088. // Moving coordinates to local viewport world
  19089. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19090. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19091. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19092. };
  19093. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19094. if (!BABYLON.PickingInfo) {
  19095. return null;
  19096. }
  19097. var pickingInfo = null;
  19098. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19099. var mesh = this.meshes[meshIndex];
  19100. if (predicate) {
  19101. if (!predicate(mesh)) {
  19102. continue;
  19103. }
  19104. }
  19105. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19106. continue;
  19107. }
  19108. var world = mesh.getWorldMatrix();
  19109. var ray = rayFunction(world);
  19110. var result = mesh.intersects(ray, fastCheck);
  19111. if (!result || !result.hit)
  19112. continue;
  19113. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19114. continue;
  19115. pickingInfo = result;
  19116. if (fastCheck) {
  19117. break;
  19118. }
  19119. }
  19120. return pickingInfo || new BABYLON.PickingInfo();
  19121. };
  19122. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19123. if (!BABYLON.PickingInfo) {
  19124. return null;
  19125. }
  19126. var pickingInfos = new Array();
  19127. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19128. var mesh = this.meshes[meshIndex];
  19129. if (predicate) {
  19130. if (!predicate(mesh)) {
  19131. continue;
  19132. }
  19133. }
  19134. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19135. continue;
  19136. }
  19137. var world = mesh.getWorldMatrix();
  19138. var ray = rayFunction(world);
  19139. var result = mesh.intersects(ray, false);
  19140. if (!result || !result.hit)
  19141. continue;
  19142. pickingInfos.push(result);
  19143. }
  19144. return pickingInfos;
  19145. };
  19146. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19147. if (!BABYLON.PickingInfo) {
  19148. return null;
  19149. }
  19150. var pickingInfo = null;
  19151. camera = camera || this.activeCamera;
  19152. if (this.spriteManagers.length > 0) {
  19153. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19154. var spriteManager = this.spriteManagers[spriteIndex];
  19155. if (!spriteManager.isPickable) {
  19156. continue;
  19157. }
  19158. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19159. if (!result || !result.hit)
  19160. continue;
  19161. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19162. continue;
  19163. pickingInfo = result;
  19164. if (fastCheck) {
  19165. break;
  19166. }
  19167. }
  19168. }
  19169. return pickingInfo || new BABYLON.PickingInfo();
  19170. };
  19171. /** Launch a ray to try to pick a mesh in the scene
  19172. * @param x position on screen
  19173. * @param y position on screen
  19174. * @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
  19175. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19176. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19177. */
  19178. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19179. var _this = this;
  19180. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19181. };
  19182. /** Launch a ray to try to pick a sprite in the scene
  19183. * @param x position on screen
  19184. * @param y position on screen
  19185. * @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
  19186. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19187. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19188. */
  19189. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19190. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19191. };
  19192. /** Use the given ray to pick a mesh in the scene
  19193. * @param ray The ray to use to pick meshes
  19194. * @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
  19195. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19196. */
  19197. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19198. var _this = this;
  19199. return this._internalPick(function (world) {
  19200. if (!_this._pickWithRayInverseMatrix) {
  19201. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19202. }
  19203. world.invertToRef(_this._pickWithRayInverseMatrix);
  19204. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19205. }, predicate, fastCheck);
  19206. };
  19207. /**
  19208. * Launch a ray to try to pick a mesh in the scene
  19209. * @param x X position on screen
  19210. * @param y Y position on screen
  19211. * @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
  19212. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19213. */
  19214. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19215. var _this = this;
  19216. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19217. };
  19218. /**
  19219. * Launch a ray to try to pick a mesh in the scene
  19220. * @param ray Ray to use
  19221. * @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
  19222. */
  19223. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19224. var _this = this;
  19225. return this._internalMultiPick(function (world) {
  19226. if (!_this._pickWithRayInverseMatrix) {
  19227. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19228. }
  19229. world.invertToRef(_this._pickWithRayInverseMatrix);
  19230. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19231. }, predicate);
  19232. };
  19233. Scene.prototype.setPointerOverMesh = function (mesh) {
  19234. if (this._pointerOverMesh === mesh) {
  19235. return;
  19236. }
  19237. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19238. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19239. }
  19240. this._pointerOverMesh = mesh;
  19241. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19242. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19243. }
  19244. };
  19245. Scene.prototype.getPointerOverMesh = function () {
  19246. return this._pointerOverMesh;
  19247. };
  19248. Scene.prototype.setPointerOverSprite = function (sprite) {
  19249. if (this._pointerOverSprite === sprite) {
  19250. return;
  19251. }
  19252. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19253. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19254. }
  19255. this._pointerOverSprite = sprite;
  19256. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19257. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19258. }
  19259. };
  19260. Scene.prototype.getPointerOverSprite = function () {
  19261. return this._pointerOverSprite;
  19262. };
  19263. // Physics
  19264. Scene.prototype.getPhysicsEngine = function () {
  19265. return this._physicsEngine;
  19266. };
  19267. /**
  19268. * Enables physics to the current scene
  19269. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19270. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19271. * @return {boolean} was the physics engine initialized
  19272. */
  19273. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19274. if (this._physicsEngine) {
  19275. return true;
  19276. }
  19277. try {
  19278. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19279. return true;
  19280. }
  19281. catch (e) {
  19282. BABYLON.Tools.Error(e.message);
  19283. return false;
  19284. }
  19285. };
  19286. Scene.prototype.disablePhysicsEngine = function () {
  19287. if (!this._physicsEngine) {
  19288. return;
  19289. }
  19290. this._physicsEngine.dispose();
  19291. this._physicsEngine = undefined;
  19292. };
  19293. Scene.prototype.isPhysicsEnabled = function () {
  19294. return this._physicsEngine !== undefined;
  19295. };
  19296. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19297. var mesh = compound.parts[0].mesh;
  19298. mesh.physicsImpostor.dispose();
  19299. mesh.physicsImpostor = null;
  19300. };
  19301. // Misc.
  19302. Scene.prototype._rebuildGeometries = function () {
  19303. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19304. var geometry = _a[_i];
  19305. geometry._rebuild();
  19306. }
  19307. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19308. var mesh = _c[_b];
  19309. mesh._rebuild();
  19310. }
  19311. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19312. var layer = _e[_d];
  19313. layer._rebuild();
  19314. }
  19315. };
  19316. Scene.prototype._rebuildTextures = function () {
  19317. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19318. var texture = _a[_i];
  19319. texture._rebuild();
  19320. }
  19321. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19322. };
  19323. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19324. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19325. if (replace === void 0) { replace = false; }
  19326. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19327. // Dispose existing camera or light in replace mode.
  19328. if (replace) {
  19329. if (this.activeCamera) {
  19330. this.activeCamera.dispose();
  19331. this.activeCamera = null;
  19332. }
  19333. if (this.lights) {
  19334. for (var i = 0; i < this.lights.length; i++) {
  19335. this.lights[i].dispose();
  19336. }
  19337. }
  19338. }
  19339. // Light
  19340. if (this.lights.length === 0) {
  19341. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19342. }
  19343. // Camera
  19344. if (!this.activeCamera) {
  19345. var worldExtends = this.getWorldExtends();
  19346. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19347. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19348. var camera;
  19349. var radius = worldSize.length() * 1.5;
  19350. if (createArcRotateCamera) {
  19351. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19352. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19353. arcRotateCamera.wheelPrecision = 100 / radius;
  19354. camera = arcRotateCamera;
  19355. }
  19356. else {
  19357. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19358. freeCamera.setTarget(worldCenter);
  19359. camera = freeCamera;
  19360. }
  19361. camera.minZ = radius * 0.01;
  19362. camera.maxZ = radius * 100;
  19363. camera.speed = radius * 0.2;
  19364. this.activeCamera = camera;
  19365. if (attachCameraControls) {
  19366. camera.attachControl(this.getEngine().getRenderingCanvas());
  19367. }
  19368. }
  19369. };
  19370. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19371. if (pbr === void 0) { pbr = false; }
  19372. if (scale === void 0) { scale = 1000; }
  19373. if (blur === void 0) { blur = 0; }
  19374. if (environmentTexture) {
  19375. this.environmentTexture = environmentTexture;
  19376. }
  19377. if (!this.environmentTexture) {
  19378. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19379. return;
  19380. }
  19381. // Skybox
  19382. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19383. if (pbr) {
  19384. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19385. hdrSkyboxMaterial.backFaceCulling = false;
  19386. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19387. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19388. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19389. hdrSkyboxMaterial.disableLighting = true;
  19390. hdrSkyboxMaterial.twoSidedLighting = true;
  19391. hdrSkybox.infiniteDistance = true;
  19392. hdrSkybox.material = hdrSkyboxMaterial;
  19393. }
  19394. else {
  19395. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19396. skyboxMaterial.backFaceCulling = false;
  19397. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19398. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19399. skyboxMaterial.disableLighting = true;
  19400. hdrSkybox.infiniteDistance = true;
  19401. hdrSkybox.material = skyboxMaterial;
  19402. }
  19403. return hdrSkybox;
  19404. };
  19405. Scene.prototype.createDefaultVRExperience = function () {
  19406. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19407. };
  19408. // Tags
  19409. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19410. if (tagsQuery === undefined) {
  19411. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19412. return list;
  19413. }
  19414. var listByTags = [];
  19415. forEach = forEach || (function (item) { return; });
  19416. for (var i in list) {
  19417. var item = list[i];
  19418. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19419. listByTags.push(item);
  19420. forEach(item);
  19421. }
  19422. }
  19423. return listByTags;
  19424. };
  19425. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19426. return this._getByTags(this.meshes, tagsQuery, forEach);
  19427. };
  19428. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19429. return this._getByTags(this.cameras, tagsQuery, forEach);
  19430. };
  19431. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19432. return this._getByTags(this.lights, tagsQuery, forEach);
  19433. };
  19434. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19435. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19436. };
  19437. /**
  19438. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19439. * This allowed control for front to back rendering or reversly depending of the special needs.
  19440. *
  19441. * @param renderingGroupId The rendering group id corresponding to its index
  19442. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19443. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19444. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19445. */
  19446. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19447. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19448. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19449. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19450. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19451. };
  19452. /**
  19453. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19454. *
  19455. * @param renderingGroupId The rendering group id corresponding to its index
  19456. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19457. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19458. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19459. */
  19460. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19461. if (depth === void 0) { depth = true; }
  19462. if (stencil === void 0) { stencil = true; }
  19463. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19464. };
  19465. /**
  19466. * Will flag all materials as dirty to trigger new shader compilation
  19467. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19468. */
  19469. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19470. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19471. var material = _a[_i];
  19472. if (predicate && !predicate(material)) {
  19473. continue;
  19474. }
  19475. material.markAsDirty(flag);
  19476. }
  19477. };
  19478. // Statics
  19479. Scene._FOGMODE_NONE = 0;
  19480. Scene._FOGMODE_EXP = 1;
  19481. Scene._FOGMODE_EXP2 = 2;
  19482. Scene._FOGMODE_LINEAR = 3;
  19483. Scene.MinDeltaTime = 1.0;
  19484. Scene.MaxDeltaTime = 1000.0;
  19485. /** The distance in pixel that you have to move to prevent some events */
  19486. Scene.DragMovementThreshold = 10; // in pixels
  19487. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19488. Scene.LongPressDelay = 500; // in milliseconds
  19489. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19490. Scene.DoubleClickDelay = 300; // in milliseconds
  19491. /** If you need to check double click without raising a single click at first click, enable this flag */
  19492. Scene.ExclusiveDoubleClickMode = false;
  19493. return Scene;
  19494. }());
  19495. BABYLON.Scene = Scene;
  19496. })(BABYLON || (BABYLON = {}));
  19497. //# sourceMappingURL=babylon.scene.js.map
  19498. var BABYLON;
  19499. (function (BABYLON) {
  19500. var Buffer = (function () {
  19501. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19502. if (engine instanceof BABYLON.Mesh) {
  19503. this._engine = engine.getScene().getEngine();
  19504. }
  19505. else {
  19506. this._engine = engine;
  19507. }
  19508. this._updatable = updatable;
  19509. this._data = data;
  19510. this._strideSize = stride;
  19511. if (!postponeInternalCreation) {
  19512. this.create();
  19513. }
  19514. this._instanced = instanced;
  19515. this._instanceDivisor = instanced ? 1 : 0;
  19516. }
  19517. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19518. // a lot of these parameters are ignored as they are overriden by the buffer
  19519. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19520. };
  19521. // Properties
  19522. Buffer.prototype.isUpdatable = function () {
  19523. return this._updatable;
  19524. };
  19525. Buffer.prototype.getData = function () {
  19526. return this._data;
  19527. };
  19528. Buffer.prototype.getBuffer = function () {
  19529. return this._buffer;
  19530. };
  19531. Buffer.prototype.getStrideSize = function () {
  19532. return this._strideSize;
  19533. };
  19534. Buffer.prototype.getIsInstanced = function () {
  19535. return this._instanced;
  19536. };
  19537. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19538. get: function () {
  19539. return this._instanceDivisor;
  19540. },
  19541. set: function (value) {
  19542. this._instanceDivisor = value;
  19543. if (value == 0) {
  19544. this._instanced = false;
  19545. }
  19546. else {
  19547. this._instanced = true;
  19548. }
  19549. },
  19550. enumerable: true,
  19551. configurable: true
  19552. });
  19553. // Methods
  19554. Buffer.prototype.create = function (data) {
  19555. if (!data && this._buffer) {
  19556. return; // nothing to do
  19557. }
  19558. data = data || this._data;
  19559. if (!this._buffer) {
  19560. if (this._updatable) {
  19561. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19562. this._data = data;
  19563. }
  19564. else {
  19565. this._buffer = this._engine.createVertexBuffer(data);
  19566. }
  19567. }
  19568. else if (this._updatable) {
  19569. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19570. this._data = data;
  19571. }
  19572. };
  19573. Buffer.prototype._rebuild = function () {
  19574. this._buffer = null;
  19575. this.create(this._data);
  19576. };
  19577. Buffer.prototype.update = function (data) {
  19578. this.create(data);
  19579. };
  19580. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19581. if (!this._buffer) {
  19582. return;
  19583. }
  19584. if (this._updatable) {
  19585. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19586. this._data = null;
  19587. }
  19588. };
  19589. Buffer.prototype.dispose = function () {
  19590. if (!this._buffer) {
  19591. return;
  19592. }
  19593. if (this._engine._releaseBuffer(this._buffer)) {
  19594. this._buffer = null;
  19595. }
  19596. };
  19597. return Buffer;
  19598. }());
  19599. BABYLON.Buffer = Buffer;
  19600. })(BABYLON || (BABYLON = {}));
  19601. //# sourceMappingURL=babylon.buffer.js.map
  19602. var BABYLON;
  19603. (function (BABYLON) {
  19604. var VertexBuffer = (function () {
  19605. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19606. if (!stride) {
  19607. // Deduce stride from kind
  19608. switch (kind) {
  19609. case VertexBuffer.PositionKind:
  19610. stride = 3;
  19611. break;
  19612. case VertexBuffer.NormalKind:
  19613. stride = 3;
  19614. break;
  19615. case VertexBuffer.UVKind:
  19616. case VertexBuffer.UV2Kind:
  19617. case VertexBuffer.UV3Kind:
  19618. case VertexBuffer.UV4Kind:
  19619. case VertexBuffer.UV5Kind:
  19620. case VertexBuffer.UV6Kind:
  19621. stride = 2;
  19622. break;
  19623. case VertexBuffer.TangentKind:
  19624. case VertexBuffer.ColorKind:
  19625. stride = 4;
  19626. break;
  19627. case VertexBuffer.MatricesIndicesKind:
  19628. case VertexBuffer.MatricesIndicesExtraKind:
  19629. stride = 4;
  19630. break;
  19631. case VertexBuffer.MatricesWeightsKind:
  19632. case VertexBuffer.MatricesWeightsExtraKind:
  19633. stride = 4;
  19634. break;
  19635. }
  19636. }
  19637. if (data instanceof BABYLON.Buffer) {
  19638. if (!stride) {
  19639. stride = data.getStrideSize();
  19640. }
  19641. this._buffer = data;
  19642. this._ownsBuffer = false;
  19643. }
  19644. else {
  19645. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19646. this._ownsBuffer = true;
  19647. }
  19648. this._stride = stride;
  19649. this._offset = offset ? offset : 0;
  19650. this._size = size ? size : stride;
  19651. this._kind = kind;
  19652. }
  19653. VertexBuffer.prototype._rebuild = function () {
  19654. if (!this._buffer) {
  19655. return;
  19656. }
  19657. this._buffer._rebuild();
  19658. };
  19659. /**
  19660. * Returns the kind of the VertexBuffer (string).
  19661. */
  19662. VertexBuffer.prototype.getKind = function () {
  19663. return this._kind;
  19664. };
  19665. // Properties
  19666. /**
  19667. * Boolean : is the VertexBuffer updatable ?
  19668. */
  19669. VertexBuffer.prototype.isUpdatable = function () {
  19670. return this._buffer.isUpdatable();
  19671. };
  19672. /**
  19673. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19674. */
  19675. VertexBuffer.prototype.getData = function () {
  19676. return this._buffer.getData();
  19677. };
  19678. /**
  19679. * Returns the WebGLBuffer associated to the VertexBuffer.
  19680. */
  19681. VertexBuffer.prototype.getBuffer = function () {
  19682. return this._buffer.getBuffer();
  19683. };
  19684. /**
  19685. * Returns the stride of the VertexBuffer (integer).
  19686. */
  19687. VertexBuffer.prototype.getStrideSize = function () {
  19688. return this._stride;
  19689. };
  19690. /**
  19691. * Returns the offset (integer).
  19692. */
  19693. VertexBuffer.prototype.getOffset = function () {
  19694. return this._offset;
  19695. };
  19696. /**
  19697. * Returns the VertexBuffer total size (integer).
  19698. */
  19699. VertexBuffer.prototype.getSize = function () {
  19700. return this._size;
  19701. };
  19702. /**
  19703. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19704. */
  19705. VertexBuffer.prototype.getIsInstanced = function () {
  19706. return this._buffer.getIsInstanced();
  19707. };
  19708. /**
  19709. * Returns the instancing divisor, zero for non-instanced (integer).
  19710. */
  19711. VertexBuffer.prototype.getInstanceDivisor = function () {
  19712. return this._buffer.instanceDivisor;
  19713. };
  19714. // Methods
  19715. /**
  19716. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19717. * Returns the created WebGLBuffer.
  19718. */
  19719. VertexBuffer.prototype.create = function (data) {
  19720. return this._buffer.create(data);
  19721. };
  19722. /**
  19723. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19724. * Returns the updated WebGLBuffer.
  19725. */
  19726. VertexBuffer.prototype.update = function (data) {
  19727. return this._buffer.update(data);
  19728. };
  19729. /**
  19730. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19731. * Returns the directly updated WebGLBuffer.
  19732. */
  19733. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19734. return this._buffer.updateDirectly(data, offset);
  19735. };
  19736. /**
  19737. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19738. */
  19739. VertexBuffer.prototype.dispose = function () {
  19740. if (this._ownsBuffer) {
  19741. this._buffer.dispose();
  19742. }
  19743. };
  19744. Object.defineProperty(VertexBuffer, "PositionKind", {
  19745. get: function () {
  19746. return VertexBuffer._PositionKind;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. Object.defineProperty(VertexBuffer, "NormalKind", {
  19752. get: function () {
  19753. return VertexBuffer._NormalKind;
  19754. },
  19755. enumerable: true,
  19756. configurable: true
  19757. });
  19758. Object.defineProperty(VertexBuffer, "TangentKind", {
  19759. get: function () {
  19760. return VertexBuffer._TangentKind;
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(VertexBuffer, "UVKind", {
  19766. get: function () {
  19767. return VertexBuffer._UVKind;
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19773. get: function () {
  19774. return VertexBuffer._UV2Kind;
  19775. },
  19776. enumerable: true,
  19777. configurable: true
  19778. });
  19779. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19780. get: function () {
  19781. return VertexBuffer._UV3Kind;
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19787. get: function () {
  19788. return VertexBuffer._UV4Kind;
  19789. },
  19790. enumerable: true,
  19791. configurable: true
  19792. });
  19793. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19794. get: function () {
  19795. return VertexBuffer._UV5Kind;
  19796. },
  19797. enumerable: true,
  19798. configurable: true
  19799. });
  19800. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19801. get: function () {
  19802. return VertexBuffer._UV6Kind;
  19803. },
  19804. enumerable: true,
  19805. configurable: true
  19806. });
  19807. Object.defineProperty(VertexBuffer, "ColorKind", {
  19808. get: function () {
  19809. return VertexBuffer._ColorKind;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19815. get: function () {
  19816. return VertexBuffer._MatricesIndicesKind;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19822. get: function () {
  19823. return VertexBuffer._MatricesWeightsKind;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19829. get: function () {
  19830. return VertexBuffer._MatricesIndicesExtraKind;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19836. get: function () {
  19837. return VertexBuffer._MatricesWeightsExtraKind;
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. // Enums
  19843. VertexBuffer._PositionKind = "position";
  19844. VertexBuffer._NormalKind = "normal";
  19845. VertexBuffer._TangentKind = "tangent";
  19846. VertexBuffer._UVKind = "uv";
  19847. VertexBuffer._UV2Kind = "uv2";
  19848. VertexBuffer._UV3Kind = "uv3";
  19849. VertexBuffer._UV4Kind = "uv4";
  19850. VertexBuffer._UV5Kind = "uv5";
  19851. VertexBuffer._UV6Kind = "uv6";
  19852. VertexBuffer._ColorKind = "color";
  19853. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19854. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19855. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19856. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19857. return VertexBuffer;
  19858. }());
  19859. BABYLON.VertexBuffer = VertexBuffer;
  19860. })(BABYLON || (BABYLON = {}));
  19861. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19862. var BABYLON;
  19863. (function (BABYLON) {
  19864. var InternalTexture = (function () {
  19865. function InternalTexture(engine, dataSource) {
  19866. this.onLoadedObservable = new BABYLON.Observable();
  19867. // Private
  19868. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  19869. this._references = 1;
  19870. this._engine = engine;
  19871. this._dataSource = dataSource;
  19872. this._webGLTexture = engine._createTexture();
  19873. }
  19874. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  19875. get: function () {
  19876. return this._dataSource;
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. InternalTexture.prototype.incrementReferences = function () {
  19882. this._references++;
  19883. };
  19884. InternalTexture.prototype.updateSize = function (width, height) {
  19885. this.width = width;
  19886. this.height = height;
  19887. this._size = width * height;
  19888. this.baseWidth = width;
  19889. this.baseHeight = height;
  19890. };
  19891. InternalTexture.prototype._rebuild = function () {
  19892. var _this = this;
  19893. var proxy;
  19894. this.isReady = false;
  19895. this._cachedCoordinatesMode = null;
  19896. this._cachedWrapU = null;
  19897. this._cachedWrapV = null;
  19898. this._cachedAnisotropicFilteringLevel = null;
  19899. switch (this._dataSource) {
  19900. case InternalTexture.DATASOURCE_TEMP:
  19901. return;
  19902. case InternalTexture.DATASOURCE_URL:
  19903. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  19904. _this.isReady = true;
  19905. }, null, this._buffer, null, this.format);
  19906. proxy._swapAndDie(this);
  19907. return;
  19908. case InternalTexture.DATASOURCE_DYNAMIC:
  19909. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  19910. proxy._swapAndDie(this);
  19911. // The engine will make sure to update content so no need to flag it as isReady = true
  19912. return;
  19913. case InternalTexture.DATASOURCE_CUBE:
  19914. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  19915. _this.isReady = true;
  19916. }, null, this.format, this._extension);
  19917. proxy._swapAndDie(this);
  19918. return;
  19919. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  19920. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  19921. proxy._swapAndDie(_this);
  19922. _this.isReady = true;
  19923. }, null, this.format, this._extension);
  19924. return;
  19925. }
  19926. };
  19927. InternalTexture.prototype._swapAndDie = function (target) {
  19928. target._webGLTexture = this._webGLTexture;
  19929. if (this._lodTextureHigh) {
  19930. if (target._lodTextureHigh) {
  19931. target._lodTextureHigh.dispose();
  19932. }
  19933. target._lodTextureHigh = this._lodTextureHigh;
  19934. }
  19935. if (this._lodTextureMid) {
  19936. if (target._lodTextureMid) {
  19937. target._lodTextureMid.dispose();
  19938. }
  19939. target._lodTextureMid = this._lodTextureMid;
  19940. }
  19941. if (this._lodTextureLow) {
  19942. if (target._lodTextureLow) {
  19943. target._lodTextureLow.dispose();
  19944. }
  19945. target._lodTextureLow = this._lodTextureLow;
  19946. }
  19947. var cache = this._engine.getLoadedTexturesCache();
  19948. var index = cache.indexOf(this);
  19949. if (index !== -1) {
  19950. cache.splice(index, 1);
  19951. }
  19952. };
  19953. InternalTexture.prototype.dispose = function () {
  19954. if (!this._webGLTexture) {
  19955. return;
  19956. }
  19957. this._references--;
  19958. if (this._references === 0) {
  19959. this._engine._releaseTexture(this);
  19960. this._webGLTexture = null;
  19961. }
  19962. };
  19963. InternalTexture.DATASOURCE_UNKNOWN = 0;
  19964. InternalTexture.DATASOURCE_URL = 1;
  19965. InternalTexture.DATASOURCE_TEMP = 2;
  19966. InternalTexture.DATASOURCE_RAW = 3;
  19967. InternalTexture.DATASOURCE_DYNAMIC = 4;
  19968. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  19969. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  19970. InternalTexture.DATASOURCE_CUBE = 7;
  19971. InternalTexture.DATASOURCE_CUBERAW = 8;
  19972. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  19973. return InternalTexture;
  19974. }());
  19975. BABYLON.InternalTexture = InternalTexture;
  19976. })(BABYLON || (BABYLON = {}));
  19977. //# sourceMappingURL=babylon.internalTexture.js.map
  19978. var BABYLON;
  19979. (function (BABYLON) {
  19980. var BaseTexture = (function () {
  19981. function BaseTexture(scene) {
  19982. this._hasAlpha = false;
  19983. this.getAlphaFromRGB = false;
  19984. this.level = 1;
  19985. this.coordinatesIndex = 0;
  19986. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  19987. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  19988. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  19989. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  19990. this.isCube = false;
  19991. this.gammaSpace = true;
  19992. this.invertZ = false;
  19993. this.lodLevelInAlpha = false;
  19994. this.lodGenerationOffset = 0.0;
  19995. this.lodGenerationScale = 0.8;
  19996. this.isRenderTarget = false;
  19997. this.animations = new Array();
  19998. /**
  19999. * An event triggered when the texture is disposed.
  20000. * @type {BABYLON.Observable}
  20001. */
  20002. this.onDisposeObservable = new BABYLON.Observable();
  20003. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20004. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20005. this._scene.textures.push(this);
  20006. this._uid = null;
  20007. }
  20008. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20009. get: function () {
  20010. return this._hasAlpha;
  20011. },
  20012. set: function (value) {
  20013. if (this._hasAlpha === value) {
  20014. return;
  20015. }
  20016. this._hasAlpha = value;
  20017. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20023. get: function () {
  20024. return this._coordinatesMode;
  20025. },
  20026. set: function (value) {
  20027. if (this._coordinatesMode === value) {
  20028. return;
  20029. }
  20030. this._coordinatesMode = value;
  20031. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20032. },
  20033. enumerable: true,
  20034. configurable: true
  20035. });
  20036. Object.defineProperty(BaseTexture.prototype, "uid", {
  20037. get: function () {
  20038. if (!this._uid) {
  20039. this._uid = BABYLON.Tools.RandomId();
  20040. }
  20041. return this._uid;
  20042. },
  20043. enumerable: true,
  20044. configurable: true
  20045. });
  20046. BaseTexture.prototype.toString = function () {
  20047. return this.name;
  20048. };
  20049. BaseTexture.prototype.getClassName = function () {
  20050. return "BaseTexture";
  20051. };
  20052. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20053. set: function (callback) {
  20054. if (this._onDisposeObserver) {
  20055. this.onDisposeObservable.remove(this._onDisposeObserver);
  20056. }
  20057. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20058. },
  20059. enumerable: true,
  20060. configurable: true
  20061. });
  20062. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20063. get: function () {
  20064. return true;
  20065. },
  20066. enumerable: true,
  20067. configurable: true
  20068. });
  20069. BaseTexture.prototype.getScene = function () {
  20070. return this._scene;
  20071. };
  20072. BaseTexture.prototype.getTextureMatrix = function () {
  20073. return null;
  20074. };
  20075. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20076. return null;
  20077. };
  20078. BaseTexture.prototype.getInternalTexture = function () {
  20079. return this._texture;
  20080. };
  20081. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20082. return !this.isBlocking || this.isReady();
  20083. };
  20084. BaseTexture.prototype.isReady = function () {
  20085. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20086. this.delayLoad();
  20087. return false;
  20088. }
  20089. if (this._texture) {
  20090. return this._texture.isReady;
  20091. }
  20092. return false;
  20093. };
  20094. BaseTexture.prototype.getSize = function () {
  20095. if (this._texture.width) {
  20096. return new BABYLON.Size(this._texture.width, this._texture.height);
  20097. }
  20098. if (this._texture._size) {
  20099. return new BABYLON.Size(this._texture._size, this._texture._size);
  20100. }
  20101. return BABYLON.Size.Zero();
  20102. };
  20103. BaseTexture.prototype.getBaseSize = function () {
  20104. if (!this.isReady() || !this._texture)
  20105. return BABYLON.Size.Zero();
  20106. if (this._texture._size) {
  20107. return new BABYLON.Size(this._texture._size, this._texture._size);
  20108. }
  20109. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20110. };
  20111. BaseTexture.prototype.scale = function (ratio) {
  20112. };
  20113. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20114. get: function () {
  20115. return false;
  20116. },
  20117. enumerable: true,
  20118. configurable: true
  20119. });
  20120. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20121. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20122. for (var index = 0; index < texturesCache.length; index++) {
  20123. var texturesCacheEntry = texturesCache[index];
  20124. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20125. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20126. texturesCacheEntry.incrementReferences();
  20127. return texturesCacheEntry;
  20128. }
  20129. }
  20130. }
  20131. return null;
  20132. };
  20133. BaseTexture.prototype._rebuild = function () {
  20134. };
  20135. BaseTexture.prototype.delayLoad = function () {
  20136. };
  20137. BaseTexture.prototype.clone = function () {
  20138. return null;
  20139. };
  20140. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20141. get: function () {
  20142. if (!this._texture) {
  20143. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20144. }
  20145. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20146. },
  20147. enumerable: true,
  20148. configurable: true
  20149. });
  20150. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20151. get: function () {
  20152. if (!this._texture) {
  20153. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20154. }
  20155. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20156. },
  20157. enumerable: true,
  20158. configurable: true
  20159. });
  20160. BaseTexture.prototype.readPixels = function (faceIndex) {
  20161. if (faceIndex === void 0) { faceIndex = 0; }
  20162. if (!this._texture) {
  20163. return null;
  20164. }
  20165. var size = this.getSize();
  20166. var engine = this.getScene().getEngine();
  20167. if (this._texture.isCube) {
  20168. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20169. }
  20170. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20171. };
  20172. BaseTexture.prototype.releaseInternalTexture = function () {
  20173. if (this._texture) {
  20174. this._texture.dispose();
  20175. this._texture = null;
  20176. }
  20177. };
  20178. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20179. get: function () {
  20180. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20181. return null;
  20182. }
  20183. if (!this._texture._sphericalPolynomial) {
  20184. this._texture._sphericalPolynomial =
  20185. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20186. }
  20187. return this._texture._sphericalPolynomial;
  20188. },
  20189. set: function (value) {
  20190. if (this._texture) {
  20191. this._texture._sphericalPolynomial = value;
  20192. }
  20193. },
  20194. enumerable: true,
  20195. configurable: true
  20196. });
  20197. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20198. get: function () {
  20199. if (this._texture) {
  20200. return this._texture._lodTextureHigh;
  20201. }
  20202. return null;
  20203. },
  20204. enumerable: true,
  20205. configurable: true
  20206. });
  20207. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20208. get: function () {
  20209. if (this._texture) {
  20210. return this._texture._lodTextureMid;
  20211. }
  20212. return null;
  20213. },
  20214. enumerable: true,
  20215. configurable: true
  20216. });
  20217. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20218. get: function () {
  20219. if (this._texture) {
  20220. return this._texture._lodTextureLow;
  20221. }
  20222. return null;
  20223. },
  20224. enumerable: true,
  20225. configurable: true
  20226. });
  20227. BaseTexture.prototype.dispose = function () {
  20228. // Animations
  20229. this.getScene().stopAnimation(this);
  20230. // Remove from scene
  20231. this._scene._removePendingData(this);
  20232. var index = this._scene.textures.indexOf(this);
  20233. if (index >= 0) {
  20234. this._scene.textures.splice(index, 1);
  20235. }
  20236. if (this._texture === undefined) {
  20237. return;
  20238. }
  20239. // Release
  20240. this.releaseInternalTexture();
  20241. // Callback
  20242. this.onDisposeObservable.notifyObservers(this);
  20243. this.onDisposeObservable.clear();
  20244. };
  20245. BaseTexture.prototype.serialize = function () {
  20246. if (!this.name) {
  20247. return null;
  20248. }
  20249. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20250. // Animations
  20251. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20252. return serializationObject;
  20253. };
  20254. BaseTexture.WhenAllReady = function (textures, callback) {
  20255. var numRemaining = textures.length;
  20256. if (numRemaining === 0) {
  20257. callback();
  20258. return;
  20259. }
  20260. var _loop_1 = function () {
  20261. texture = textures[i];
  20262. if (texture.isReady()) {
  20263. if (--numRemaining === 0) {
  20264. callback();
  20265. }
  20266. }
  20267. else {
  20268. onLoadObservable = texture.onLoadObservable;
  20269. var onLoadCallback_1 = function () {
  20270. onLoadObservable.removeCallback(onLoadCallback_1);
  20271. if (--numRemaining === 0) {
  20272. callback();
  20273. }
  20274. };
  20275. onLoadObservable.add(onLoadCallback_1);
  20276. }
  20277. };
  20278. var texture, onLoadObservable;
  20279. for (var i = 0; i < textures.length; i++) {
  20280. _loop_1();
  20281. }
  20282. };
  20283. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20284. __decorate([
  20285. BABYLON.serialize()
  20286. ], BaseTexture.prototype, "name", void 0);
  20287. __decorate([
  20288. BABYLON.serialize("hasAlpha")
  20289. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20290. __decorate([
  20291. BABYLON.serialize()
  20292. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20293. __decorate([
  20294. BABYLON.serialize()
  20295. ], BaseTexture.prototype, "level", void 0);
  20296. __decorate([
  20297. BABYLON.serialize()
  20298. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20299. __decorate([
  20300. BABYLON.serialize("coordinatesMode")
  20301. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20302. __decorate([
  20303. BABYLON.serialize()
  20304. ], BaseTexture.prototype, "wrapU", void 0);
  20305. __decorate([
  20306. BABYLON.serialize()
  20307. ], BaseTexture.prototype, "wrapV", void 0);
  20308. __decorate([
  20309. BABYLON.serialize()
  20310. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20311. __decorate([
  20312. BABYLON.serialize()
  20313. ], BaseTexture.prototype, "isCube", void 0);
  20314. __decorate([
  20315. BABYLON.serialize()
  20316. ], BaseTexture.prototype, "gammaSpace", void 0);
  20317. __decorate([
  20318. BABYLON.serialize()
  20319. ], BaseTexture.prototype, "invertZ", void 0);
  20320. __decorate([
  20321. BABYLON.serialize()
  20322. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20323. __decorate([
  20324. BABYLON.serialize()
  20325. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20326. __decorate([
  20327. BABYLON.serialize()
  20328. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20329. __decorate([
  20330. BABYLON.serialize()
  20331. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20332. return BaseTexture;
  20333. }());
  20334. BABYLON.BaseTexture = BaseTexture;
  20335. })(BABYLON || (BABYLON = {}));
  20336. //# sourceMappingURL=babylon.baseTexture.js.map
  20337. var BABYLON;
  20338. (function (BABYLON) {
  20339. var Texture = (function (_super) {
  20340. __extends(Texture, _super);
  20341. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20342. if (noMipmap === void 0) { noMipmap = false; }
  20343. if (invertY === void 0) { invertY = true; }
  20344. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20345. if (onLoad === void 0) { onLoad = null; }
  20346. if (onError === void 0) { onError = null; }
  20347. if (buffer === void 0) { buffer = null; }
  20348. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20349. var _this = _super.call(this, scene) || this;
  20350. _this.uOffset = 0;
  20351. _this.vOffset = 0;
  20352. _this.uScale = 1.0;
  20353. _this.vScale = 1.0;
  20354. _this.uAng = 0;
  20355. _this.vAng = 0;
  20356. _this.wAng = 0;
  20357. _this._isBlocking = true;
  20358. _this.name = url;
  20359. _this.url = url;
  20360. _this._noMipmap = noMipmap;
  20361. _this._invertY = invertY;
  20362. _this._samplingMode = samplingMode;
  20363. _this._buffer = buffer;
  20364. _this._deleteBuffer = deleteBuffer;
  20365. _this._format = format;
  20366. scene = _this.getScene();
  20367. var load = function () {
  20368. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20369. _this.onLoadObservable.notifyObservers(_this);
  20370. }
  20371. if (onLoad) {
  20372. onLoad();
  20373. }
  20374. if (!_this.isBlocking) {
  20375. scene.resetCachedMaterial();
  20376. }
  20377. };
  20378. if (!url) {
  20379. _this._delayedOnLoad = load;
  20380. _this._delayedOnError = onError;
  20381. return _this;
  20382. }
  20383. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20384. if (!_this._texture) {
  20385. if (!scene.useDelayedTextureLoading) {
  20386. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20387. if (deleteBuffer) {
  20388. delete _this._buffer;
  20389. }
  20390. }
  20391. else {
  20392. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20393. _this._delayedOnLoad = load;
  20394. _this._delayedOnError = onError;
  20395. }
  20396. }
  20397. else {
  20398. if (_this._texture.isReady) {
  20399. BABYLON.Tools.SetImmediate(function () { return load(); });
  20400. }
  20401. else {
  20402. _this._texture.onLoadedObservable.add(load);
  20403. }
  20404. }
  20405. return _this;
  20406. }
  20407. Object.defineProperty(Texture.prototype, "noMipmap", {
  20408. get: function () {
  20409. return this._noMipmap;
  20410. },
  20411. enumerable: true,
  20412. configurable: true
  20413. });
  20414. Object.defineProperty(Texture.prototype, "isBlocking", {
  20415. get: function () {
  20416. return this._isBlocking;
  20417. },
  20418. set: function (value) {
  20419. this._isBlocking = value;
  20420. },
  20421. enumerable: true,
  20422. configurable: true
  20423. });
  20424. Object.defineProperty(Texture.prototype, "samplingMode", {
  20425. get: function () {
  20426. return this._samplingMode;
  20427. },
  20428. enumerable: true,
  20429. configurable: true
  20430. });
  20431. Texture.prototype.updateURL = function (url) {
  20432. this.url = url;
  20433. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20434. this.delayLoad();
  20435. };
  20436. Texture.prototype.delayLoad = function () {
  20437. var _this = this;
  20438. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20439. return;
  20440. }
  20441. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20442. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20443. if (!this._texture) {
  20444. 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);
  20445. if (this._deleteBuffer) {
  20446. delete this._buffer;
  20447. }
  20448. }
  20449. else {
  20450. if (this._texture.isReady) {
  20451. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20452. }
  20453. else {
  20454. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20455. }
  20456. }
  20457. };
  20458. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20459. if (!this._texture) {
  20460. return;
  20461. }
  20462. this._samplingMode = samplingMode;
  20463. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20464. };
  20465. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20466. x *= this.uScale;
  20467. y *= this.vScale;
  20468. x -= 0.5 * this.uScale;
  20469. y -= 0.5 * this.vScale;
  20470. z -= 0.5;
  20471. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20472. t.x += 0.5 * this.uScale + this.uOffset;
  20473. t.y += 0.5 * this.vScale + this.vOffset;
  20474. t.z += 0.5;
  20475. };
  20476. Texture.prototype.getTextureMatrix = function () {
  20477. var _this = this;
  20478. if (this.uOffset === this._cachedUOffset &&
  20479. this.vOffset === this._cachedVOffset &&
  20480. this.uScale === this._cachedUScale &&
  20481. this.vScale === this._cachedVScale &&
  20482. this.uAng === this._cachedUAng &&
  20483. this.vAng === this._cachedVAng &&
  20484. this.wAng === this._cachedWAng) {
  20485. return this._cachedTextureMatrix;
  20486. }
  20487. this._cachedUOffset = this.uOffset;
  20488. this._cachedVOffset = this.vOffset;
  20489. this._cachedUScale = this.uScale;
  20490. this._cachedVScale = this.vScale;
  20491. this._cachedUAng = this.uAng;
  20492. this._cachedVAng = this.vAng;
  20493. this._cachedWAng = this.wAng;
  20494. if (!this._cachedTextureMatrix) {
  20495. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20496. this._rowGenerationMatrix = new BABYLON.Matrix();
  20497. this._t0 = BABYLON.Vector3.Zero();
  20498. this._t1 = BABYLON.Vector3.Zero();
  20499. this._t2 = BABYLON.Vector3.Zero();
  20500. }
  20501. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20502. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20503. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20504. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20505. this._t1.subtractInPlace(this._t0);
  20506. this._t2.subtractInPlace(this._t0);
  20507. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20508. this._cachedTextureMatrix.m[0] = this._t1.x;
  20509. this._cachedTextureMatrix.m[1] = this._t1.y;
  20510. this._cachedTextureMatrix.m[2] = this._t1.z;
  20511. this._cachedTextureMatrix.m[4] = this._t2.x;
  20512. this._cachedTextureMatrix.m[5] = this._t2.y;
  20513. this._cachedTextureMatrix.m[6] = this._t2.z;
  20514. this._cachedTextureMatrix.m[8] = this._t0.x;
  20515. this._cachedTextureMatrix.m[9] = this._t0.y;
  20516. this._cachedTextureMatrix.m[10] = this._t0.z;
  20517. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20518. return mat.hasTexture(_this);
  20519. });
  20520. return this._cachedTextureMatrix;
  20521. };
  20522. Texture.prototype.getReflectionTextureMatrix = function () {
  20523. var _this = this;
  20524. var scene = this.getScene();
  20525. if (this.uOffset === this._cachedUOffset &&
  20526. this.vOffset === this._cachedVOffset &&
  20527. this.uScale === this._cachedUScale &&
  20528. this.vScale === this._cachedVScale &&
  20529. this.coordinatesMode === this._cachedCoordinatesMode) {
  20530. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20531. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20532. return this._cachedTextureMatrix;
  20533. }
  20534. }
  20535. else {
  20536. return this._cachedTextureMatrix;
  20537. }
  20538. }
  20539. if (!this._cachedTextureMatrix) {
  20540. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20541. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20542. }
  20543. this._cachedUOffset = this.uOffset;
  20544. this._cachedVOffset = this.vOffset;
  20545. this._cachedUScale = this.uScale;
  20546. this._cachedVScale = this.vScale;
  20547. this._cachedCoordinatesMode = this.coordinatesMode;
  20548. switch (this.coordinatesMode) {
  20549. case Texture.PLANAR_MODE:
  20550. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20551. this._cachedTextureMatrix[0] = this.uScale;
  20552. this._cachedTextureMatrix[5] = this.vScale;
  20553. this._cachedTextureMatrix[12] = this.uOffset;
  20554. this._cachedTextureMatrix[13] = this.vOffset;
  20555. break;
  20556. case Texture.PROJECTION_MODE:
  20557. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20558. this._projectionModeMatrix.m[0] = 0.5;
  20559. this._projectionModeMatrix.m[5] = -0.5;
  20560. this._projectionModeMatrix.m[10] = 0.0;
  20561. this._projectionModeMatrix.m[12] = 0.5;
  20562. this._projectionModeMatrix.m[13] = 0.5;
  20563. this._projectionModeMatrix.m[14] = 1.0;
  20564. this._projectionModeMatrix.m[15] = 1.0;
  20565. var projectionMatrix = scene.getProjectionMatrix();
  20566. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20567. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20568. break;
  20569. default:
  20570. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20571. break;
  20572. }
  20573. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20574. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20575. });
  20576. return this._cachedTextureMatrix;
  20577. };
  20578. Texture.prototype.clone = function () {
  20579. var _this = this;
  20580. return BABYLON.SerializationHelper.Clone(function () {
  20581. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20582. }, this);
  20583. };
  20584. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20585. get: function () {
  20586. if (!this._onLoadObservable) {
  20587. this._onLoadObservable = new BABYLON.Observable();
  20588. }
  20589. return this._onLoadObservable;
  20590. },
  20591. enumerable: true,
  20592. configurable: true
  20593. });
  20594. Texture.prototype.serialize = function () {
  20595. var serializationObject = _super.prototype.serialize.call(this);
  20596. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20597. serializationObject.base64String = this._buffer;
  20598. serializationObject.name = serializationObject.name.replace("data:", "");
  20599. }
  20600. return serializationObject;
  20601. };
  20602. Texture.prototype.getClassName = function () {
  20603. return "Texture";
  20604. };
  20605. Texture.prototype.dispose = function () {
  20606. _super.prototype.dispose.call(this);
  20607. if (this.onLoadObservable) {
  20608. this.onLoadObservable.clear();
  20609. this._onLoadObservable = null;
  20610. }
  20611. this._delayedOnLoad = null;
  20612. this._delayedOnError = null;
  20613. };
  20614. // Statics
  20615. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20616. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20617. if (onLoad === void 0) { onLoad = null; }
  20618. if (onError === void 0) { onError = null; }
  20619. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20620. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20621. };
  20622. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20623. if (parsedTexture.customType) {
  20624. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20625. // Update Sampling Mode
  20626. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20627. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20628. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20629. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20630. }
  20631. }
  20632. return parsedCustomTexture;
  20633. }
  20634. if (parsedTexture.isCube) {
  20635. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20636. }
  20637. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20638. return null;
  20639. }
  20640. var texture = BABYLON.SerializationHelper.Parse(function () {
  20641. if (parsedTexture.mirrorPlane) {
  20642. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20643. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20644. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20645. return mirrorTexture;
  20646. }
  20647. else if (parsedTexture.isRenderTarget) {
  20648. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20649. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20650. return renderTargetTexture;
  20651. }
  20652. else {
  20653. var texture;
  20654. if (parsedTexture.base64String) {
  20655. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20656. }
  20657. else {
  20658. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20659. }
  20660. return texture;
  20661. }
  20662. }, parsedTexture, scene);
  20663. // Update Sampling Mode
  20664. if (parsedTexture.samplingMode) {
  20665. var sampling = parsedTexture.samplingMode;
  20666. if (texture._samplingMode !== sampling) {
  20667. texture.updateSamplingMode(sampling);
  20668. }
  20669. }
  20670. // Animations
  20671. if (parsedTexture.animations) {
  20672. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20673. var parsedAnimation = parsedTexture.animations[animationIndex];
  20674. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20675. }
  20676. }
  20677. return texture;
  20678. };
  20679. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20680. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20681. if (noMipmap === void 0) { noMipmap = false; }
  20682. if (invertY === void 0) { invertY = true; }
  20683. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20684. if (onLoad === void 0) { onLoad = null; }
  20685. if (onError === void 0) { onError = null; }
  20686. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20687. if (name.substr(0, 5) !== "data:") {
  20688. name = "data:" + name;
  20689. }
  20690. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20691. };
  20692. // Constants
  20693. Texture.NEAREST_SAMPLINGMODE = 1;
  20694. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20695. Texture.BILINEAR_SAMPLINGMODE = 2;
  20696. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20697. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20698. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20699. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20700. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20701. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20702. Texture.NEAREST_LINEAR = 7;
  20703. Texture.NEAREST_NEAREST = 8;
  20704. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20705. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20706. Texture.LINEAR_LINEAR = 11;
  20707. Texture.LINEAR_NEAREST = 12;
  20708. Texture.EXPLICIT_MODE = 0;
  20709. Texture.SPHERICAL_MODE = 1;
  20710. Texture.PLANAR_MODE = 2;
  20711. Texture.CUBIC_MODE = 3;
  20712. Texture.PROJECTION_MODE = 4;
  20713. Texture.SKYBOX_MODE = 5;
  20714. Texture.INVCUBIC_MODE = 6;
  20715. Texture.EQUIRECTANGULAR_MODE = 7;
  20716. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20717. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20718. Texture.CLAMP_ADDRESSMODE = 0;
  20719. Texture.WRAP_ADDRESSMODE = 1;
  20720. Texture.MIRROR_ADDRESSMODE = 2;
  20721. __decorate([
  20722. BABYLON.serialize()
  20723. ], Texture.prototype, "url", void 0);
  20724. __decorate([
  20725. BABYLON.serialize()
  20726. ], Texture.prototype, "uOffset", void 0);
  20727. __decorate([
  20728. BABYLON.serialize()
  20729. ], Texture.prototype, "vOffset", void 0);
  20730. __decorate([
  20731. BABYLON.serialize()
  20732. ], Texture.prototype, "uScale", void 0);
  20733. __decorate([
  20734. BABYLON.serialize()
  20735. ], Texture.prototype, "vScale", void 0);
  20736. __decorate([
  20737. BABYLON.serialize()
  20738. ], Texture.prototype, "uAng", void 0);
  20739. __decorate([
  20740. BABYLON.serialize()
  20741. ], Texture.prototype, "vAng", void 0);
  20742. __decorate([
  20743. BABYLON.serialize()
  20744. ], Texture.prototype, "wAng", void 0);
  20745. __decorate([
  20746. BABYLON.serialize()
  20747. ], Texture.prototype, "isBlocking", null);
  20748. return Texture;
  20749. }(BABYLON.BaseTexture));
  20750. BABYLON.Texture = Texture;
  20751. })(BABYLON || (BABYLON = {}));
  20752. //# sourceMappingURL=babylon.texture.js.map
  20753. var BABYLON;
  20754. (function (BABYLON) {
  20755. var _InstancesBatch = (function () {
  20756. function _InstancesBatch() {
  20757. this.mustReturn = false;
  20758. this.visibleInstances = new Array();
  20759. this.renderSelf = new Array();
  20760. }
  20761. return _InstancesBatch;
  20762. }());
  20763. BABYLON._InstancesBatch = _InstancesBatch;
  20764. var Mesh = (function (_super) {
  20765. __extends(Mesh, _super);
  20766. /**
  20767. * @constructor
  20768. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20769. * @param {Scene} scene The scene to add this mesh to.
  20770. * @param {Node} parent The parent of this mesh, if it has one
  20771. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20772. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20773. * When false, achieved by calling a clone(), also passing False.
  20774. * This will make creation of children, recursive.
  20775. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20776. */
  20777. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20778. if (parent === void 0) { parent = null; }
  20779. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20780. var _this = _super.call(this, name, scene) || this;
  20781. // Events
  20782. /**
  20783. * An event triggered before rendering the mesh
  20784. * @type {BABYLON.Observable}
  20785. */
  20786. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20787. /**
  20788. * An event triggered after rendering the mesh
  20789. * @type {BABYLON.Observable}
  20790. */
  20791. _this.onAfterRenderObservable = new BABYLON.Observable();
  20792. /**
  20793. * An event triggered before drawing the mesh
  20794. * @type {BABYLON.Observable}
  20795. */
  20796. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20797. // Members
  20798. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20799. _this.instances = new Array();
  20800. _this._LODLevels = new Array();
  20801. _this._visibleInstances = {};
  20802. _this._renderIdForInstances = new Array();
  20803. _this._batchCache = new _InstancesBatch();
  20804. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20805. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20806. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20807. // Will be used to save a source mesh reference, If any
  20808. _this._source = null;
  20809. if (source) {
  20810. // Source mesh
  20811. _this._source = source;
  20812. // Geometry
  20813. if (source._geometry) {
  20814. source._geometry.applyToMesh(_this);
  20815. }
  20816. // Deep copy
  20817. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  20818. // Parent
  20819. _this.parent = source.parent;
  20820. // Pivot
  20821. _this.setPivotMatrix(source.getPivotMatrix());
  20822. _this.id = name + "." + source.id;
  20823. // Material
  20824. _this.material = source.material;
  20825. var index;
  20826. if (!doNotCloneChildren) {
  20827. // Children
  20828. for (index = 0; index < scene.meshes.length; index++) {
  20829. var mesh = scene.meshes[index];
  20830. if (mesh.parent === source) {
  20831. // doNotCloneChildren is always going to be False
  20832. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20833. }
  20834. }
  20835. }
  20836. // Physics clone
  20837. var physicsEngine = _this.getScene().getPhysicsEngine();
  20838. if (clonePhysicsImpostor && physicsEngine) {
  20839. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20840. if (impostor) {
  20841. _this.physicsImpostor = impostor.clone(_this);
  20842. }
  20843. }
  20844. // Particles
  20845. for (index = 0; index < scene.particleSystems.length; index++) {
  20846. var system = scene.particleSystems[index];
  20847. if (system.emitter === source) {
  20848. system.clone(system.name, _this);
  20849. }
  20850. }
  20851. _this.computeWorldMatrix(true);
  20852. }
  20853. // Parent
  20854. if (parent !== null) {
  20855. _this.parent = parent;
  20856. }
  20857. return _this;
  20858. }
  20859. Object.defineProperty(Mesh, "FRONTSIDE", {
  20860. /**
  20861. * Mesh side orientation : usually the external or front surface
  20862. */
  20863. get: function () {
  20864. return Mesh._FRONTSIDE;
  20865. },
  20866. enumerable: true,
  20867. configurable: true
  20868. });
  20869. Object.defineProperty(Mesh, "BACKSIDE", {
  20870. /**
  20871. * Mesh side orientation : usually the internal or back surface
  20872. */
  20873. get: function () {
  20874. return Mesh._BACKSIDE;
  20875. },
  20876. enumerable: true,
  20877. configurable: true
  20878. });
  20879. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20880. /**
  20881. * Mesh side orientation : both internal and external or front and back surfaces
  20882. */
  20883. get: function () {
  20884. return Mesh._DOUBLESIDE;
  20885. },
  20886. enumerable: true,
  20887. configurable: true
  20888. });
  20889. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20890. /**
  20891. * Mesh side orientation : by default, `FRONTSIDE`
  20892. */
  20893. get: function () {
  20894. return Mesh._DEFAULTSIDE;
  20895. },
  20896. enumerable: true,
  20897. configurable: true
  20898. });
  20899. Object.defineProperty(Mesh, "NO_CAP", {
  20900. /**
  20901. * Mesh cap setting : no cap
  20902. */
  20903. get: function () {
  20904. return Mesh._NO_CAP;
  20905. },
  20906. enumerable: true,
  20907. configurable: true
  20908. });
  20909. Object.defineProperty(Mesh, "CAP_START", {
  20910. /**
  20911. * Mesh cap setting : one cap at the beginning of the mesh
  20912. */
  20913. get: function () {
  20914. return Mesh._CAP_START;
  20915. },
  20916. enumerable: true,
  20917. configurable: true
  20918. });
  20919. Object.defineProperty(Mesh, "CAP_END", {
  20920. /**
  20921. * Mesh cap setting : one cap at the end of the mesh
  20922. */
  20923. get: function () {
  20924. return Mesh._CAP_END;
  20925. },
  20926. enumerable: true,
  20927. configurable: true
  20928. });
  20929. Object.defineProperty(Mesh, "CAP_ALL", {
  20930. /**
  20931. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  20932. */
  20933. get: function () {
  20934. return Mesh._CAP_ALL;
  20935. },
  20936. enumerable: true,
  20937. configurable: true
  20938. });
  20939. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  20940. set: function (callback) {
  20941. if (this._onBeforeDrawObserver) {
  20942. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  20943. }
  20944. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  20945. },
  20946. enumerable: true,
  20947. configurable: true
  20948. });
  20949. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  20950. get: function () {
  20951. return this._morphTargetManager;
  20952. },
  20953. set: function (value) {
  20954. if (this._morphTargetManager === value) {
  20955. return;
  20956. }
  20957. this._morphTargetManager = value;
  20958. this._syncGeometryWithMorphTargetManager();
  20959. },
  20960. enumerable: true,
  20961. configurable: true
  20962. });
  20963. Object.defineProperty(Mesh.prototype, "source", {
  20964. get: function () {
  20965. return this._source;
  20966. },
  20967. enumerable: true,
  20968. configurable: true
  20969. });
  20970. // Methods
  20971. /**
  20972. * Returns the string "Mesh".
  20973. */
  20974. Mesh.prototype.getClassName = function () {
  20975. return "Mesh";
  20976. };
  20977. /**
  20978. * Returns a string.
  20979. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20980. */
  20981. Mesh.prototype.toString = function (fullDetails) {
  20982. var ret = _super.prototype.toString.call(this, fullDetails);
  20983. ret += ", n vertices: " + this.getTotalVertices();
  20984. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  20985. if (this.animations) {
  20986. for (var i = 0; i < this.animations.length; i++) {
  20987. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20988. }
  20989. }
  20990. if (fullDetails) {
  20991. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  20992. }
  20993. return ret;
  20994. };
  20995. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  20996. /**
  20997. * True if the mesh has some Levels Of Details (LOD).
  20998. * Returns a boolean.
  20999. */
  21000. get: function () {
  21001. return this._LODLevels.length > 0;
  21002. },
  21003. enumerable: true,
  21004. configurable: true
  21005. });
  21006. Mesh.prototype._sortLODLevels = function () {
  21007. this._LODLevels.sort(function (a, b) {
  21008. if (a.distance < b.distance) {
  21009. return 1;
  21010. }
  21011. if (a.distance > b.distance) {
  21012. return -1;
  21013. }
  21014. return 0;
  21015. });
  21016. };
  21017. /**
  21018. * Add a mesh as LOD level triggered at the given distance.
  21019. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21020. * @param {number} distance The distance from the center of the object to show this level
  21021. * @param {Mesh} mesh The mesh to be added as LOD level
  21022. * @return {Mesh} This mesh (for chaining)
  21023. */
  21024. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21025. if (mesh && mesh._masterMesh) {
  21026. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21027. return this;
  21028. }
  21029. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21030. this._LODLevels.push(level);
  21031. if (mesh) {
  21032. mesh._masterMesh = this;
  21033. }
  21034. this._sortLODLevels();
  21035. return this;
  21036. };
  21037. /**
  21038. * Returns the LOD level mesh at the passed distance or null if not found.
  21039. * It is related to the method `addLODLevel(distance, mesh)`.
  21040. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21041. * Returns an object Mesh or `null`.
  21042. */
  21043. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21044. for (var index = 0; index < this._LODLevels.length; index++) {
  21045. var level = this._LODLevels[index];
  21046. if (level.distance === distance) {
  21047. return level.mesh;
  21048. }
  21049. }
  21050. return null;
  21051. };
  21052. /**
  21053. * Remove a mesh from the LOD array
  21054. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21055. * @param {Mesh} mesh The mesh to be removed.
  21056. * @return {Mesh} This mesh (for chaining)
  21057. */
  21058. Mesh.prototype.removeLODLevel = function (mesh) {
  21059. for (var index = 0; index < this._LODLevels.length; index++) {
  21060. if (this._LODLevels[index].mesh === mesh) {
  21061. this._LODLevels.splice(index, 1);
  21062. if (mesh) {
  21063. mesh._masterMesh = null;
  21064. }
  21065. }
  21066. }
  21067. this._sortLODLevels();
  21068. return this;
  21069. };
  21070. /**
  21071. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21072. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21073. */
  21074. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21075. if (!this._LODLevels || this._LODLevels.length === 0) {
  21076. return this;
  21077. }
  21078. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21079. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21080. if (this.onLODLevelSelection) {
  21081. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21082. }
  21083. return this;
  21084. }
  21085. for (var index = 0; index < this._LODLevels.length; index++) {
  21086. var level = this._LODLevels[index];
  21087. if (level.distance < distanceToCamera) {
  21088. if (level.mesh) {
  21089. level.mesh._preActivate();
  21090. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21091. }
  21092. if (this.onLODLevelSelection) {
  21093. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21094. }
  21095. return level.mesh;
  21096. }
  21097. }
  21098. if (this.onLODLevelSelection) {
  21099. this.onLODLevelSelection(distanceToCamera, this, this);
  21100. }
  21101. return this;
  21102. };
  21103. Object.defineProperty(Mesh.prototype, "geometry", {
  21104. /**
  21105. * Returns the mesh internal Geometry object.
  21106. */
  21107. get: function () {
  21108. return this._geometry;
  21109. },
  21110. enumerable: true,
  21111. configurable: true
  21112. });
  21113. /**
  21114. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21115. */
  21116. Mesh.prototype.getTotalVertices = function () {
  21117. if (!this._geometry) {
  21118. return 0;
  21119. }
  21120. return this._geometry.getTotalVertices();
  21121. };
  21122. /**
  21123. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21124. * 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.
  21125. * You can force the copy with forceCopy === true
  21126. * Returns null if the mesh has no geometry or no vertex buffer.
  21127. * Possible `kind` values :
  21128. * - BABYLON.VertexBuffer.PositionKind
  21129. * - BABYLON.VertexBuffer.UVKind
  21130. * - BABYLON.VertexBuffer.UV2Kind
  21131. * - BABYLON.VertexBuffer.UV3Kind
  21132. * - BABYLON.VertexBuffer.UV4Kind
  21133. * - BABYLON.VertexBuffer.UV5Kind
  21134. * - BABYLON.VertexBuffer.UV6Kind
  21135. * - BABYLON.VertexBuffer.ColorKind
  21136. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21137. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21138. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21139. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21140. */
  21141. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21142. if (!this._geometry) {
  21143. return null;
  21144. }
  21145. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21146. };
  21147. /**
  21148. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21149. * Returns `undefined` if the mesh has no geometry.
  21150. * Possible `kind` values :
  21151. * - BABYLON.VertexBuffer.PositionKind
  21152. * - BABYLON.VertexBuffer.UVKind
  21153. * - BABYLON.VertexBuffer.UV2Kind
  21154. * - BABYLON.VertexBuffer.UV3Kind
  21155. * - BABYLON.VertexBuffer.UV4Kind
  21156. * - BABYLON.VertexBuffer.UV5Kind
  21157. * - BABYLON.VertexBuffer.UV6Kind
  21158. * - BABYLON.VertexBuffer.ColorKind
  21159. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21160. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21161. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21162. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21163. */
  21164. Mesh.prototype.getVertexBuffer = function (kind) {
  21165. if (!this._geometry) {
  21166. return undefined;
  21167. }
  21168. return this._geometry.getVertexBuffer(kind);
  21169. };
  21170. /**
  21171. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21172. * Possible `kind` values :
  21173. * - BABYLON.VertexBuffer.PositionKind
  21174. * - BABYLON.VertexBuffer.UVKind
  21175. * - BABYLON.VertexBuffer.UV2Kind
  21176. * - BABYLON.VertexBuffer.UV3Kind
  21177. * - BABYLON.VertexBuffer.UV4Kind
  21178. * - BABYLON.VertexBuffer.UV5Kind
  21179. * - BABYLON.VertexBuffer.UV6Kind
  21180. * - BABYLON.VertexBuffer.ColorKind
  21181. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21182. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21183. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21184. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21185. */
  21186. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21187. if (!this._geometry) {
  21188. if (this._delayInfo) {
  21189. return this._delayInfo.indexOf(kind) !== -1;
  21190. }
  21191. return false;
  21192. }
  21193. return this._geometry.isVerticesDataPresent(kind);
  21194. };
  21195. /**
  21196. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21197. * Possible `kind` values :
  21198. * - BABYLON.VertexBuffer.PositionKind
  21199. * - BABYLON.VertexBuffer.UVKind
  21200. * - BABYLON.VertexBuffer.UV2Kind
  21201. * - BABYLON.VertexBuffer.UV3Kind
  21202. * - BABYLON.VertexBuffer.UV4Kind
  21203. * - BABYLON.VertexBuffer.UV5Kind
  21204. * - BABYLON.VertexBuffer.UV6Kind
  21205. * - BABYLON.VertexBuffer.ColorKind
  21206. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21207. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21208. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21209. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21210. */
  21211. Mesh.prototype.getVerticesDataKinds = function () {
  21212. if (!this._geometry) {
  21213. var result = [];
  21214. if (this._delayInfo) {
  21215. this._delayInfo.forEach(function (kind, index, array) {
  21216. result.push(kind);
  21217. });
  21218. }
  21219. return result;
  21220. }
  21221. return this._geometry.getVerticesDataKinds();
  21222. };
  21223. /**
  21224. * Returns a positive integer : the total number of indices in this mesh geometry.
  21225. * Returns zero if the mesh has no geometry.
  21226. */
  21227. Mesh.prototype.getTotalIndices = function () {
  21228. if (!this._geometry) {
  21229. return 0;
  21230. }
  21231. return this._geometry.getTotalIndices();
  21232. };
  21233. /**
  21234. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21235. * 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.
  21236. * Returns an empty array if the mesh has no geometry.
  21237. */
  21238. Mesh.prototype.getIndices = function (copyWhenShared) {
  21239. if (!this._geometry) {
  21240. return [];
  21241. }
  21242. return this._geometry.getIndices(copyWhenShared);
  21243. };
  21244. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21245. get: function () {
  21246. return this._masterMesh !== null && this._masterMesh !== undefined;
  21247. },
  21248. enumerable: true,
  21249. configurable: true
  21250. });
  21251. /**
  21252. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21253. */
  21254. Mesh.prototype.isReady = function () {
  21255. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21256. return false;
  21257. }
  21258. return _super.prototype.isReady.call(this);
  21259. };
  21260. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21261. get: function () {
  21262. return this._sideOrientation;
  21263. },
  21264. /**
  21265. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21266. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21267. */
  21268. set: function (sideO) {
  21269. this._sideOrientation = sideO;
  21270. },
  21271. enumerable: true,
  21272. configurable: true
  21273. });
  21274. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21275. /**
  21276. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21277. * This property is pertinent only for updatable parametric shapes.
  21278. */
  21279. get: function () {
  21280. return this._areNormalsFrozen;
  21281. },
  21282. enumerable: true,
  21283. configurable: true
  21284. });
  21285. /**
  21286. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21287. * It has no effect at all on other shapes.
  21288. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21289. * Returns the Mesh.
  21290. */
  21291. Mesh.prototype.freezeNormals = function () {
  21292. this._areNormalsFrozen = true;
  21293. return this;
  21294. };
  21295. /**
  21296. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21297. * It has no effect at all on other shapes.
  21298. * It reactivates the mesh normals computation if it was previously frozen.
  21299. * Returns the Mesh.
  21300. */
  21301. Mesh.prototype.unfreezeNormals = function () {
  21302. this._areNormalsFrozen = false;
  21303. return this;
  21304. };
  21305. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21306. /**
  21307. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21308. */
  21309. set: function (count) {
  21310. this._overridenInstanceCount = count;
  21311. },
  21312. enumerable: true,
  21313. configurable: true
  21314. });
  21315. // Methods
  21316. Mesh.prototype._preActivate = function () {
  21317. var sceneRenderId = this.getScene().getRenderId();
  21318. if (this._preActivateId === sceneRenderId) {
  21319. return this;
  21320. }
  21321. this._preActivateId = sceneRenderId;
  21322. this._visibleInstances = null;
  21323. return this;
  21324. };
  21325. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21326. if (this._visibleInstances) {
  21327. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21328. }
  21329. return this;
  21330. };
  21331. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21332. if (!this._visibleInstances) {
  21333. this._visibleInstances = {};
  21334. this._visibleInstances.defaultRenderId = renderId;
  21335. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21336. }
  21337. if (!this._visibleInstances[renderId]) {
  21338. this._visibleInstances[renderId] = new Array();
  21339. }
  21340. this._visibleInstances[renderId].push(instance);
  21341. return this;
  21342. };
  21343. /**
  21344. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21345. * This means the mesh underlying bounding box and sphere are recomputed.
  21346. * Returns the Mesh.
  21347. */
  21348. Mesh.prototype.refreshBoundingInfo = function () {
  21349. if (this._boundingInfo.isLocked) {
  21350. return;
  21351. }
  21352. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21353. if (data) {
  21354. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21355. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21356. }
  21357. if (this.subMeshes) {
  21358. for (var index = 0; index < this.subMeshes.length; index++) {
  21359. this.subMeshes[index].refreshBoundingInfo();
  21360. }
  21361. }
  21362. this._updateBoundingInfo();
  21363. return this;
  21364. };
  21365. Mesh.prototype._createGlobalSubMesh = function (force) {
  21366. var totalVertices = this.getTotalVertices();
  21367. if (!totalVertices || !this.getIndices()) {
  21368. return null;
  21369. }
  21370. // Check if we need to recreate the submeshes
  21371. if (this.subMeshes && this.subMeshes.length > 0) {
  21372. var totalIndices = this.getIndices().length;
  21373. var needToRecreate = false;
  21374. if (force) {
  21375. needToRecreate = true;
  21376. }
  21377. else {
  21378. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21379. var submesh = _a[_i];
  21380. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21381. needToRecreate = true;
  21382. break;
  21383. }
  21384. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21385. needToRecreate = true;
  21386. break;
  21387. }
  21388. }
  21389. }
  21390. if (!needToRecreate) {
  21391. return;
  21392. }
  21393. }
  21394. this.releaseSubMeshes();
  21395. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21396. };
  21397. Mesh.prototype.subdivide = function (count) {
  21398. if (count < 1) {
  21399. return;
  21400. }
  21401. var totalIndices = this.getTotalIndices();
  21402. var subdivisionSize = (totalIndices / count) | 0;
  21403. var offset = 0;
  21404. // Ensure that subdivisionSize is a multiple of 3
  21405. while (subdivisionSize % 3 !== 0) {
  21406. subdivisionSize++;
  21407. }
  21408. this.releaseSubMeshes();
  21409. for (var index = 0; index < count; index++) {
  21410. if (offset >= totalIndices) {
  21411. break;
  21412. }
  21413. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21414. offset += subdivisionSize;
  21415. }
  21416. this.synchronizeInstances();
  21417. };
  21418. /**
  21419. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21420. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21421. * The `data` are either a numeric array either a Float32Array.
  21422. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21423. * 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).
  21424. * Note that a new underlying VertexBuffer object is created each call.
  21425. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21426. *
  21427. * Possible `kind` values :
  21428. * - BABYLON.VertexBuffer.PositionKind
  21429. * - BABYLON.VertexBuffer.UVKind
  21430. * - BABYLON.VertexBuffer.UV2Kind
  21431. * - BABYLON.VertexBuffer.UV3Kind
  21432. * - BABYLON.VertexBuffer.UV4Kind
  21433. * - BABYLON.VertexBuffer.UV5Kind
  21434. * - BABYLON.VertexBuffer.UV6Kind
  21435. * - BABYLON.VertexBuffer.ColorKind
  21436. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21437. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21438. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21439. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21440. *
  21441. * Returns the Mesh.
  21442. */
  21443. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21444. if (!this._geometry) {
  21445. var vertexData = new BABYLON.VertexData();
  21446. vertexData.set(data, kind);
  21447. var scene = this.getScene();
  21448. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21449. }
  21450. else {
  21451. this._geometry.setVerticesData(kind, data, updatable, stride);
  21452. }
  21453. return this;
  21454. };
  21455. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21456. if (updatable === void 0) { updatable = true; }
  21457. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21458. return;
  21459. }
  21460. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21461. };
  21462. /**
  21463. * Sets the mesh VertexBuffer.
  21464. * Returns the Mesh.
  21465. */
  21466. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21467. if (!this._geometry) {
  21468. var scene = this.getScene();
  21469. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21470. }
  21471. this._geometry.setVerticesBuffer(buffer);
  21472. return this;
  21473. };
  21474. /**
  21475. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21476. * If the mesh has no geometry, it is simply returned as it is.
  21477. * The `data` are either a numeric array either a Float32Array.
  21478. * No new underlying VertexBuffer object is created.
  21479. * 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.
  21480. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21481. *
  21482. * Possible `kind` values :
  21483. * - BABYLON.VertexBuffer.PositionKind
  21484. * - BABYLON.VertexBuffer.UVKind
  21485. * - BABYLON.VertexBuffer.UV2Kind
  21486. * - BABYLON.VertexBuffer.UV3Kind
  21487. * - BABYLON.VertexBuffer.UV4Kind
  21488. * - BABYLON.VertexBuffer.UV5Kind
  21489. * - BABYLON.VertexBuffer.UV6Kind
  21490. * - BABYLON.VertexBuffer.ColorKind
  21491. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21492. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21493. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21494. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21495. *
  21496. * Returns the Mesh.
  21497. */
  21498. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21499. if (!this._geometry) {
  21500. return;
  21501. }
  21502. if (!makeItUnique) {
  21503. this._geometry.updateVerticesData(kind, data, updateExtends);
  21504. }
  21505. else {
  21506. this.makeGeometryUnique();
  21507. this.updateVerticesData(kind, data, updateExtends, false);
  21508. }
  21509. return this;
  21510. };
  21511. /**
  21512. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21513. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21514. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21515. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21516. * Returns the Mesh.
  21517. */
  21518. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21519. if (computeNormals === void 0) { computeNormals = true; }
  21520. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21521. positionFunction(positions);
  21522. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21523. if (computeNormals) {
  21524. var indices = this.getIndices();
  21525. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21526. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21527. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21528. }
  21529. return this;
  21530. };
  21531. /**
  21532. * Creates a un-shared specific occurence of the geometry for the mesh.
  21533. * Returns the Mesh.
  21534. */
  21535. Mesh.prototype.makeGeometryUnique = function () {
  21536. if (!this._geometry) {
  21537. return;
  21538. }
  21539. var oldGeometry = this._geometry;
  21540. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21541. oldGeometry.releaseForMesh(this, true);
  21542. geometry.applyToMesh(this);
  21543. return this;
  21544. };
  21545. /**
  21546. * Sets the mesh indices.
  21547. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21548. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21549. * This method creates a new index buffer each call.
  21550. * Returns the Mesh.
  21551. */
  21552. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21553. if (!this._geometry) {
  21554. var vertexData = new BABYLON.VertexData();
  21555. vertexData.indices = indices;
  21556. var scene = this.getScene();
  21557. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21558. }
  21559. else {
  21560. this._geometry.setIndices(indices, totalVertices);
  21561. }
  21562. return this;
  21563. };
  21564. /**
  21565. * Invert the geometry to move from a right handed system to a left handed one.
  21566. * Returns the Mesh.
  21567. */
  21568. Mesh.prototype.toLeftHanded = function () {
  21569. if (!this._geometry) {
  21570. return;
  21571. }
  21572. this._geometry.toLeftHanded();
  21573. return this;
  21574. };
  21575. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21576. var engine = this.getScene().getEngine();
  21577. // Wireframe
  21578. var indexToBind;
  21579. if (this._unIndexed) {
  21580. indexToBind = null;
  21581. }
  21582. else {
  21583. switch (fillMode) {
  21584. case BABYLON.Material.PointFillMode:
  21585. indexToBind = null;
  21586. break;
  21587. case BABYLON.Material.WireFrameFillMode:
  21588. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21589. break;
  21590. default:
  21591. case BABYLON.Material.TriangleFillMode:
  21592. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21593. break;
  21594. }
  21595. }
  21596. // VBOs
  21597. this._geometry._bind(effect, indexToBind);
  21598. return this;
  21599. };
  21600. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21601. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21602. return this;
  21603. }
  21604. this.onBeforeDrawObservable.notifyObservers(this);
  21605. var engine = this.getScene().getEngine();
  21606. // Draw order
  21607. switch (fillMode) {
  21608. case BABYLON.Material.PointFillMode:
  21609. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21610. break;
  21611. case BABYLON.Material.WireFrameFillMode:
  21612. if (this._unIndexed) {
  21613. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21614. }
  21615. else {
  21616. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  21617. }
  21618. break;
  21619. default:
  21620. if (this._unIndexed) {
  21621. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21622. }
  21623. else {
  21624. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21625. }
  21626. }
  21627. return this;
  21628. };
  21629. /**
  21630. * Registers for this mesh a javascript function called just before the rendering process.
  21631. * This function is passed the current mesh.
  21632. * Return the Mesh.
  21633. */
  21634. Mesh.prototype.registerBeforeRender = function (func) {
  21635. this.onBeforeRenderObservable.add(func);
  21636. return this;
  21637. };
  21638. /**
  21639. * Disposes a previously registered javascript function called before the rendering.
  21640. * This function is passed the current mesh.
  21641. * Returns the Mesh.
  21642. */
  21643. Mesh.prototype.unregisterBeforeRender = function (func) {
  21644. this.onBeforeRenderObservable.removeCallback(func);
  21645. return this;
  21646. };
  21647. /**
  21648. * Registers for this mesh a javascript function called just after the rendering is complete.
  21649. * This function is passed the current mesh.
  21650. * Returns the Mesh.
  21651. */
  21652. Mesh.prototype.registerAfterRender = function (func) {
  21653. this.onAfterRenderObservable.add(func);
  21654. return this;
  21655. };
  21656. /**
  21657. * Disposes a previously registered javascript function called after the rendering.
  21658. * This function is passed the current mesh.
  21659. * Return the Mesh.
  21660. */
  21661. Mesh.prototype.unregisterAfterRender = function (func) {
  21662. this.onAfterRenderObservable.removeCallback(func);
  21663. return this;
  21664. };
  21665. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21666. var scene = this.getScene();
  21667. this._batchCache.mustReturn = false;
  21668. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21669. this._batchCache.visibleInstances[subMeshId] = null;
  21670. if (this._visibleInstances) {
  21671. var currentRenderId = scene.getRenderId();
  21672. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21673. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21674. var selfRenderId = this._renderId;
  21675. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21676. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21677. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21678. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21679. }
  21680. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21681. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21682. this._batchCache.mustReturn = true;
  21683. return this._batchCache;
  21684. }
  21685. if (currentRenderId !== selfRenderId) {
  21686. this._batchCache.renderSelf[subMeshId] = false;
  21687. }
  21688. }
  21689. this._renderIdForInstances[subMeshId] = currentRenderId;
  21690. }
  21691. return this._batchCache;
  21692. };
  21693. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21694. var visibleInstances = batch.visibleInstances[subMesh._id];
  21695. var matricesCount = visibleInstances.length + 1;
  21696. var bufferSize = matricesCount * 16 * 4;
  21697. var currentInstancesBufferSize = this._instancesBufferSize;
  21698. var instancesBuffer = this._instancesBuffer;
  21699. while (this._instancesBufferSize < bufferSize) {
  21700. this._instancesBufferSize *= 2;
  21701. }
  21702. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21703. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21704. }
  21705. var offset = 0;
  21706. var instancesCount = 0;
  21707. var world = this.getWorldMatrix();
  21708. if (batch.renderSelf[subMesh._id]) {
  21709. world.copyToArray(this._instancesData, offset);
  21710. offset += 16;
  21711. instancesCount++;
  21712. }
  21713. if (visibleInstances) {
  21714. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21715. var instance = visibleInstances[instanceIndex];
  21716. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21717. offset += 16;
  21718. instancesCount++;
  21719. }
  21720. }
  21721. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21722. if (instancesBuffer) {
  21723. instancesBuffer.dispose();
  21724. }
  21725. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21726. this._instancesBuffer = instancesBuffer;
  21727. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21728. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21729. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21730. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21731. }
  21732. else {
  21733. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21734. }
  21735. this._bind(subMesh, effect, fillMode);
  21736. this._draw(subMesh, fillMode, instancesCount);
  21737. engine.unbindInstanceAttributes();
  21738. return this;
  21739. };
  21740. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21741. var scene = this.getScene();
  21742. var engine = scene.getEngine();
  21743. if (hardwareInstancedRendering) {
  21744. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21745. }
  21746. else {
  21747. if (batch.renderSelf[subMesh._id]) {
  21748. // Draw
  21749. if (onBeforeDraw) {
  21750. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21751. }
  21752. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21753. }
  21754. if (batch.visibleInstances[subMesh._id]) {
  21755. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21756. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21757. // World
  21758. var world = instance.getWorldMatrix();
  21759. if (onBeforeDraw) {
  21760. onBeforeDraw(true, world, effectiveMaterial);
  21761. }
  21762. // Draw
  21763. this._draw(subMesh, fillMode);
  21764. }
  21765. }
  21766. }
  21767. return this;
  21768. };
  21769. /**
  21770. * Triggers the draw call for the mesh.
  21771. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21772. * Returns the Mesh.
  21773. */
  21774. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21775. this.checkOcclusionQuery();
  21776. if (this._isOccluded) {
  21777. return;
  21778. }
  21779. var scene = this.getScene();
  21780. // Managing instances
  21781. var batch = this._getInstancesRenderList(subMesh._id);
  21782. if (batch.mustReturn) {
  21783. return this;
  21784. }
  21785. // Checking geometry state
  21786. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21787. return this;
  21788. }
  21789. var callbackIndex;
  21790. this.onBeforeRenderObservable.notifyObservers(this);
  21791. var engine = scene.getEngine();
  21792. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21793. // Material
  21794. var effectiveMaterial = subMesh.getMaterial();
  21795. if (!effectiveMaterial) {
  21796. return this;
  21797. }
  21798. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21799. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  21800. return this;
  21801. }
  21802. }
  21803. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21804. return this;
  21805. }
  21806. // Alpha mode
  21807. if (enableAlphaMode) {
  21808. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21809. }
  21810. // Outline - step 1
  21811. var savedDepthWrite = engine.getDepthWrite();
  21812. if (this.renderOutline) {
  21813. engine.setDepthWrite(false);
  21814. scene.getOutlineRenderer().render(subMesh, batch);
  21815. engine.setDepthWrite(savedDepthWrite);
  21816. }
  21817. var effect;
  21818. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21819. effect = subMesh.effect;
  21820. }
  21821. else {
  21822. effect = effectiveMaterial.getEffect();
  21823. }
  21824. effectiveMaterial._preBind(effect);
  21825. // Bind
  21826. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21827. if (!hardwareInstancedRendering) {
  21828. this._bind(subMesh, effect, fillMode);
  21829. }
  21830. var world = this.getWorldMatrix();
  21831. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21832. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  21833. }
  21834. else {
  21835. effectiveMaterial.bind(world, this);
  21836. }
  21837. // Draw
  21838. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21839. // Unbind
  21840. effectiveMaterial.unbind();
  21841. // Outline - step 2
  21842. if (this.renderOutline && savedDepthWrite) {
  21843. engine.setDepthWrite(true);
  21844. engine.setColorWrite(false);
  21845. scene.getOutlineRenderer().render(subMesh, batch);
  21846. engine.setColorWrite(true);
  21847. }
  21848. // Overlay
  21849. if (this.renderOverlay) {
  21850. var currentMode = engine.getAlphaMode();
  21851. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21852. scene.getOutlineRenderer().render(subMesh, batch, true);
  21853. engine.setAlphaMode(currentMode);
  21854. }
  21855. this.onAfterRenderObservable.notifyObservers(this);
  21856. return this;
  21857. };
  21858. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21859. if (isInstance) {
  21860. effectiveMaterial.bindOnlyWorldMatrix(world);
  21861. }
  21862. return this;
  21863. };
  21864. /**
  21865. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21866. */
  21867. Mesh.prototype.getEmittedParticleSystems = function () {
  21868. var results = new Array();
  21869. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21870. var particleSystem = this.getScene().particleSystems[index];
  21871. if (particleSystem.emitter === this) {
  21872. results.push(particleSystem);
  21873. }
  21874. }
  21875. return results;
  21876. };
  21877. /**
  21878. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21879. */
  21880. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21881. var results = new Array();
  21882. var descendants = this.getDescendants();
  21883. descendants.push(this);
  21884. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21885. var particleSystem = this.getScene().particleSystems[index];
  21886. var emitter = particleSystem.emitter;
  21887. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  21888. results.push(particleSystem);
  21889. }
  21890. }
  21891. return results;
  21892. };
  21893. Mesh.prototype._checkDelayState = function () {
  21894. var scene = this.getScene();
  21895. if (this._geometry) {
  21896. this._geometry.load(scene);
  21897. }
  21898. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21899. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21900. this._queueLoad(this, scene);
  21901. }
  21902. return this;
  21903. };
  21904. Mesh.prototype._queueLoad = function (mesh, scene) {
  21905. var _this = this;
  21906. scene._addPendingData(mesh);
  21907. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21908. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21909. if (data instanceof ArrayBuffer) {
  21910. _this._delayLoadingFunction(data, _this);
  21911. }
  21912. else {
  21913. _this._delayLoadingFunction(JSON.parse(data), _this);
  21914. }
  21915. _this.instances.forEach(function (instance) {
  21916. instance._syncSubMeshes();
  21917. });
  21918. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21919. scene._removePendingData(_this);
  21920. }, function () { }, scene.database, getBinaryData);
  21921. return this;
  21922. };
  21923. /**
  21924. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21925. */
  21926. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  21927. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21928. return false;
  21929. }
  21930. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  21931. return false;
  21932. }
  21933. this._checkDelayState();
  21934. return true;
  21935. };
  21936. /**
  21937. * Sets the mesh material by the material or multiMaterial `id` property.
  21938. * The material `id` is a string identifying the material or the multiMaterial.
  21939. * This method returns the Mesh.
  21940. */
  21941. Mesh.prototype.setMaterialByID = function (id) {
  21942. var materials = this.getScene().materials;
  21943. var index;
  21944. for (index = materials.length - 1; index > -1; index--) {
  21945. if (materials[index].id === id) {
  21946. this.material = materials[index];
  21947. return this;
  21948. }
  21949. }
  21950. // Multi
  21951. var multiMaterials = this.getScene().multiMaterials;
  21952. for (index = multiMaterials.length - 1; index > -1; index--) {
  21953. if (multiMaterials[index].id === id) {
  21954. this.material = multiMaterials[index];
  21955. return this;
  21956. }
  21957. }
  21958. return this;
  21959. };
  21960. /**
  21961. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  21962. */
  21963. Mesh.prototype.getAnimatables = function () {
  21964. var results = [];
  21965. if (this.material) {
  21966. results.push(this.material);
  21967. }
  21968. if (this.skeleton) {
  21969. results.push(this.skeleton);
  21970. }
  21971. return results;
  21972. };
  21973. /**
  21974. * Modifies the mesh geometry according to the passed transformation matrix.
  21975. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  21976. * The mesh normals are modified accordingly the same transformation.
  21977. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21978. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21979. * Returns the Mesh.
  21980. */
  21981. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  21982. // Position
  21983. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21984. return this;
  21985. }
  21986. var submeshes = this.subMeshes.splice(0);
  21987. this._resetPointsArrayCache();
  21988. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21989. var temp = [];
  21990. var index;
  21991. for (index = 0; index < data.length; index += 3) {
  21992. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  21993. }
  21994. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  21995. // Normals
  21996. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21997. return this;
  21998. }
  21999. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22000. temp = [];
  22001. for (index = 0; index < data.length; index += 3) {
  22002. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22003. }
  22004. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22005. // flip faces?
  22006. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22007. this.flipFaces();
  22008. }
  22009. // Restore submeshes
  22010. this.releaseSubMeshes();
  22011. this.subMeshes = submeshes;
  22012. return this;
  22013. };
  22014. /**
  22015. * Modifies the mesh geometry according to its own current World Matrix.
  22016. * The mesh World Matrix is then reset.
  22017. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22018. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22019. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22020. * Returns the Mesh.
  22021. */
  22022. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22023. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22024. this.scaling.copyFromFloats(1, 1, 1);
  22025. this.position.copyFromFloats(0, 0, 0);
  22026. this.rotation.copyFromFloats(0, 0, 0);
  22027. //only if quaternion is already set
  22028. if (this.rotationQuaternion) {
  22029. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22030. }
  22031. this._worldMatrix = BABYLON.Matrix.Identity();
  22032. return this;
  22033. };
  22034. Object.defineProperty(Mesh.prototype, "_positions", {
  22035. // Cache
  22036. get: function () {
  22037. if (this._geometry) {
  22038. return this._geometry._positions;
  22039. }
  22040. return null;
  22041. },
  22042. enumerable: true,
  22043. configurable: true
  22044. });
  22045. Mesh.prototype._resetPointsArrayCache = function () {
  22046. if (this._geometry) {
  22047. this._geometry._resetPointsArrayCache();
  22048. }
  22049. return this;
  22050. };
  22051. Mesh.prototype._generatePointsArray = function () {
  22052. if (this._geometry) {
  22053. return this._geometry._generatePointsArray();
  22054. }
  22055. return false;
  22056. };
  22057. /**
  22058. * Returns a new Mesh object generated from the current mesh properties.
  22059. * This method must not get confused with createInstance().
  22060. * The parameter `name` is a string, the name given to the new mesh.
  22061. * The optional parameter `newParent` can be any Node object (default `null`).
  22062. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22063. * 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.
  22064. */
  22065. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22066. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22067. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22068. };
  22069. /**
  22070. * Disposes the mesh.
  22071. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22072. */
  22073. Mesh.prototype.dispose = function (doNotRecurse) {
  22074. var _this = this;
  22075. this.morphTargetManager = undefined;
  22076. if (this._geometry) {
  22077. this._geometry.releaseForMesh(this, true);
  22078. }
  22079. // Sources
  22080. var meshes = this.getScene().meshes;
  22081. meshes.forEach(function (mesh) {
  22082. if (mesh._source && mesh._source === _this) {
  22083. mesh._source = null;
  22084. }
  22085. });
  22086. this._source = null;
  22087. // Instances
  22088. if (this._instancesBuffer) {
  22089. this._instancesBuffer.dispose();
  22090. this._instancesBuffer = null;
  22091. }
  22092. while (this.instances.length) {
  22093. this.instances[0].dispose();
  22094. }
  22095. // Highlight layers.
  22096. var highlightLayers = this.getScene().highlightLayers;
  22097. for (var i = 0; i < highlightLayers.length; i++) {
  22098. var highlightLayer = highlightLayers[i];
  22099. if (highlightLayer) {
  22100. highlightLayer.removeMesh(this);
  22101. highlightLayer.removeExcludedMesh(this);
  22102. }
  22103. }
  22104. _super.prototype.dispose.call(this, doNotRecurse);
  22105. };
  22106. /**
  22107. * Modifies the mesh geometry according to a displacement map.
  22108. * 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.
  22109. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22110. * This method returns nothing.
  22111. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22112. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22113. * 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.
  22114. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22115. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22116. *
  22117. * Returns the Mesh.
  22118. */
  22119. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22120. var _this = this;
  22121. var scene = this.getScene();
  22122. var onload = function (img) {
  22123. // Getting height map data
  22124. var canvas = document.createElement("canvas");
  22125. var context = canvas.getContext("2d");
  22126. var heightMapWidth = img.width;
  22127. var heightMapHeight = img.height;
  22128. canvas.width = heightMapWidth;
  22129. canvas.height = heightMapHeight;
  22130. context.drawImage(img, 0, 0);
  22131. // Create VertexData from map data
  22132. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22133. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22134. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22135. //execute success callback, if set
  22136. if (onSuccess) {
  22137. onSuccess(_this);
  22138. }
  22139. };
  22140. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22141. return this;
  22142. };
  22143. /**
  22144. * Modifies the mesh geometry according to a displacementMap buffer.
  22145. * 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.
  22146. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22147. * This method returns nothing.
  22148. * 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.
  22149. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22150. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22151. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22152. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22153. *
  22154. * Returns the Mesh.
  22155. */
  22156. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22157. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22158. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22159. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22160. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22161. return this;
  22162. }
  22163. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22164. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22165. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22166. var position = BABYLON.Vector3.Zero();
  22167. var normal = BABYLON.Vector3.Zero();
  22168. var uv = BABYLON.Vector2.Zero();
  22169. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22170. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22171. for (var index = 0; index < positions.length; index += 3) {
  22172. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22173. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22174. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22175. // Compute height
  22176. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22177. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22178. var pos = (u + v * heightMapWidth) * 4;
  22179. var r = buffer[pos] / 255.0;
  22180. var g = buffer[pos + 1] / 255.0;
  22181. var b = buffer[pos + 2] / 255.0;
  22182. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22183. normal.normalize();
  22184. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22185. position = position.add(normal);
  22186. position.toArray(positions, index);
  22187. }
  22188. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22189. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22190. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22191. return this;
  22192. };
  22193. /**
  22194. * Modify the mesh to get a flat shading rendering.
  22195. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22196. * This method returns the Mesh.
  22197. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22198. */
  22199. Mesh.prototype.convertToFlatShadedMesh = function () {
  22200. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22201. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22202. var kinds = this.getVerticesDataKinds();
  22203. var vbs = [];
  22204. var data = [];
  22205. var newdata = [];
  22206. var updatableNormals = false;
  22207. var kindIndex;
  22208. var kind;
  22209. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22210. kind = kinds[kindIndex];
  22211. var vertexBuffer = this.getVertexBuffer(kind);
  22212. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22213. updatableNormals = vertexBuffer.isUpdatable();
  22214. kinds.splice(kindIndex, 1);
  22215. kindIndex--;
  22216. continue;
  22217. }
  22218. vbs[kind] = vertexBuffer;
  22219. data[kind] = vbs[kind].getData();
  22220. newdata[kind] = [];
  22221. }
  22222. // Save previous submeshes
  22223. var previousSubmeshes = this.subMeshes.slice(0);
  22224. var indices = this.getIndices();
  22225. var totalIndices = this.getTotalIndices();
  22226. // Generating unique vertices per face
  22227. var index;
  22228. for (index = 0; index < totalIndices; index++) {
  22229. var vertexIndex = indices[index];
  22230. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22231. kind = kinds[kindIndex];
  22232. var stride = vbs[kind].getStrideSize();
  22233. for (var offset = 0; offset < stride; offset++) {
  22234. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22235. }
  22236. }
  22237. }
  22238. // Updating faces & normal
  22239. var normals = [];
  22240. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22241. for (index = 0; index < totalIndices; index += 3) {
  22242. indices[index] = index;
  22243. indices[index + 1] = index + 1;
  22244. indices[index + 2] = index + 2;
  22245. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22246. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22247. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22248. var p1p2 = p1.subtract(p2);
  22249. var p3p2 = p3.subtract(p2);
  22250. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22251. // Store same normals for every vertex
  22252. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22253. normals.push(normal.x);
  22254. normals.push(normal.y);
  22255. normals.push(normal.z);
  22256. }
  22257. }
  22258. this.setIndices(indices);
  22259. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22260. // Updating vertex buffers
  22261. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22262. kind = kinds[kindIndex];
  22263. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22264. }
  22265. // Updating submeshes
  22266. this.releaseSubMeshes();
  22267. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22268. var previousOne = previousSubmeshes[submeshIndex];
  22269. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22270. }
  22271. this.synchronizeInstances();
  22272. return this;
  22273. };
  22274. /**
  22275. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22276. * In other words, more vertices, no more indices and a single bigger VBO.
  22277. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22278. * Returns the Mesh.
  22279. */
  22280. Mesh.prototype.convertToUnIndexedMesh = function () {
  22281. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22282. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22283. var kinds = this.getVerticesDataKinds();
  22284. var vbs = [];
  22285. var data = [];
  22286. var newdata = [];
  22287. var updatableNormals = false;
  22288. var kindIndex;
  22289. var kind;
  22290. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22291. kind = kinds[kindIndex];
  22292. var vertexBuffer = this.getVertexBuffer(kind);
  22293. vbs[kind] = vertexBuffer;
  22294. data[kind] = vbs[kind].getData();
  22295. newdata[kind] = [];
  22296. }
  22297. // Save previous submeshes
  22298. var previousSubmeshes = this.subMeshes.slice(0);
  22299. var indices = this.getIndices();
  22300. var totalIndices = this.getTotalIndices();
  22301. // Generating unique vertices per face
  22302. var index;
  22303. for (index = 0; index < totalIndices; index++) {
  22304. var vertexIndex = indices[index];
  22305. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22306. kind = kinds[kindIndex];
  22307. var stride = vbs[kind].getStrideSize();
  22308. for (var offset = 0; offset < stride; offset++) {
  22309. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22310. }
  22311. }
  22312. }
  22313. // Updating indices
  22314. for (index = 0; index < totalIndices; index += 3) {
  22315. indices[index] = index;
  22316. indices[index + 1] = index + 1;
  22317. indices[index + 2] = index + 2;
  22318. }
  22319. this.setIndices(indices);
  22320. // Updating vertex buffers
  22321. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22322. kind = kinds[kindIndex];
  22323. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22324. }
  22325. // Updating submeshes
  22326. this.releaseSubMeshes();
  22327. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22328. var previousOne = previousSubmeshes[submeshIndex];
  22329. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22330. }
  22331. this._unIndexed = true;
  22332. this.synchronizeInstances();
  22333. return this;
  22334. };
  22335. /**
  22336. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22337. * This method returns the Mesh.
  22338. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22339. */
  22340. Mesh.prototype.flipFaces = function (flipNormals) {
  22341. if (flipNormals === void 0) { flipNormals = false; }
  22342. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22343. var i;
  22344. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22345. for (i = 0; i < vertex_data.normals.length; i++) {
  22346. vertex_data.normals[i] *= -1;
  22347. }
  22348. }
  22349. var temp;
  22350. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22351. // reassign indices
  22352. temp = vertex_data.indices[i + 1];
  22353. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22354. vertex_data.indices[i + 2] = temp;
  22355. }
  22356. vertex_data.applyToMesh(this);
  22357. return this;
  22358. };
  22359. // Instances
  22360. /**
  22361. * Creates a new InstancedMesh object from the mesh model.
  22362. * An instance shares the same properties and the same material than its model.
  22363. * Only these properties of each instance can then be set individually :
  22364. * - position
  22365. * - rotation
  22366. * - rotationQuaternion
  22367. * - setPivotMatrix
  22368. * - scaling
  22369. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22370. * Warning : this method is not supported for Line mesh and LineSystem
  22371. */
  22372. Mesh.prototype.createInstance = function (name) {
  22373. return new BABYLON.InstancedMesh(name, this);
  22374. };
  22375. /**
  22376. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22377. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22378. * This method returns the Mesh.
  22379. */
  22380. Mesh.prototype.synchronizeInstances = function () {
  22381. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22382. var instance = this.instances[instanceIndex];
  22383. instance._syncSubMeshes();
  22384. }
  22385. return this;
  22386. };
  22387. /**
  22388. * Simplify the mesh according to the given array of settings.
  22389. * Function will return immediately and will simplify async. It returns the Mesh.
  22390. * @param settings a collection of simplification settings.
  22391. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22392. * @param type the type of simplification to run.
  22393. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22394. */
  22395. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22396. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22397. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22398. this.getScene().simplificationQueue.addTask({
  22399. settings: settings,
  22400. parallelProcessing: parallelProcessing,
  22401. mesh: this,
  22402. simplificationType: simplificationType,
  22403. successCallback: successCallback
  22404. });
  22405. return this;
  22406. };
  22407. /**
  22408. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22409. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22410. * This should be used together with the simplification to avoid disappearing triangles.
  22411. * Returns the Mesh.
  22412. * @param successCallback an optional success callback to be called after the optimization finished.
  22413. */
  22414. Mesh.prototype.optimizeIndices = function (successCallback) {
  22415. var _this = this;
  22416. var indices = this.getIndices();
  22417. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22418. var vectorPositions = [];
  22419. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22420. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22421. }
  22422. var dupes = [];
  22423. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22424. var realPos = vectorPositions.length - 1 - iteration;
  22425. var testedPosition = vectorPositions[realPos];
  22426. for (var j = 0; j < realPos; ++j) {
  22427. var againstPosition = vectorPositions[j];
  22428. if (testedPosition.equals(againstPosition)) {
  22429. dupes[realPos] = j;
  22430. break;
  22431. }
  22432. }
  22433. }, function () {
  22434. for (var i = 0; i < indices.length; ++i) {
  22435. indices[i] = dupes[indices[i]] || indices[i];
  22436. }
  22437. //indices are now reordered
  22438. var originalSubMeshes = _this.subMeshes.slice(0);
  22439. _this.setIndices(indices);
  22440. _this.subMeshes = originalSubMeshes;
  22441. if (successCallback) {
  22442. successCallback(_this);
  22443. }
  22444. });
  22445. return this;
  22446. };
  22447. Mesh.prototype.serialize = function (serializationObject) {
  22448. serializationObject.name = this.name;
  22449. serializationObject.id = this.id;
  22450. serializationObject.type = this.getClassName();
  22451. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22452. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22453. }
  22454. serializationObject.position = this.position.asArray();
  22455. if (this.rotationQuaternion) {
  22456. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22457. }
  22458. else if (this.rotation) {
  22459. serializationObject.rotation = this.rotation.asArray();
  22460. }
  22461. serializationObject.scaling = this.scaling.asArray();
  22462. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22463. serializationObject.isEnabled = this.isEnabled();
  22464. serializationObject.isVisible = this.isVisible;
  22465. serializationObject.infiniteDistance = this.infiniteDistance;
  22466. serializationObject.pickable = this.isPickable;
  22467. serializationObject.receiveShadows = this.receiveShadows;
  22468. serializationObject.billboardMode = this.billboardMode;
  22469. serializationObject.visibility = this.visibility;
  22470. serializationObject.checkCollisions = this.checkCollisions;
  22471. serializationObject.isBlocker = this.isBlocker;
  22472. // Parent
  22473. if (this.parent) {
  22474. serializationObject.parentId = this.parent.id;
  22475. }
  22476. // Geometry
  22477. var geometry = this._geometry;
  22478. if (geometry) {
  22479. var geometryId = geometry.id;
  22480. serializationObject.geometryId = geometryId;
  22481. // SubMeshes
  22482. serializationObject.subMeshes = [];
  22483. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22484. var subMesh = this.subMeshes[subIndex];
  22485. serializationObject.subMeshes.push({
  22486. materialIndex: subMesh.materialIndex,
  22487. verticesStart: subMesh.verticesStart,
  22488. verticesCount: subMesh.verticesCount,
  22489. indexStart: subMesh.indexStart,
  22490. indexCount: subMesh.indexCount
  22491. });
  22492. }
  22493. }
  22494. // Material
  22495. if (this.material) {
  22496. serializationObject.materialId = this.material.id;
  22497. }
  22498. else {
  22499. this.material = null;
  22500. }
  22501. // Morph targets
  22502. if (this.morphTargetManager) {
  22503. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22504. }
  22505. // Skeleton
  22506. if (this.skeleton) {
  22507. serializationObject.skeletonId = this.skeleton.id;
  22508. }
  22509. // Physics
  22510. //TODO implement correct serialization for physics impostors.
  22511. if (this.getPhysicsImpostor()) {
  22512. var impostor = this.getPhysicsImpostor();
  22513. serializationObject.physicsMass = impostor.getParam("mass");
  22514. serializationObject.physicsFriction = impostor.getParam("friction");
  22515. serializationObject.physicsRestitution = impostor.getParam("mass");
  22516. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22517. }
  22518. // Metadata
  22519. if (this.metadata) {
  22520. serializationObject.metadata = this.metadata;
  22521. }
  22522. // Instances
  22523. serializationObject.instances = [];
  22524. for (var index = 0; index < this.instances.length; index++) {
  22525. var instance = this.instances[index];
  22526. var serializationInstance = {
  22527. name: instance.name,
  22528. position: instance.position.asArray(),
  22529. scaling: instance.scaling.asArray()
  22530. };
  22531. if (instance.rotationQuaternion) {
  22532. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22533. }
  22534. else if (instance.rotation) {
  22535. serializationInstance.rotation = instance.rotation.asArray();
  22536. }
  22537. serializationObject.instances.push(serializationInstance);
  22538. // Animations
  22539. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22540. serializationInstance.ranges = instance.serializeAnimationRanges();
  22541. }
  22542. //
  22543. // Animations
  22544. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22545. serializationObject.ranges = this.serializeAnimationRanges();
  22546. // Layer mask
  22547. serializationObject.layerMask = this.layerMask;
  22548. // Alpha
  22549. serializationObject.alphaIndex = this.alphaIndex;
  22550. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22551. // Overlay
  22552. serializationObject.overlayAlpha = this.overlayAlpha;
  22553. serializationObject.overlayColor = this.overlayColor.asArray();
  22554. serializationObject.renderOverlay = this.renderOverlay;
  22555. // Fog
  22556. serializationObject.applyFog = this.applyFog;
  22557. // Action Manager
  22558. if (this.actionManager) {
  22559. serializationObject.actions = this.actionManager.serialize(this.name);
  22560. }
  22561. };
  22562. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22563. if (!this.geometry) {
  22564. return;
  22565. }
  22566. this._markSubMeshesAsAttributesDirty();
  22567. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22568. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22569. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22570. this.morphTargetManager = undefined;
  22571. return;
  22572. }
  22573. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22574. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22575. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22576. if (morphTarget.hasNormals) {
  22577. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22578. }
  22579. if (morphTarget.hasTangents) {
  22580. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22581. }
  22582. }
  22583. }
  22584. else {
  22585. var index = 0;
  22586. // Positions
  22587. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22588. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22589. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22590. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22591. }
  22592. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22593. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22594. }
  22595. index++;
  22596. }
  22597. }
  22598. };
  22599. // Statics
  22600. /**
  22601. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22602. * The parameter `parsedMesh` is the mesh to be copied.
  22603. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22604. */
  22605. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22606. var mesh;
  22607. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22608. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22609. }
  22610. else {
  22611. mesh = new Mesh(parsedMesh.name, scene);
  22612. }
  22613. mesh.id = parsedMesh.id;
  22614. if (BABYLON.Tags) {
  22615. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22616. }
  22617. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22618. if (parsedMesh.metadata !== undefined) {
  22619. mesh.metadata = parsedMesh.metadata;
  22620. }
  22621. if (parsedMesh.rotationQuaternion) {
  22622. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22623. }
  22624. else if (parsedMesh.rotation) {
  22625. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22626. }
  22627. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22628. if (parsedMesh.localMatrix) {
  22629. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22630. }
  22631. else if (parsedMesh.pivotMatrix) {
  22632. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22633. }
  22634. mesh.setEnabled(parsedMesh.isEnabled);
  22635. mesh.isVisible = parsedMesh.isVisible;
  22636. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22637. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22638. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22639. if (parsedMesh.applyFog !== undefined) {
  22640. mesh.applyFog = parsedMesh.applyFog;
  22641. }
  22642. if (parsedMesh.pickable !== undefined) {
  22643. mesh.isPickable = parsedMesh.pickable;
  22644. }
  22645. if (parsedMesh.alphaIndex !== undefined) {
  22646. mesh.alphaIndex = parsedMesh.alphaIndex;
  22647. }
  22648. mesh.receiveShadows = parsedMesh.receiveShadows;
  22649. mesh.billboardMode = parsedMesh.billboardMode;
  22650. if (parsedMesh.visibility !== undefined) {
  22651. mesh.visibility = parsedMesh.visibility;
  22652. }
  22653. mesh.checkCollisions = parsedMesh.checkCollisions;
  22654. if (parsedMesh.isBlocker !== undefined) {
  22655. mesh.isBlocker = parsedMesh.isBlocker;
  22656. }
  22657. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22658. // freezeWorldMatrix
  22659. if (parsedMesh.freezeWorldMatrix) {
  22660. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22661. }
  22662. // Parent
  22663. if (parsedMesh.parentId) {
  22664. mesh._waitingParentId = parsedMesh.parentId;
  22665. }
  22666. // Actions
  22667. if (parsedMesh.actions !== undefined) {
  22668. mesh._waitingActions = parsedMesh.actions;
  22669. }
  22670. // Overlay
  22671. if (parsedMesh.overlayAlpha !== undefined) {
  22672. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22673. }
  22674. if (parsedMesh.overlayColor !== undefined) {
  22675. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22676. }
  22677. if (parsedMesh.renderOverlay !== undefined) {
  22678. mesh.renderOverlay = parsedMesh.renderOverlay;
  22679. }
  22680. // Geometry
  22681. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22682. if (parsedMesh.delayLoadingFile) {
  22683. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22684. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22685. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22686. if (parsedMesh._binaryInfo) {
  22687. mesh._binaryInfo = parsedMesh._binaryInfo;
  22688. }
  22689. mesh._delayInfo = [];
  22690. if (parsedMesh.hasUVs) {
  22691. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22692. }
  22693. if (parsedMesh.hasUVs2) {
  22694. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22695. }
  22696. if (parsedMesh.hasUVs3) {
  22697. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22698. }
  22699. if (parsedMesh.hasUVs4) {
  22700. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22701. }
  22702. if (parsedMesh.hasUVs5) {
  22703. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22704. }
  22705. if (parsedMesh.hasUVs6) {
  22706. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22707. }
  22708. if (parsedMesh.hasColors) {
  22709. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22710. }
  22711. if (parsedMesh.hasMatricesIndices) {
  22712. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22713. }
  22714. if (parsedMesh.hasMatricesWeights) {
  22715. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22716. }
  22717. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22718. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22719. mesh._checkDelayState();
  22720. }
  22721. }
  22722. else {
  22723. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22724. }
  22725. // Material
  22726. if (parsedMesh.materialId) {
  22727. mesh.setMaterialByID(parsedMesh.materialId);
  22728. }
  22729. else {
  22730. mesh.material = null;
  22731. }
  22732. // Morph targets
  22733. if (parsedMesh.morphTargetManagerId > -1) {
  22734. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22735. }
  22736. // Skeleton
  22737. if (parsedMesh.skeletonId > -1) {
  22738. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22739. if (parsedMesh.numBoneInfluencers) {
  22740. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22741. }
  22742. }
  22743. // Animations
  22744. if (parsedMesh.animations) {
  22745. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22746. var parsedAnimation = parsedMesh.animations[animationIndex];
  22747. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22748. }
  22749. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22750. }
  22751. if (parsedMesh.autoAnimate) {
  22752. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22753. }
  22754. // Layer Mask
  22755. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22756. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22757. }
  22758. else {
  22759. mesh.layerMask = 0x0FFFFFFF;
  22760. }
  22761. // Physics
  22762. if (parsedMesh.physicsImpostor) {
  22763. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22764. mass: parsedMesh.physicsMass,
  22765. friction: parsedMesh.physicsFriction,
  22766. restitution: parsedMesh.physicsRestitution
  22767. }, scene);
  22768. }
  22769. // Instances
  22770. if (parsedMesh.instances) {
  22771. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22772. var parsedInstance = parsedMesh.instances[index];
  22773. var instance = mesh.createInstance(parsedInstance.name);
  22774. if (BABYLON.Tags) {
  22775. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22776. }
  22777. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22778. if (parsedInstance.parentId) {
  22779. instance._waitingParentId = parsedInstance.parentId;
  22780. }
  22781. if (parsedInstance.rotationQuaternion) {
  22782. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22783. }
  22784. else if (parsedInstance.rotation) {
  22785. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22786. }
  22787. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22788. instance.checkCollisions = mesh.checkCollisions;
  22789. if (parsedMesh.animations) {
  22790. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22791. parsedAnimation = parsedMesh.animations[animationIndex];
  22792. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22793. }
  22794. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22795. }
  22796. }
  22797. }
  22798. return mesh;
  22799. };
  22800. /**
  22801. * Creates a ribbon mesh.
  22802. * Please consider using the same method from the MeshBuilder class instead.
  22803. * 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.
  22804. *
  22805. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22806. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22807. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22808. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22809. * 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.
  22810. * 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.
  22811. * 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
  22812. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22813. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22814. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22815. */
  22816. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22817. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22818. pathArray: pathArray,
  22819. closeArray: closeArray,
  22820. closePath: closePath,
  22821. offset: offset,
  22822. updatable: updatable,
  22823. sideOrientation: sideOrientation,
  22824. instance: instance
  22825. }, scene);
  22826. };
  22827. /**
  22828. * Creates a plane polygonal mesh. By default, this is a disc.
  22829. * Please consider using the same method from the MeshBuilder class instead.
  22830. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22831. * 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.
  22832. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22833. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22834. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22835. */
  22836. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22837. var options = {
  22838. radius: radius,
  22839. tessellation: tessellation,
  22840. sideOrientation: sideOrientation,
  22841. updatable: updatable
  22842. };
  22843. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22844. };
  22845. /**
  22846. * Creates a box mesh.
  22847. * Please consider using the same method from the MeshBuilder class instead.
  22848. * The parameter `size` sets the size (float) of each box side (default 1).
  22849. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22850. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22851. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22852. */
  22853. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22854. var options = {
  22855. size: size,
  22856. sideOrientation: sideOrientation,
  22857. updatable: updatable
  22858. };
  22859. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22860. };
  22861. /**
  22862. * Creates a sphere mesh.
  22863. * Please consider using the same method from the MeshBuilder class instead.
  22864. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22865. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22866. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22867. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22868. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22869. */
  22870. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22871. var options = {
  22872. segments: segments,
  22873. diameterX: diameter,
  22874. diameterY: diameter,
  22875. diameterZ: diameter,
  22876. sideOrientation: sideOrientation,
  22877. updatable: updatable
  22878. };
  22879. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22880. };
  22881. /**
  22882. * Creates a cylinder or a cone mesh.
  22883. * Please consider using the same method from the MeshBuilder class instead.
  22884. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22885. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22886. * 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.
  22887. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22888. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22889. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22890. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22891. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22892. */
  22893. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22894. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22895. if (scene !== undefined) {
  22896. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22897. updatable = scene;
  22898. }
  22899. scene = subdivisions;
  22900. subdivisions = 1;
  22901. }
  22902. var options = {
  22903. height: height,
  22904. diameterTop: diameterTop,
  22905. diameterBottom: diameterBottom,
  22906. tessellation: tessellation,
  22907. subdivisions: subdivisions,
  22908. sideOrientation: sideOrientation,
  22909. updatable: updatable
  22910. };
  22911. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22912. };
  22913. // Torus (Code from SharpDX.org)
  22914. /**
  22915. * Creates a torus mesh.
  22916. * Please consider using the same method from the MeshBuilder class instead.
  22917. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22918. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22919. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22920. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22921. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22923. */
  22924. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22925. var options = {
  22926. diameter: diameter,
  22927. thickness: thickness,
  22928. tessellation: tessellation,
  22929. sideOrientation: sideOrientation,
  22930. updatable: updatable
  22931. };
  22932. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  22933. };
  22934. /**
  22935. * Creates a torus knot mesh.
  22936. * Please consider using the same method from the MeshBuilder class instead.
  22937. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22938. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22939. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22940. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22941. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22942. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22944. */
  22945. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  22946. var options = {
  22947. radius: radius,
  22948. tube: tube,
  22949. radialSegments: radialSegments,
  22950. tubularSegments: tubularSegments,
  22951. p: p,
  22952. q: q,
  22953. sideOrientation: sideOrientation,
  22954. updatable: updatable
  22955. };
  22956. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  22957. };
  22958. /**
  22959. * Creates a line mesh.
  22960. * Please consider using the same method from the MeshBuilder class instead.
  22961. * 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.
  22962. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22963. * The parameter `points` is an array successive Vector3.
  22964. * 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
  22965. * When updating an instance, remember that only point positions can change, not the number of points.
  22966. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22967. */
  22968. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  22969. var options = {
  22970. points: points,
  22971. updatable: updatable,
  22972. instance: instance
  22973. };
  22974. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  22975. };
  22976. /**
  22977. * Creates a dashed line mesh.
  22978. * Please consider using the same method from the MeshBuilder class instead.
  22979. * 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.
  22980. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22981. * The parameter `points` is an array successive Vector3.
  22982. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22983. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22984. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22985. * 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
  22986. * When updating an instance, remember that only point positions can change, not the number of points.
  22987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22988. */
  22989. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  22990. var options = {
  22991. points: points,
  22992. dashSize: dashSize,
  22993. gapSize: gapSize,
  22994. dashNb: dashNb,
  22995. updatable: updatable,
  22996. instance: instance
  22997. };
  22998. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  22999. };
  23000. /**
  23001. * Creates a polygon mesh.
  23002. * Please consider using the same method from the MeshBuilder class instead.
  23003. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23004. * 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.
  23005. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23007. * Remember you can only change the shape positions, not their number when updating a polygon.
  23008. */
  23009. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23010. var options = {
  23011. shape: shape,
  23012. holes: holes,
  23013. updatable: updatable,
  23014. sideOrientation: sideOrientation
  23015. };
  23016. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23017. };
  23018. /**
  23019. * Creates an extruded polygon mesh, with depth in the Y direction.
  23020. * Please consider using the same method from the MeshBuilder class instead.
  23021. */
  23022. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23023. var options = {
  23024. shape: shape,
  23025. holes: holes,
  23026. depth: depth,
  23027. updatable: updatable,
  23028. sideOrientation: sideOrientation
  23029. };
  23030. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23031. };
  23032. /**
  23033. * Creates an extruded shape mesh.
  23034. * 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.
  23035. * Please consider using the same method from the MeshBuilder class instead.
  23036. *
  23037. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23038. * 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
  23039. * extruded along the Z axis.
  23040. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23041. * 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.
  23042. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23043. * 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
  23044. * 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
  23045. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23046. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23047. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23048. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23049. */
  23050. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23051. var options = {
  23052. shape: shape,
  23053. path: path,
  23054. scale: scale,
  23055. rotation: rotation,
  23056. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23057. sideOrientation: sideOrientation,
  23058. instance: instance,
  23059. updatable: updatable
  23060. };
  23061. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23062. };
  23063. /**
  23064. * Creates an custom extruded shape mesh.
  23065. * 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.
  23066. * Please consider using the same method from the MeshBuilder class instead.
  23067. *
  23068. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23069. * 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
  23070. * extruded along the Z axis.
  23071. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23072. * 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
  23073. * and the distance of this point from the begining of the path :
  23074. * ```javascript
  23075. * var rotationFunction = function(i, distance) {
  23076. * // do things
  23077. * return rotationValue; }
  23078. * ```
  23079. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23080. * 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
  23081. * and the distance of this point from the begining of the path :
  23082. * ```javascript
  23083. * var scaleFunction = function(i, distance) {
  23084. * // do things
  23085. * return scaleValue;}
  23086. * ```
  23087. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23088. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23089. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23090. * 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
  23091. * 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
  23092. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23093. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23094. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23095. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23096. */
  23097. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23098. var options = {
  23099. shape: shape,
  23100. path: path,
  23101. scaleFunction: scaleFunction,
  23102. rotationFunction: rotationFunction,
  23103. ribbonCloseArray: ribbonCloseArray,
  23104. ribbonClosePath: ribbonClosePath,
  23105. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23106. sideOrientation: sideOrientation,
  23107. instance: instance,
  23108. updatable: updatable
  23109. };
  23110. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23111. };
  23112. /**
  23113. * Creates lathe mesh.
  23114. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23115. * Please consider using the same method from the MeshBuilder class instead.
  23116. * 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
  23117. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23118. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23119. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23121. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23123. */
  23124. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23125. var options = {
  23126. shape: shape,
  23127. radius: radius,
  23128. tessellation: tessellation,
  23129. sideOrientation: sideOrientation,
  23130. updatable: updatable
  23131. };
  23132. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23133. };
  23134. /**
  23135. * Creates a plane mesh.
  23136. * Please consider using the same method from the MeshBuilder class instead.
  23137. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23138. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23139. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23140. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23141. */
  23142. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23143. var options = {
  23144. size: size,
  23145. width: size,
  23146. height: size,
  23147. sideOrientation: sideOrientation,
  23148. updatable: updatable
  23149. };
  23150. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23151. };
  23152. /**
  23153. * Creates a ground mesh.
  23154. * Please consider using the same method from the MeshBuilder class instead.
  23155. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23156. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23157. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23158. */
  23159. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23160. var options = {
  23161. width: width,
  23162. height: height,
  23163. subdivisions: subdivisions,
  23164. updatable: updatable
  23165. };
  23166. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23167. };
  23168. /**
  23169. * Creates a tiled ground mesh.
  23170. * Please consider using the same method from the MeshBuilder class instead.
  23171. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23172. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23173. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23174. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23175. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23176. * numbers of subdivisions on the ground width and height of each tile.
  23177. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23178. */
  23179. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23180. var options = {
  23181. xmin: xmin,
  23182. zmin: zmin,
  23183. xmax: xmax,
  23184. zmax: zmax,
  23185. subdivisions: subdivisions,
  23186. precision: precision,
  23187. updatable: updatable
  23188. };
  23189. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23190. };
  23191. /**
  23192. * Creates a ground mesh from a height map.
  23193. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23194. * Please consider using the same method from the MeshBuilder class instead.
  23195. * The parameter `url` sets the URL of the height map image resource.
  23196. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23197. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23198. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23199. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23200. * 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).
  23201. * This function is passed the newly built mesh :
  23202. * ```javascript
  23203. * function(mesh) { // do things
  23204. * return; }
  23205. * ```
  23206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23207. */
  23208. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23209. var options = {
  23210. width: width,
  23211. height: height,
  23212. subdivisions: subdivisions,
  23213. minHeight: minHeight,
  23214. maxHeight: maxHeight,
  23215. updatable: updatable,
  23216. onReady: onReady
  23217. };
  23218. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23219. };
  23220. /**
  23221. * Creates a tube mesh.
  23222. * 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.
  23223. * Please consider using the same method from the MeshBuilder class instead.
  23224. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23225. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23226. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23227. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23228. * 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.
  23229. * It must return a radius value (positive float) :
  23230. * ```javascript
  23231. * var radiusFunction = function(i, distance) {
  23232. * // do things
  23233. * return radius; }
  23234. * ```
  23235. * 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
  23236. * 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
  23237. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23238. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23240. */
  23241. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23242. var options = {
  23243. path: path,
  23244. radius: radius,
  23245. tessellation: tessellation,
  23246. radiusFunction: radiusFunction,
  23247. arc: 1,
  23248. cap: cap,
  23249. updatable: updatable,
  23250. sideOrientation: sideOrientation,
  23251. instance: instance
  23252. };
  23253. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23254. };
  23255. /**
  23256. * Creates a polyhedron mesh.
  23257. * Please consider using the same method from the MeshBuilder class instead.
  23258. * 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
  23259. * to choose the wanted type.
  23260. * The parameter `size` (positive float, default 1) sets the polygon size.
  23261. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23262. * 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`.
  23263. * 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
  23264. * 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)`).
  23265. * 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
  23266. * 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.
  23267. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23268. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23269. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23270. */
  23271. Mesh.CreatePolyhedron = function (name, options, scene) {
  23272. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23273. };
  23274. /**
  23275. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23276. * Please consider using the same method from the MeshBuilder class instead.
  23277. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23278. * 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`).
  23279. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23280. * 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.
  23281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23282. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23284. */
  23285. Mesh.CreateIcoSphere = function (name, options, scene) {
  23286. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23287. };
  23288. /**
  23289. * Creates a decal mesh.
  23290. * Please consider using the same method from the MeshBuilder class instead.
  23291. * 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.
  23292. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23293. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23294. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23295. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23296. */
  23297. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23298. var options = {
  23299. position: position,
  23300. normal: normal,
  23301. size: size,
  23302. angle: angle
  23303. };
  23304. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23305. };
  23306. // Skeletons
  23307. /**
  23308. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23309. */
  23310. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23311. var source;
  23312. if (!this._sourcePositions) {
  23313. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23314. this._sourcePositions = new Float32Array(source);
  23315. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23316. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23317. }
  23318. }
  23319. return this._sourcePositions;
  23320. };
  23321. /**
  23322. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23323. */
  23324. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23325. var source;
  23326. if (!this._sourceNormals) {
  23327. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23328. this._sourceNormals = new Float32Array(source);
  23329. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23330. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23331. }
  23332. }
  23333. return this._sourceNormals;
  23334. };
  23335. /**
  23336. * Updates the vertex buffer by applying transformation from the bones.
  23337. * Returns the Mesh.
  23338. *
  23339. * @param {skeleton} skeleton to apply
  23340. */
  23341. Mesh.prototype.applySkeleton = function (skeleton) {
  23342. if (!this.geometry) {
  23343. return this;
  23344. }
  23345. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23346. return this;
  23347. }
  23348. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23349. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23350. return this;
  23351. }
  23352. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23353. return this;
  23354. }
  23355. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23356. return this;
  23357. }
  23358. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23359. return this;
  23360. }
  23361. if (!this._sourcePositions) {
  23362. var submeshes = this.subMeshes.slice();
  23363. this.setPositionsForCPUSkinning();
  23364. this.subMeshes = submeshes;
  23365. }
  23366. if (!this._sourceNormals) {
  23367. this.setNormalsForCPUSkinning();
  23368. }
  23369. // positionsData checks for not being Float32Array will only pass at most once
  23370. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23371. if (!(positionsData instanceof Float32Array)) {
  23372. positionsData = new Float32Array(positionsData);
  23373. }
  23374. // normalsData checks for not being Float32Array will only pass at most once
  23375. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23376. if (!(normalsData instanceof Float32Array)) {
  23377. normalsData = new Float32Array(normalsData);
  23378. }
  23379. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23380. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23381. var needExtras = this.numBoneInfluencers > 4;
  23382. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23383. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23384. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23385. var tempVector3 = BABYLON.Vector3.Zero();
  23386. var finalMatrix = new BABYLON.Matrix();
  23387. var tempMatrix = new BABYLON.Matrix();
  23388. var matWeightIdx = 0;
  23389. var inf;
  23390. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23391. var weight;
  23392. for (inf = 0; inf < 4; inf++) {
  23393. weight = matricesWeightsData[matWeightIdx + inf];
  23394. if (weight > 0) {
  23395. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23396. finalMatrix.addToSelf(tempMatrix);
  23397. }
  23398. else
  23399. break;
  23400. }
  23401. if (needExtras) {
  23402. for (inf = 0; inf < 4; inf++) {
  23403. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23404. if (weight > 0) {
  23405. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23406. finalMatrix.addToSelf(tempMatrix);
  23407. }
  23408. else
  23409. break;
  23410. }
  23411. }
  23412. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23413. tempVector3.toArray(positionsData, index);
  23414. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23415. tempVector3.toArray(normalsData, index);
  23416. finalMatrix.reset();
  23417. }
  23418. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23419. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23420. return this;
  23421. };
  23422. // Tools
  23423. /**
  23424. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23425. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23426. */
  23427. Mesh.MinMax = function (meshes) {
  23428. var minVector = null;
  23429. var maxVector = null;
  23430. meshes.forEach(function (mesh, index, array) {
  23431. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23432. if (!minVector) {
  23433. minVector = boundingBox.minimumWorld;
  23434. maxVector = boundingBox.maximumWorld;
  23435. }
  23436. else {
  23437. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23438. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23439. }
  23440. });
  23441. return {
  23442. min: minVector,
  23443. max: maxVector
  23444. };
  23445. };
  23446. /**
  23447. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23448. */
  23449. Mesh.Center = function (meshesOrMinMaxVector) {
  23450. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23451. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23452. };
  23453. /**
  23454. * Merge the array of meshes into a single mesh for performance reasons.
  23455. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23456. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23457. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23458. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23459. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23460. */
  23461. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23462. if (disposeSource === void 0) { disposeSource = true; }
  23463. var index;
  23464. if (!allow32BitsIndices) {
  23465. var totalVertices = 0;
  23466. // Counting vertices
  23467. for (index = 0; index < meshes.length; index++) {
  23468. if (meshes[index]) {
  23469. totalVertices += meshes[index].getTotalVertices();
  23470. if (totalVertices > 65536) {
  23471. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23472. return null;
  23473. }
  23474. }
  23475. }
  23476. }
  23477. // Merge
  23478. var vertexData;
  23479. var otherVertexData;
  23480. var indiceArray = new Array();
  23481. var source;
  23482. for (index = 0; index < meshes.length; index++) {
  23483. if (meshes[index]) {
  23484. meshes[index].computeWorldMatrix(true);
  23485. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23486. otherVertexData.transform(meshes[index].getWorldMatrix());
  23487. if (vertexData) {
  23488. vertexData.merge(otherVertexData);
  23489. }
  23490. else {
  23491. vertexData = otherVertexData;
  23492. source = meshes[index];
  23493. }
  23494. if (subdivideWithSubMeshes) {
  23495. indiceArray.push(meshes[index].getTotalIndices());
  23496. }
  23497. }
  23498. }
  23499. if (!meshSubclass) {
  23500. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23501. }
  23502. vertexData.applyToMesh(meshSubclass);
  23503. // Setting properties
  23504. meshSubclass.material = source.material;
  23505. meshSubclass.checkCollisions = source.checkCollisions;
  23506. // Cleaning
  23507. if (disposeSource) {
  23508. for (index = 0; index < meshes.length; index++) {
  23509. if (meshes[index]) {
  23510. meshes[index].dispose();
  23511. }
  23512. }
  23513. }
  23514. // Subdivide
  23515. if (subdivideWithSubMeshes) {
  23516. //-- Suppresions du submesh global
  23517. meshSubclass.releaseSubMeshes();
  23518. index = 0;
  23519. var offset = 0;
  23520. //-- aplique la subdivision en fonction du tableau d'indices
  23521. while (index < indiceArray.length) {
  23522. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23523. offset += indiceArray[index];
  23524. index++;
  23525. }
  23526. }
  23527. return meshSubclass;
  23528. };
  23529. // Consts
  23530. Mesh._FRONTSIDE = 0;
  23531. Mesh._BACKSIDE = 1;
  23532. Mesh._DOUBLESIDE = 2;
  23533. Mesh._DEFAULTSIDE = 0;
  23534. Mesh._NO_CAP = 0;
  23535. Mesh._CAP_START = 1;
  23536. Mesh._CAP_END = 2;
  23537. Mesh._CAP_ALL = 3;
  23538. return Mesh;
  23539. }(BABYLON.AbstractMesh));
  23540. BABYLON.Mesh = Mesh;
  23541. })(BABYLON || (BABYLON = {}));
  23542. //# sourceMappingURL=babylon.mesh.js.map
  23543. var BABYLON;
  23544. (function (BABYLON) {
  23545. var BaseSubMesh = (function () {
  23546. function BaseSubMesh() {
  23547. }
  23548. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23549. get: function () {
  23550. return this._materialEffect;
  23551. },
  23552. enumerable: true,
  23553. configurable: true
  23554. });
  23555. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23556. if (this._materialEffect === effect) {
  23557. if (!effect) {
  23558. this._materialDefines = undefined;
  23559. }
  23560. return;
  23561. }
  23562. this._materialDefines = defines;
  23563. this._materialEffect = effect;
  23564. };
  23565. return BaseSubMesh;
  23566. }());
  23567. BABYLON.BaseSubMesh = BaseSubMesh;
  23568. var SubMesh = (function (_super) {
  23569. __extends(SubMesh, _super);
  23570. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23571. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23572. var _this = _super.call(this) || this;
  23573. _this.materialIndex = materialIndex;
  23574. _this.verticesStart = verticesStart;
  23575. _this.verticesCount = verticesCount;
  23576. _this.indexStart = indexStart;
  23577. _this.indexCount = indexCount;
  23578. _this._renderId = 0;
  23579. _this._mesh = mesh;
  23580. _this._renderingMesh = renderingMesh || mesh;
  23581. mesh.subMeshes.push(_this);
  23582. _this._trianglePlanes = [];
  23583. _this._id = mesh.subMeshes.length - 1;
  23584. if (createBoundingBox) {
  23585. _this.refreshBoundingInfo();
  23586. mesh.computeWorldMatrix(true);
  23587. }
  23588. return _this;
  23589. }
  23590. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23591. get: function () {
  23592. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23593. },
  23594. enumerable: true,
  23595. configurable: true
  23596. });
  23597. /**
  23598. * Returns the submesh BoudingInfo object.
  23599. */
  23600. SubMesh.prototype.getBoundingInfo = function () {
  23601. if (this.IsGlobal) {
  23602. return this._mesh.getBoundingInfo();
  23603. }
  23604. return this._boundingInfo;
  23605. };
  23606. /**
  23607. * Sets the submesh BoundingInfo.
  23608. * Return the SubMesh.
  23609. */
  23610. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23611. this._boundingInfo = boundingInfo;
  23612. return this;
  23613. };
  23614. /**
  23615. * Returns the mesh of the current submesh.
  23616. */
  23617. SubMesh.prototype.getMesh = function () {
  23618. return this._mesh;
  23619. };
  23620. /**
  23621. * Returns the rendering mesh of the submesh.
  23622. */
  23623. SubMesh.prototype.getRenderingMesh = function () {
  23624. return this._renderingMesh;
  23625. };
  23626. /**
  23627. * Returns the submesh material.
  23628. */
  23629. SubMesh.prototype.getMaterial = function () {
  23630. var rootMaterial = this._renderingMesh.material;
  23631. if (rootMaterial && rootMaterial.getSubMaterial) {
  23632. var multiMaterial = rootMaterial;
  23633. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23634. if (this._currentMaterial !== effectiveMaterial) {
  23635. this._currentMaterial = effectiveMaterial;
  23636. this._materialDefines = undefined;
  23637. }
  23638. return effectiveMaterial;
  23639. }
  23640. if (!rootMaterial) {
  23641. return this._mesh.getScene().defaultMaterial;
  23642. }
  23643. return rootMaterial;
  23644. };
  23645. // Methods
  23646. /**
  23647. * Sets a new updated BoundingInfo object to the submesh.
  23648. * Returns the SubMesh.
  23649. */
  23650. SubMesh.prototype.refreshBoundingInfo = function () {
  23651. this._lastColliderWorldVertices = null;
  23652. if (this.IsGlobal) {
  23653. return;
  23654. }
  23655. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23656. if (!data) {
  23657. this._boundingInfo = this._mesh._boundingInfo;
  23658. return;
  23659. }
  23660. var indices = this._renderingMesh.getIndices();
  23661. var extend;
  23662. //is this the only submesh?
  23663. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23664. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23665. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23666. }
  23667. else {
  23668. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23669. }
  23670. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23671. return this;
  23672. };
  23673. SubMesh.prototype._checkCollision = function (collider) {
  23674. return this.getBoundingInfo()._checkCollision(collider);
  23675. };
  23676. /**
  23677. * Updates the submesh BoundingInfo.
  23678. * Returns the Submesh.
  23679. */
  23680. SubMesh.prototype.updateBoundingInfo = function (world) {
  23681. if (!this.getBoundingInfo()) {
  23682. this.refreshBoundingInfo();
  23683. }
  23684. this.getBoundingInfo().update(world);
  23685. return this;
  23686. };
  23687. /**
  23688. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23689. * Boolean returned.
  23690. */
  23691. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23692. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23693. };
  23694. /**
  23695. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23696. * Boolean returned.
  23697. */
  23698. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23699. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23700. };
  23701. /**
  23702. * Renders the submesh.
  23703. * Returns it.
  23704. */
  23705. SubMesh.prototype.render = function (enableAlphaMode) {
  23706. this._renderingMesh.render(this, enableAlphaMode);
  23707. return this;
  23708. };
  23709. /**
  23710. * Returns a new Index Buffer.
  23711. * Type returned : WebGLBuffer.
  23712. */
  23713. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23714. if (!this._linesIndexBuffer) {
  23715. var linesIndices = [];
  23716. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23717. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23718. }
  23719. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23720. this.linesIndexCount = linesIndices.length;
  23721. }
  23722. return this._linesIndexBuffer;
  23723. };
  23724. /**
  23725. * True is the passed Ray intersects the submesh bounding box.
  23726. * Boolean returned.
  23727. */
  23728. SubMesh.prototype.canIntersects = function (ray) {
  23729. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23730. };
  23731. /**
  23732. * Returns an object IntersectionInfo.
  23733. */
  23734. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23735. var intersectInfo = null;
  23736. // LineMesh first as it's also a Mesh...
  23737. if (this._mesh instanceof BABYLON.LinesMesh) {
  23738. var lineMesh = this._mesh;
  23739. // Line test
  23740. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23741. var p0 = positions[indices[index]];
  23742. var p1 = positions[indices[index + 1]];
  23743. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23744. if (length < 0) {
  23745. continue;
  23746. }
  23747. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23748. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23749. if (fastCheck) {
  23750. break;
  23751. }
  23752. }
  23753. }
  23754. }
  23755. else {
  23756. // Triangles test
  23757. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23758. var p0 = positions[indices[index]];
  23759. var p1 = positions[indices[index + 1]];
  23760. var p2 = positions[indices[index + 2]];
  23761. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  23762. if (currentIntersectInfo) {
  23763. if (currentIntersectInfo.distance < 0) {
  23764. continue;
  23765. }
  23766. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  23767. intersectInfo = currentIntersectInfo;
  23768. intersectInfo.faceId = index / 3;
  23769. if (fastCheck) {
  23770. break;
  23771. }
  23772. }
  23773. }
  23774. }
  23775. }
  23776. return intersectInfo;
  23777. };
  23778. SubMesh.prototype._rebuild = function () {
  23779. if (this._linesIndexBuffer) {
  23780. this._linesIndexBuffer = null;
  23781. }
  23782. };
  23783. // Clone
  23784. /**
  23785. * Creates a new Submesh from the passed Mesh.
  23786. */
  23787. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  23788. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  23789. if (!this.IsGlobal) {
  23790. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  23791. }
  23792. return result;
  23793. };
  23794. // Dispose
  23795. /**
  23796. * Disposes the Submesh.
  23797. * Returns nothing.
  23798. */
  23799. SubMesh.prototype.dispose = function () {
  23800. if (this._linesIndexBuffer) {
  23801. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  23802. this._linesIndexBuffer = null;
  23803. }
  23804. // Remove from mesh
  23805. var index = this._mesh.subMeshes.indexOf(this);
  23806. this._mesh.subMeshes.splice(index, 1);
  23807. };
  23808. // Statics
  23809. /**
  23810. * Creates a new Submesh from the passed parameters :
  23811. * - materialIndex (integer) : the index of the main mesh material.
  23812. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  23813. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  23814. * - mesh (Mesh) : the main mesh to create the submesh from.
  23815. * - renderingMesh (optional Mesh) : rendering mesh.
  23816. */
  23817. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  23818. var minVertexIndex = Number.MAX_VALUE;
  23819. var maxVertexIndex = -Number.MAX_VALUE;
  23820. renderingMesh = renderingMesh || mesh;
  23821. var indices = renderingMesh.getIndices();
  23822. for (var index = startIndex; index < startIndex + indexCount; index++) {
  23823. var vertexIndex = indices[index];
  23824. if (vertexIndex < minVertexIndex)
  23825. minVertexIndex = vertexIndex;
  23826. if (vertexIndex > maxVertexIndex)
  23827. maxVertexIndex = vertexIndex;
  23828. }
  23829. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23830. };
  23831. return SubMesh;
  23832. }(BaseSubMesh));
  23833. BABYLON.SubMesh = SubMesh;
  23834. })(BABYLON || (BABYLON = {}));
  23835. //# sourceMappingURL=babylon.subMesh.js.map
  23836. var BABYLON;
  23837. (function (BABYLON) {
  23838. var EffectFallbacks = (function () {
  23839. function EffectFallbacks() {
  23840. this._defines = {};
  23841. this._currentRank = 32;
  23842. this._maxRank = -1;
  23843. }
  23844. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23845. if (!this._defines[rank]) {
  23846. if (rank < this._currentRank) {
  23847. this._currentRank = rank;
  23848. }
  23849. if (rank > this._maxRank) {
  23850. this._maxRank = rank;
  23851. }
  23852. this._defines[rank] = new Array();
  23853. }
  23854. this._defines[rank].push(define);
  23855. };
  23856. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23857. this._meshRank = rank;
  23858. this._mesh = mesh;
  23859. if (rank < this._currentRank) {
  23860. this._currentRank = rank;
  23861. }
  23862. if (rank > this._maxRank) {
  23863. this._maxRank = rank;
  23864. }
  23865. };
  23866. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23867. get: function () {
  23868. return this._currentRank <= this._maxRank;
  23869. },
  23870. enumerable: true,
  23871. configurable: true
  23872. });
  23873. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23874. // First we try to switch to CPU skinning
  23875. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  23876. this._mesh.computeBonesUsingShaders = false;
  23877. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23878. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23879. var scene = this._mesh.getScene();
  23880. for (var index = 0; index < scene.meshes.length; index++) {
  23881. var otherMesh = scene.meshes[index];
  23882. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  23883. otherMesh.computeBonesUsingShaders = false;
  23884. }
  23885. }
  23886. }
  23887. else {
  23888. var currentFallbacks = this._defines[this._currentRank];
  23889. if (currentFallbacks) {
  23890. for (var index = 0; index < currentFallbacks.length; index++) {
  23891. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23892. }
  23893. }
  23894. this._currentRank++;
  23895. }
  23896. return currentDefines;
  23897. };
  23898. return EffectFallbacks;
  23899. }());
  23900. BABYLON.EffectFallbacks = EffectFallbacks;
  23901. var EffectCreationOptions = (function () {
  23902. function EffectCreationOptions() {
  23903. }
  23904. return EffectCreationOptions;
  23905. }());
  23906. BABYLON.EffectCreationOptions = EffectCreationOptions;
  23907. var Effect = (function () {
  23908. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23909. var _this = this;
  23910. this.uniqueId = 0;
  23911. this.onCompileObservable = new BABYLON.Observable();
  23912. this.onErrorObservable = new BABYLON.Observable();
  23913. this.onBindObservable = new BABYLON.Observable();
  23914. this._uniformBuffersNames = {};
  23915. this._isReady = false;
  23916. this._compilationError = "";
  23917. this.name = baseName;
  23918. if (attributesNamesOrOptions.attributes) {
  23919. var options = attributesNamesOrOptions;
  23920. this._engine = uniformsNamesOrEngine;
  23921. this._attributesNames = options.attributes;
  23922. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  23923. this._samplers = options.samplers;
  23924. this.defines = options.defines;
  23925. this.onError = options.onError;
  23926. this.onCompiled = options.onCompiled;
  23927. this._fallbacks = options.fallbacks;
  23928. this._indexParameters = options.indexParameters;
  23929. if (options.uniformBuffersNames) {
  23930. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  23931. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  23932. }
  23933. }
  23934. }
  23935. else {
  23936. this._engine = engine;
  23937. this.defines = defines;
  23938. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  23939. this._samplers = samplers;
  23940. this._attributesNames = attributesNamesOrOptions;
  23941. this.onError = onError;
  23942. this.onCompiled = onCompiled;
  23943. this._indexParameters = indexParameters;
  23944. this._fallbacks = fallbacks;
  23945. }
  23946. this.uniqueId = Effect._uniqueIdSeed++;
  23947. var vertexSource;
  23948. var fragmentSource;
  23949. if (baseName.vertexElement) {
  23950. vertexSource = document.getElementById(baseName.vertexElement);
  23951. if (!vertexSource) {
  23952. vertexSource = baseName.vertexElement;
  23953. }
  23954. }
  23955. else {
  23956. vertexSource = baseName.vertex || baseName;
  23957. }
  23958. if (baseName.fragmentElement) {
  23959. fragmentSource = document.getElementById(baseName.fragmentElement);
  23960. if (!fragmentSource) {
  23961. fragmentSource = baseName.fragmentElement;
  23962. }
  23963. }
  23964. else {
  23965. fragmentSource = baseName.fragment || baseName;
  23966. }
  23967. this._loadVertexShader(vertexSource, function (vertexCode) {
  23968. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23969. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  23970. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23971. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23972. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  23973. if (baseName) {
  23974. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  23975. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  23976. }
  23977. else {
  23978. _this._vertexSourceCode = migratedVertexCode;
  23979. _this._fragmentSourceCode = migratedFragmentCode;
  23980. }
  23981. _this._prepareEffect();
  23982. });
  23983. });
  23984. });
  23985. });
  23986. });
  23987. });
  23988. }
  23989. Object.defineProperty(Effect.prototype, "key", {
  23990. get: function () {
  23991. return this._key;
  23992. },
  23993. enumerable: true,
  23994. configurable: true
  23995. });
  23996. // Properties
  23997. Effect.prototype.isReady = function () {
  23998. return this._isReady;
  23999. };
  24000. Effect.prototype.getEngine = function () {
  24001. return this._engine;
  24002. };
  24003. Effect.prototype.getProgram = function () {
  24004. return this._program;
  24005. };
  24006. Effect.prototype.getAttributesNames = function () {
  24007. return this._attributesNames;
  24008. };
  24009. Effect.prototype.getAttributeLocation = function (index) {
  24010. return this._attributes[index];
  24011. };
  24012. Effect.prototype.getAttributeLocationByName = function (name) {
  24013. var index = this._attributesNames.indexOf(name);
  24014. return this._attributes[index];
  24015. };
  24016. Effect.prototype.getAttributesCount = function () {
  24017. return this._attributes.length;
  24018. };
  24019. Effect.prototype.getUniformIndex = function (uniformName) {
  24020. return this._uniformsNames.indexOf(uniformName);
  24021. };
  24022. Effect.prototype.getUniform = function (uniformName) {
  24023. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24024. };
  24025. Effect.prototype.getSamplers = function () {
  24026. return this._samplers;
  24027. };
  24028. Effect.prototype.getCompilationError = function () {
  24029. return this._compilationError;
  24030. };
  24031. // Methods
  24032. Effect.prototype.executeWhenCompiled = function (func) {
  24033. if (this.isReady()) {
  24034. func(this);
  24035. return;
  24036. }
  24037. this.onCompileObservable.add(function (effect) {
  24038. func(effect);
  24039. });
  24040. };
  24041. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24042. // DOM element ?
  24043. if (vertex instanceof HTMLElement) {
  24044. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24045. callback(vertexCode);
  24046. return;
  24047. }
  24048. // Base64 encoded ?
  24049. if (vertex.substr(0, 7) === "base64:") {
  24050. var vertexBinary = window.atob(vertex.substr(7));
  24051. callback(vertexBinary);
  24052. return;
  24053. }
  24054. // Is in local store ?
  24055. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24056. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24057. return;
  24058. }
  24059. var vertexShaderUrl;
  24060. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24061. vertexShaderUrl = vertex;
  24062. }
  24063. else {
  24064. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24065. }
  24066. // Vertex shader
  24067. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24068. };
  24069. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24070. // DOM element ?
  24071. if (fragment instanceof HTMLElement) {
  24072. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24073. callback(fragmentCode);
  24074. return;
  24075. }
  24076. // Base64 encoded ?
  24077. if (fragment.substr(0, 7) === "base64:") {
  24078. var fragmentBinary = window.atob(fragment.substr(7));
  24079. callback(fragmentBinary);
  24080. return;
  24081. }
  24082. // Is in local store ?
  24083. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24084. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24085. return;
  24086. }
  24087. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24088. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24089. return;
  24090. }
  24091. var fragmentShaderUrl;
  24092. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24093. fragmentShaderUrl = fragment;
  24094. }
  24095. else {
  24096. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24097. }
  24098. // Fragment shader
  24099. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24100. };
  24101. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24102. // Rebuild shaders source code
  24103. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24104. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24105. vertexCode = prefix + vertexCode;
  24106. fragmentCode = prefix + fragmentCode;
  24107. // Number lines of shaders source code
  24108. var i = 2;
  24109. var regex = /\n/gm;
  24110. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24111. i = 2;
  24112. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24113. // Dump shaders name and formatted source code
  24114. if (this.name.vertexElement) {
  24115. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24116. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24117. }
  24118. else if (this.name.vertex) {
  24119. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24120. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24121. }
  24122. else {
  24123. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24124. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24125. }
  24126. };
  24127. ;
  24128. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24129. var preparedSourceCode = this._processPrecision(sourceCode);
  24130. if (this._engine.webGLVersion == 1) {
  24131. callback(preparedSourceCode);
  24132. return;
  24133. }
  24134. // Already converted
  24135. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24136. callback(preparedSourceCode.replace("#version 300 es", ""));
  24137. return;
  24138. }
  24139. // Remove extensions
  24140. // #extension GL_OES_standard_derivatives : enable
  24141. // #extension GL_EXT_shader_texture_lod : enable
  24142. // #extension GL_EXT_frag_depth : enable
  24143. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  24144. var result = preparedSourceCode.replace(regex, "");
  24145. // Migrate to GLSL v300
  24146. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24147. result = result.replace(/attribute[ \t]/g, "in ");
  24148. result = result.replace(/[ \t]attribute/g, " in");
  24149. if (isFragment) {
  24150. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24151. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24152. result = result.replace(/texture2D\(/g, "texture(");
  24153. result = result.replace(/textureCube\(/g, "texture(");
  24154. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24155. result = result.replace(/gl_FragColor/g, "glFragColor");
  24156. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  24157. }
  24158. callback(result);
  24159. };
  24160. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24161. var _this = this;
  24162. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24163. var match = regex.exec(sourceCode);
  24164. var returnValue = new String(sourceCode);
  24165. while (match != null) {
  24166. var includeFile = match[1];
  24167. // Uniform declaration
  24168. if (includeFile.indexOf("__decl__") !== -1) {
  24169. includeFile = includeFile.replace(/__decl__/, "");
  24170. if (this._engine.webGLVersion != 1) {
  24171. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24172. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24173. }
  24174. includeFile = includeFile + "Declaration";
  24175. }
  24176. if (Effect.IncludesShadersStore[includeFile]) {
  24177. // Substitution
  24178. var includeContent = Effect.IncludesShadersStore[includeFile];
  24179. if (match[2]) {
  24180. var splits = match[3].split(",");
  24181. for (var index = 0; index < splits.length; index += 2) {
  24182. var source = new RegExp(splits[index], "g");
  24183. var dest = splits[index + 1];
  24184. includeContent = includeContent.replace(source, dest);
  24185. }
  24186. }
  24187. if (match[4]) {
  24188. var indexString = match[5];
  24189. if (indexString.indexOf("..") !== -1) {
  24190. var indexSplits = indexString.split("..");
  24191. var minIndex = parseInt(indexSplits[0]);
  24192. var maxIndex = parseInt(indexSplits[1]);
  24193. var sourceIncludeContent = includeContent.slice(0);
  24194. includeContent = "";
  24195. if (isNaN(maxIndex)) {
  24196. maxIndex = this._indexParameters[indexSplits[1]];
  24197. }
  24198. for (var i = minIndex; i < maxIndex; i++) {
  24199. if (this._engine.webGLVersion === 1) {
  24200. // Ubo replacement
  24201. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24202. return p1 + "{X}";
  24203. });
  24204. }
  24205. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24206. }
  24207. }
  24208. else {
  24209. if (this._engine.webGLVersion === 1) {
  24210. // Ubo replacement
  24211. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24212. return p1 + "{X}";
  24213. });
  24214. }
  24215. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24216. }
  24217. }
  24218. // Replace
  24219. returnValue = returnValue.replace(match[0], includeContent);
  24220. }
  24221. else {
  24222. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24223. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24224. Effect.IncludesShadersStore[includeFile] = fileContent;
  24225. _this._processIncludes(returnValue, callback);
  24226. });
  24227. return;
  24228. }
  24229. match = regex.exec(sourceCode);
  24230. }
  24231. callback(returnValue);
  24232. };
  24233. Effect.prototype._processPrecision = function (source) {
  24234. if (source.indexOf("precision highp float") === -1) {
  24235. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24236. source = "precision mediump float;\n" + source;
  24237. }
  24238. else {
  24239. source = "precision highp float;\n" + source;
  24240. }
  24241. }
  24242. else {
  24243. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24244. source = source.replace("precision highp float", "precision mediump float");
  24245. }
  24246. }
  24247. return source;
  24248. };
  24249. Effect.prototype._prepareEffect = function () {
  24250. var attributesNames = this._attributesNames;
  24251. var defines = this.defines;
  24252. var fallbacks = this._fallbacks;
  24253. this._valueCache = {};
  24254. try {
  24255. var engine = this._engine;
  24256. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24257. if (engine.webGLVersion > 1) {
  24258. for (var name in this._uniformBuffersNames) {
  24259. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24260. }
  24261. }
  24262. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24263. this._attributes = engine.getAttributes(this._program, attributesNames);
  24264. var index;
  24265. for (index = 0; index < this._samplers.length; index++) {
  24266. var sampler = this.getUniform(this._samplers[index]);
  24267. if (sampler == null) {
  24268. this._samplers.splice(index, 1);
  24269. index--;
  24270. }
  24271. }
  24272. engine.bindSamplers(this);
  24273. this._compilationError = "";
  24274. this._isReady = true;
  24275. if (this.onCompiled) {
  24276. this.onCompiled(this);
  24277. }
  24278. this.onCompileObservable.notifyObservers(this);
  24279. this.onCompileObservable.clear();
  24280. }
  24281. catch (e) {
  24282. this._compilationError = e.message;
  24283. // Let's go through fallbacks then
  24284. BABYLON.Tools.Error("Unable to compile effect:");
  24285. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24286. return " " + uniform;
  24287. }));
  24288. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24289. return " " + attribute;
  24290. }));
  24291. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24292. BABYLON.Tools.Error("Error: " + this._compilationError);
  24293. if (fallbacks && fallbacks.isMoreFallbacks) {
  24294. BABYLON.Tools.Error("Trying next fallback.");
  24295. this.defines = fallbacks.reduce(this.defines);
  24296. this._prepareEffect();
  24297. }
  24298. else {
  24299. if (this.onError) {
  24300. this.onError(this, this._compilationError);
  24301. }
  24302. this.onErrorObservable.notifyObservers(this);
  24303. this.onErrorObservable.clear();
  24304. }
  24305. }
  24306. };
  24307. Object.defineProperty(Effect.prototype, "isSupported", {
  24308. get: function () {
  24309. return this._compilationError === "";
  24310. },
  24311. enumerable: true,
  24312. configurable: true
  24313. });
  24314. Effect.prototype._bindTexture = function (channel, texture) {
  24315. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24316. };
  24317. Effect.prototype.setTexture = function (channel, texture) {
  24318. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24319. };
  24320. Effect.prototype.setTextureArray = function (channel, textures) {
  24321. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24322. var initialPos = this._samplers.indexOf(channel);
  24323. for (var index = 1; index < textures.length; index++) {
  24324. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24325. }
  24326. }
  24327. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24328. };
  24329. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24330. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24331. };
  24332. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24333. var cache = this._valueCache[uniformName];
  24334. var flag = matrix.updateFlag;
  24335. if (cache !== undefined && cache === flag) {
  24336. return false;
  24337. }
  24338. this._valueCache[uniformName] = flag;
  24339. return true;
  24340. };
  24341. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24342. var cache = this._valueCache[uniformName];
  24343. if (!cache) {
  24344. cache = [x, y];
  24345. this._valueCache[uniformName] = cache;
  24346. return true;
  24347. }
  24348. var changed = false;
  24349. if (cache[0] !== x) {
  24350. cache[0] = x;
  24351. changed = true;
  24352. }
  24353. if (cache[1] !== y) {
  24354. cache[1] = y;
  24355. changed = true;
  24356. }
  24357. return changed;
  24358. };
  24359. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24360. var cache = this._valueCache[uniformName];
  24361. if (!cache) {
  24362. cache = [x, y, z];
  24363. this._valueCache[uniformName] = cache;
  24364. return true;
  24365. }
  24366. var changed = false;
  24367. if (cache[0] !== x) {
  24368. cache[0] = x;
  24369. changed = true;
  24370. }
  24371. if (cache[1] !== y) {
  24372. cache[1] = y;
  24373. changed = true;
  24374. }
  24375. if (cache[2] !== z) {
  24376. cache[2] = z;
  24377. changed = true;
  24378. }
  24379. return changed;
  24380. };
  24381. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24382. var cache = this._valueCache[uniformName];
  24383. if (!cache) {
  24384. cache = [x, y, z, w];
  24385. this._valueCache[uniformName] = cache;
  24386. return true;
  24387. }
  24388. var changed = false;
  24389. if (cache[0] !== x) {
  24390. cache[0] = x;
  24391. changed = true;
  24392. }
  24393. if (cache[1] !== y) {
  24394. cache[1] = y;
  24395. changed = true;
  24396. }
  24397. if (cache[2] !== z) {
  24398. cache[2] = z;
  24399. changed = true;
  24400. }
  24401. if (cache[3] !== w) {
  24402. cache[3] = w;
  24403. changed = true;
  24404. }
  24405. return changed;
  24406. };
  24407. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24408. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24409. return;
  24410. }
  24411. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24412. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24413. };
  24414. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24415. this._engine.bindUniformBlock(this._program, blockName, index);
  24416. };
  24417. Effect.prototype.setIntArray = function (uniformName, array) {
  24418. this._valueCache[uniformName] = null;
  24419. this._engine.setIntArray(this.getUniform(uniformName), array);
  24420. return this;
  24421. };
  24422. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24423. this._valueCache[uniformName] = null;
  24424. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24425. return this;
  24426. };
  24427. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24428. this._valueCache[uniformName] = null;
  24429. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24430. return this;
  24431. };
  24432. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24433. this._valueCache[uniformName] = null;
  24434. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24435. return this;
  24436. };
  24437. Effect.prototype.setFloatArray = function (uniformName, array) {
  24438. this._valueCache[uniformName] = null;
  24439. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24440. return this;
  24441. };
  24442. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24443. this._valueCache[uniformName] = null;
  24444. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24445. return this;
  24446. };
  24447. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24448. this._valueCache[uniformName] = null;
  24449. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24450. return this;
  24451. };
  24452. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24453. this._valueCache[uniformName] = null;
  24454. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24455. return this;
  24456. };
  24457. Effect.prototype.setArray = function (uniformName, array) {
  24458. this._valueCache[uniformName] = null;
  24459. this._engine.setArray(this.getUniform(uniformName), array);
  24460. return this;
  24461. };
  24462. Effect.prototype.setArray2 = function (uniformName, array) {
  24463. this._valueCache[uniformName] = null;
  24464. this._engine.setArray2(this.getUniform(uniformName), array);
  24465. return this;
  24466. };
  24467. Effect.prototype.setArray3 = function (uniformName, array) {
  24468. this._valueCache[uniformName] = null;
  24469. this._engine.setArray3(this.getUniform(uniformName), array);
  24470. return this;
  24471. };
  24472. Effect.prototype.setArray4 = function (uniformName, array) {
  24473. this._valueCache[uniformName] = null;
  24474. this._engine.setArray4(this.getUniform(uniformName), array);
  24475. return this;
  24476. };
  24477. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24478. if (!matrices) {
  24479. return;
  24480. }
  24481. this._valueCache[uniformName] = null;
  24482. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24483. return this;
  24484. };
  24485. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24486. if (this._cacheMatrix(uniformName, matrix)) {
  24487. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24488. }
  24489. return this;
  24490. };
  24491. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24492. this._valueCache[uniformName] = null;
  24493. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24494. return this;
  24495. };
  24496. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24497. this._valueCache[uniformName] = null;
  24498. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24499. return this;
  24500. };
  24501. Effect.prototype.setFloat = function (uniformName, value) {
  24502. var cache = this._valueCache[uniformName];
  24503. if (cache !== undefined && cache === value)
  24504. return this;
  24505. this._valueCache[uniformName] = value;
  24506. this._engine.setFloat(this.getUniform(uniformName), value);
  24507. return this;
  24508. };
  24509. Effect.prototype.setBool = function (uniformName, bool) {
  24510. var cache = this._valueCache[uniformName];
  24511. if (cache !== undefined && cache === bool)
  24512. return this;
  24513. this._valueCache[uniformName] = bool;
  24514. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24515. return this;
  24516. };
  24517. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24518. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24519. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24520. }
  24521. return this;
  24522. };
  24523. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24524. if (this._cacheFloat2(uniformName, x, y)) {
  24525. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24526. }
  24527. return this;
  24528. };
  24529. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24530. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24531. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24532. }
  24533. return this;
  24534. };
  24535. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24536. if (this._cacheFloat3(uniformName, x, y, z)) {
  24537. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24538. }
  24539. return this;
  24540. };
  24541. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24542. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24543. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24544. }
  24545. return this;
  24546. };
  24547. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24548. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24549. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24550. }
  24551. return this;
  24552. };
  24553. Effect.prototype.setColor3 = function (uniformName, color3) {
  24554. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24555. this._engine.setColor3(this.getUniform(uniformName), color3);
  24556. }
  24557. return this;
  24558. };
  24559. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24560. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24561. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24562. }
  24563. return this;
  24564. };
  24565. Effect.ResetCache = function () {
  24566. Effect._baseCache = {};
  24567. };
  24568. Effect._uniqueIdSeed = 0;
  24569. Effect._baseCache = {};
  24570. // Statics
  24571. Effect.ShadersStore = {};
  24572. Effect.IncludesShadersStore = {};
  24573. return Effect;
  24574. }());
  24575. BABYLON.Effect = Effect;
  24576. })(BABYLON || (BABYLON = {}));
  24577. //# sourceMappingURL=babylon.effect.js.map
  24578. var BABYLON;
  24579. (function (BABYLON) {
  24580. var MaterialHelper = (function () {
  24581. function MaterialHelper() {
  24582. }
  24583. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24584. defines._needUVs = true;
  24585. defines[key] = true;
  24586. if (texture.getTextureMatrix().isIdentity(true)) {
  24587. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24588. if (texture.coordinatesIndex === 0) {
  24589. defines["MAINUV1"] = true;
  24590. }
  24591. else {
  24592. defines["MAINUV2"] = true;
  24593. }
  24594. }
  24595. else {
  24596. defines[key + "DIRECTUV"] = 0;
  24597. }
  24598. };
  24599. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24600. var matrix = texture.getTextureMatrix();
  24601. if (!matrix.isIdentity(true)) {
  24602. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24603. }
  24604. };
  24605. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24606. if (defines._areMiscDirty) {
  24607. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24608. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24609. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24610. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24611. }
  24612. };
  24613. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24614. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24615. var changed = false;
  24616. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24617. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24618. changed = true;
  24619. }
  24620. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24621. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24622. changed = true;
  24623. }
  24624. if (defines["INSTANCES"] !== useInstances) {
  24625. defines["INSTANCES"] = useInstances;
  24626. changed = true;
  24627. }
  24628. if (changed) {
  24629. defines.markAsUnprocessed();
  24630. }
  24631. };
  24632. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24633. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24634. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24635. return false;
  24636. }
  24637. defines._normals = defines._needNormals;
  24638. defines._uvs = defines._needUVs;
  24639. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24640. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24641. defines["TANGENT"] = true;
  24642. }
  24643. if (defines._needUVs) {
  24644. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24645. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24646. }
  24647. else {
  24648. defines["UV1"] = false;
  24649. defines["UV2"] = false;
  24650. }
  24651. if (useVertexColor) {
  24652. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24653. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24654. }
  24655. if (useBones) {
  24656. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24657. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24658. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24659. }
  24660. else {
  24661. defines["NUM_BONE_INFLUENCERS"] = 0;
  24662. defines["BonesPerMesh"] = 0;
  24663. }
  24664. }
  24665. if (useMorphTargets) {
  24666. if (mesh.morphTargetManager) {
  24667. var manager = mesh.morphTargetManager;
  24668. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24669. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24670. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24671. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24672. }
  24673. else {
  24674. defines["MORPHTARGETS_TANGENT"] = false;
  24675. defines["MORPHTARGETS_NORMAL"] = false;
  24676. defines["MORPHTARGETS"] = false;
  24677. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24678. }
  24679. }
  24680. return true;
  24681. };
  24682. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24683. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24684. if (disableLighting === void 0) { disableLighting = false; }
  24685. if (!defines._areLightsDirty) {
  24686. return defines._needNormals;
  24687. }
  24688. var lightIndex = 0;
  24689. var needNormals = false;
  24690. var needRebuild = false;
  24691. var lightmapMode = false;
  24692. var shadowEnabled = false;
  24693. var specularEnabled = false;
  24694. if (scene.lightsEnabled && !disableLighting) {
  24695. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24696. var light = _a[_i];
  24697. needNormals = true;
  24698. if (defines["LIGHT" + lightIndex] === undefined) {
  24699. needRebuild = true;
  24700. }
  24701. defines["LIGHT" + lightIndex] = true;
  24702. defines["SPOTLIGHT" + lightIndex] = false;
  24703. defines["HEMILIGHT" + lightIndex] = false;
  24704. defines["POINTLIGHT" + lightIndex] = false;
  24705. defines["DIRLIGHT" + lightIndex] = false;
  24706. var type;
  24707. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24708. type = "SPOTLIGHT" + lightIndex;
  24709. }
  24710. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24711. type = "HEMILIGHT" + lightIndex;
  24712. }
  24713. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24714. type = "POINTLIGHT" + lightIndex;
  24715. }
  24716. else {
  24717. type = "DIRLIGHT" + lightIndex;
  24718. }
  24719. defines[type] = true;
  24720. // Specular
  24721. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24722. specularEnabled = true;
  24723. }
  24724. // Shadows
  24725. defines["SHADOW" + lightIndex] = false;
  24726. defines["SHADOWPCF" + lightIndex] = false;
  24727. defines["SHADOWESM" + lightIndex] = false;
  24728. defines["SHADOWCUBE" + lightIndex] = false;
  24729. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24730. var shadowGenerator = light.getShadowGenerator();
  24731. if (shadowGenerator) {
  24732. shadowEnabled = true;
  24733. shadowGenerator.prepareDefines(defines, lightIndex);
  24734. }
  24735. }
  24736. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24737. lightmapMode = true;
  24738. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24739. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  24740. }
  24741. else {
  24742. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  24743. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  24744. }
  24745. lightIndex++;
  24746. if (lightIndex === maxSimultaneousLights)
  24747. break;
  24748. }
  24749. }
  24750. defines["SPECULARTERM"] = specularEnabled;
  24751. defines["SHADOWS"] = shadowEnabled;
  24752. // Resetting all other lights if any
  24753. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  24754. if (defines["LIGHT" + index] !== undefined) {
  24755. defines["LIGHT" + index] = false;
  24756. defines["HEMILIGHT" + lightIndex] = false;
  24757. defines["POINTLIGHT" + lightIndex] = false;
  24758. defines["DIRLIGHT" + lightIndex] = false;
  24759. defines["SPOTLIGHT" + lightIndex] = false;
  24760. defines["SHADOW" + lightIndex] = false;
  24761. }
  24762. }
  24763. var caps = scene.getEngine().getCaps();
  24764. if (defines["SHADOWFLOAT"] === undefined) {
  24765. needRebuild = true;
  24766. }
  24767. defines["SHADOWFLOAT"] = shadowEnabled &&
  24768. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  24769. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  24770. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  24771. if (needRebuild) {
  24772. defines.rebuild();
  24773. }
  24774. return needNormals;
  24775. };
  24776. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  24777. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24778. var uniformsList, uniformBuffersList, samplersList, defines;
  24779. if (uniformsListOrOptions.uniformsNames) {
  24780. var options = uniformsListOrOptions;
  24781. uniformsList = options.uniformsNames;
  24782. uniformBuffersList = options.uniformBuffersNames;
  24783. samplersList = options.samplers;
  24784. defines = options.defines;
  24785. maxSimultaneousLights = options.maxSimultaneousLights;
  24786. }
  24787. else {
  24788. uniformsList = uniformsListOrOptions;
  24789. }
  24790. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24791. if (!defines["LIGHT" + lightIndex]) {
  24792. break;
  24793. }
  24794. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  24795. if (uniformBuffersList) {
  24796. uniformBuffersList.push("Light" + lightIndex);
  24797. }
  24798. samplersList.push("shadowSampler" + lightIndex);
  24799. }
  24800. if (defines["NUM_MORPH_INFLUENCERS"]) {
  24801. uniformsList.push("morphTargetInfluences");
  24802. }
  24803. };
  24804. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24805. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24806. if (!defines["SHADOWS"]) {
  24807. return;
  24808. }
  24809. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24810. if (!defines["LIGHT" + lightIndex]) {
  24811. break;
  24812. }
  24813. if (lightIndex > 0) {
  24814. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24815. }
  24816. if (defines["SHADOW" + lightIndex]) {
  24817. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24818. }
  24819. if (defines["SHADOWPCF" + lightIndex]) {
  24820. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24821. }
  24822. if (defines["SHADOWESM" + lightIndex]) {
  24823. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  24824. }
  24825. }
  24826. };
  24827. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  24828. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  24829. if (influencers > 0) {
  24830. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  24831. var manager = mesh.morphTargetManager;
  24832. var normal = manager.supportsNormals && defines["NORMAL"];
  24833. var tangent = manager.supportsTangents && defines["TANGENT"];
  24834. for (var index = 0; index < influencers; index++) {
  24835. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  24836. if (normal) {
  24837. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  24838. }
  24839. if (tangent) {
  24840. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  24841. }
  24842. if (attribs.length > maxAttributesCount) {
  24843. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  24844. }
  24845. }
  24846. }
  24847. };
  24848. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24849. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24850. fallbacks.addCPUSkinningFallback(0, mesh);
  24851. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24852. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24853. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24854. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24855. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24856. }
  24857. }
  24858. };
  24859. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24860. if (defines["INSTANCES"]) {
  24861. attribs.push("world0");
  24862. attribs.push("world1");
  24863. attribs.push("world2");
  24864. attribs.push("world3");
  24865. }
  24866. };
  24867. // Bindings
  24868. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  24869. if (light.shadowEnabled && mesh.receiveShadows) {
  24870. var shadowGenerator = light.getShadowGenerator();
  24871. if (shadowGenerator) {
  24872. shadowGenerator.bindShadowLight(lightIndex, effect);
  24873. }
  24874. }
  24875. };
  24876. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24877. light.transferToEffect(effect, lightIndex + "");
  24878. };
  24879. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  24880. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24881. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  24882. var lightIndex = 0;
  24883. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24884. var light = _a[_i];
  24885. var scaledIntensity = light.getScaledIntensity();
  24886. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  24887. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24888. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  24889. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  24890. if (defines["SPECULARTERM"]) {
  24891. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  24892. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  24893. }
  24894. // Shadows
  24895. if (scene.shadowsEnabled) {
  24896. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  24897. }
  24898. light._uniformBuffer.update();
  24899. lightIndex++;
  24900. if (lightIndex === maxSimultaneousLights)
  24901. break;
  24902. }
  24903. };
  24904. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24905. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24906. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24907. effect.setColor3("vFogColor", scene.fogColor);
  24908. }
  24909. };
  24910. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24911. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24912. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  24913. if (matrices) {
  24914. effect.setMatrices("mBones", matrices);
  24915. }
  24916. }
  24917. };
  24918. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  24919. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  24920. return;
  24921. }
  24922. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  24923. };
  24924. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24925. if (defines["LOGARITHMICDEPTH"]) {
  24926. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24927. }
  24928. };
  24929. MaterialHelper.BindClipPlane = function (effect, scene) {
  24930. if (scene.clipPlane) {
  24931. var clipPlane = scene.clipPlane;
  24932. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24933. }
  24934. };
  24935. return MaterialHelper;
  24936. }());
  24937. BABYLON.MaterialHelper = MaterialHelper;
  24938. })(BABYLON || (BABYLON = {}));
  24939. //# sourceMappingURL=babylon.materialHelper.js.map
  24940. var BABYLON;
  24941. (function (BABYLON) {
  24942. var MaterialDefines = (function () {
  24943. function MaterialDefines() {
  24944. this._isDirty = true;
  24945. this._areLightsDirty = true;
  24946. this._areAttributesDirty = true;
  24947. this._areTexturesDirty = true;
  24948. this._areFresnelDirty = true;
  24949. this._areMiscDirty = true;
  24950. this._areImageProcessingDirty = true;
  24951. this._normals = false;
  24952. this._uvs = false;
  24953. this._needNormals = false;
  24954. this._needUVs = false;
  24955. }
  24956. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  24957. get: function () {
  24958. return this._isDirty;
  24959. },
  24960. enumerable: true,
  24961. configurable: true
  24962. });
  24963. MaterialDefines.prototype.markAsProcessed = function () {
  24964. this._isDirty = false;
  24965. this._areAttributesDirty = false;
  24966. this._areTexturesDirty = false;
  24967. this._areFresnelDirty = false;
  24968. this._areLightsDirty = false;
  24969. this._areMiscDirty = false;
  24970. this._areImageProcessingDirty = false;
  24971. };
  24972. MaterialDefines.prototype.markAsUnprocessed = function () {
  24973. this._isDirty = true;
  24974. };
  24975. MaterialDefines.prototype.markAllAsDirty = function () {
  24976. this._areTexturesDirty = true;
  24977. this._areAttributesDirty = true;
  24978. this._areLightsDirty = true;
  24979. this._areFresnelDirty = true;
  24980. this._areMiscDirty = true;
  24981. this._areImageProcessingDirty = true;
  24982. this._isDirty = true;
  24983. };
  24984. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  24985. this._areImageProcessingDirty = true;
  24986. this._isDirty = true;
  24987. };
  24988. MaterialDefines.prototype.markAsLightDirty = function () {
  24989. this._areLightsDirty = true;
  24990. this._isDirty = true;
  24991. };
  24992. MaterialDefines.prototype.markAsAttributesDirty = function () {
  24993. this._areAttributesDirty = true;
  24994. this._isDirty = true;
  24995. };
  24996. MaterialDefines.prototype.markAsTexturesDirty = function () {
  24997. this._areTexturesDirty = true;
  24998. this._isDirty = true;
  24999. };
  25000. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25001. this._areFresnelDirty = true;
  25002. this._isDirty = true;
  25003. };
  25004. MaterialDefines.prototype.markAsMiscDirty = function () {
  25005. this._areMiscDirty = true;
  25006. this._isDirty = true;
  25007. };
  25008. MaterialDefines.prototype.rebuild = function () {
  25009. if (this._keys) {
  25010. delete this._keys;
  25011. }
  25012. this._keys = [];
  25013. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25014. var key = _a[_i];
  25015. if (key[0] === "_") {
  25016. continue;
  25017. }
  25018. this._keys.push(key);
  25019. }
  25020. };
  25021. MaterialDefines.prototype.isEqual = function (other) {
  25022. if (this._keys.length !== other._keys.length) {
  25023. return false;
  25024. }
  25025. for (var index = 0; index < this._keys.length; index++) {
  25026. var prop = this._keys[index];
  25027. if (this[prop] !== other[prop]) {
  25028. return false;
  25029. }
  25030. }
  25031. return true;
  25032. };
  25033. MaterialDefines.prototype.cloneTo = function (other) {
  25034. if (this._keys.length !== other._keys.length) {
  25035. other._keys = this._keys.slice(0);
  25036. }
  25037. for (var index = 0; index < this._keys.length; index++) {
  25038. var prop = this._keys[index];
  25039. other[prop] = this[prop];
  25040. }
  25041. };
  25042. MaterialDefines.prototype.reset = function () {
  25043. for (var index = 0; index < this._keys.length; index++) {
  25044. var prop = this._keys[index];
  25045. if (typeof (this[prop]) === "number") {
  25046. this[prop] = 0;
  25047. }
  25048. else {
  25049. this[prop] = false;
  25050. }
  25051. }
  25052. };
  25053. MaterialDefines.prototype.toString = function () {
  25054. var result = "";
  25055. for (var index = 0; index < this._keys.length; index++) {
  25056. var prop = this._keys[index];
  25057. var value = this[prop];
  25058. if (typeof (value) === "number") {
  25059. result += "#define " + prop + " " + this[prop] + "\n";
  25060. }
  25061. else if (value) {
  25062. result += "#define " + prop + "\n";
  25063. }
  25064. }
  25065. return result;
  25066. };
  25067. return MaterialDefines;
  25068. }());
  25069. BABYLON.MaterialDefines = MaterialDefines;
  25070. var Material = (function () {
  25071. function Material(name, scene, doNotAdd) {
  25072. this.checkReadyOnEveryCall = false;
  25073. this.checkReadyOnlyOnce = false;
  25074. this.state = "";
  25075. this.alpha = 1.0;
  25076. this._backFaceCulling = true;
  25077. this.doNotSerialize = false;
  25078. this.storeEffectOnSubMeshes = false;
  25079. /**
  25080. * An event triggered when the material is disposed.
  25081. * @type {BABYLON.Observable}
  25082. */
  25083. this.onDisposeObservable = new BABYLON.Observable();
  25084. /**
  25085. * An event triggered when the material is bound.
  25086. * @type {BABYLON.Observable}
  25087. */
  25088. this.onBindObservable = new BABYLON.Observable();
  25089. /**
  25090. * An event triggered when the material is unbound.
  25091. * @type {BABYLON.Observable}
  25092. */
  25093. this.onUnBindObservable = new BABYLON.Observable();
  25094. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25095. this.disableDepthWrite = false;
  25096. this._fogEnabled = true;
  25097. this.pointSize = 1.0;
  25098. this.zOffset = 0;
  25099. this._wasPreviouslyReady = false;
  25100. this._fillMode = Material.TriangleFillMode;
  25101. this.name = name;
  25102. this.id = name || BABYLON.Tools.RandomId();
  25103. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25104. if (this._scene.useRightHandedSystem) {
  25105. this.sideOrientation = Material.ClockWiseSideOrientation;
  25106. }
  25107. else {
  25108. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25109. }
  25110. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25111. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  25112. if (!doNotAdd) {
  25113. this._scene.materials.push(this);
  25114. }
  25115. }
  25116. Object.defineProperty(Material, "TriangleFillMode", {
  25117. get: function () {
  25118. return Material._TriangleFillMode;
  25119. },
  25120. enumerable: true,
  25121. configurable: true
  25122. });
  25123. Object.defineProperty(Material, "WireFrameFillMode", {
  25124. get: function () {
  25125. return Material._WireFrameFillMode;
  25126. },
  25127. enumerable: true,
  25128. configurable: true
  25129. });
  25130. Object.defineProperty(Material, "PointFillMode", {
  25131. get: function () {
  25132. return Material._PointFillMode;
  25133. },
  25134. enumerable: true,
  25135. configurable: true
  25136. });
  25137. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25138. get: function () {
  25139. return Material._ClockWiseSideOrientation;
  25140. },
  25141. enumerable: true,
  25142. configurable: true
  25143. });
  25144. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25145. get: function () {
  25146. return Material._CounterClockWiseSideOrientation;
  25147. },
  25148. enumerable: true,
  25149. configurable: true
  25150. });
  25151. Object.defineProperty(Material, "TextureDirtyFlag", {
  25152. get: function () {
  25153. return Material._TextureDirtyFlag;
  25154. },
  25155. enumerable: true,
  25156. configurable: true
  25157. });
  25158. Object.defineProperty(Material, "LightDirtyFlag", {
  25159. get: function () {
  25160. return Material._LightDirtyFlag;
  25161. },
  25162. enumerable: true,
  25163. configurable: true
  25164. });
  25165. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25166. get: function () {
  25167. return Material._FresnelDirtyFlag;
  25168. },
  25169. enumerable: true,
  25170. configurable: true
  25171. });
  25172. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25173. get: function () {
  25174. return Material._AttributesDirtyFlag;
  25175. },
  25176. enumerable: true,
  25177. configurable: true
  25178. });
  25179. Object.defineProperty(Material, "MiscDirtyFlag", {
  25180. get: function () {
  25181. return Material._MiscDirtyFlag;
  25182. },
  25183. enumerable: true,
  25184. configurable: true
  25185. });
  25186. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25187. get: function () {
  25188. return this._backFaceCulling;
  25189. },
  25190. set: function (value) {
  25191. if (this._backFaceCulling === value) {
  25192. return;
  25193. }
  25194. this._backFaceCulling = value;
  25195. this.markAsDirty(Material.TextureDirtyFlag);
  25196. },
  25197. enumerable: true,
  25198. configurable: true
  25199. });
  25200. Object.defineProperty(Material.prototype, "onDispose", {
  25201. set: function (callback) {
  25202. if (this._onDisposeObserver) {
  25203. this.onDisposeObservable.remove(this._onDisposeObserver);
  25204. }
  25205. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25206. },
  25207. enumerable: true,
  25208. configurable: true
  25209. });
  25210. Object.defineProperty(Material.prototype, "onBind", {
  25211. set: function (callback) {
  25212. if (this._onBindObserver) {
  25213. this.onBindObservable.remove(this._onBindObserver);
  25214. }
  25215. this._onBindObserver = this.onBindObservable.add(callback);
  25216. },
  25217. enumerable: true,
  25218. configurable: true
  25219. });
  25220. Object.defineProperty(Material.prototype, "fogEnabled", {
  25221. get: function () {
  25222. return this._fogEnabled;
  25223. },
  25224. set: function (value) {
  25225. if (this._fogEnabled === value) {
  25226. return;
  25227. }
  25228. this._fogEnabled = value;
  25229. this.markAsDirty(Material.MiscDirtyFlag);
  25230. },
  25231. enumerable: true,
  25232. configurable: true
  25233. });
  25234. Object.defineProperty(Material.prototype, "wireframe", {
  25235. get: function () {
  25236. return this._fillMode === Material.WireFrameFillMode;
  25237. },
  25238. set: function (value) {
  25239. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25240. },
  25241. enumerable: true,
  25242. configurable: true
  25243. });
  25244. Object.defineProperty(Material.prototype, "pointsCloud", {
  25245. get: function () {
  25246. return this._fillMode === Material.PointFillMode;
  25247. },
  25248. set: function (value) {
  25249. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25250. },
  25251. enumerable: true,
  25252. configurable: true
  25253. });
  25254. Object.defineProperty(Material.prototype, "fillMode", {
  25255. get: function () {
  25256. return this._fillMode;
  25257. },
  25258. set: function (value) {
  25259. if (this._fillMode === value) {
  25260. return;
  25261. }
  25262. this._fillMode = value;
  25263. this.markAsDirty(Material.MiscDirtyFlag);
  25264. },
  25265. enumerable: true,
  25266. configurable: true
  25267. });
  25268. /**
  25269. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25270. * subclasses should override adding information pertainent to themselves
  25271. */
  25272. Material.prototype.toString = function (fullDetails) {
  25273. var ret = "Name: " + this.name;
  25274. if (fullDetails) {
  25275. }
  25276. return ret;
  25277. };
  25278. /**
  25279. * Child classes can use it to update shaders
  25280. */
  25281. Material.prototype.getClassName = function () {
  25282. return "Material";
  25283. };
  25284. Object.defineProperty(Material.prototype, "isFrozen", {
  25285. get: function () {
  25286. return this.checkReadyOnlyOnce;
  25287. },
  25288. enumerable: true,
  25289. configurable: true
  25290. });
  25291. Material.prototype.freeze = function () {
  25292. this.checkReadyOnlyOnce = true;
  25293. };
  25294. Material.prototype.unfreeze = function () {
  25295. this.checkReadyOnlyOnce = false;
  25296. };
  25297. Material.prototype.isReady = function (mesh, useInstances) {
  25298. return true;
  25299. };
  25300. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25301. return false;
  25302. };
  25303. Material.prototype.getEffect = function () {
  25304. return this._effect;
  25305. };
  25306. Material.prototype.getScene = function () {
  25307. return this._scene;
  25308. };
  25309. Material.prototype.needAlphaBlending = function () {
  25310. return (this.alpha < 1.0);
  25311. };
  25312. Material.prototype.needAlphaTesting = function () {
  25313. return false;
  25314. };
  25315. Material.prototype.getAlphaTestTexture = function () {
  25316. return null;
  25317. };
  25318. Material.prototype.markDirty = function () {
  25319. this._wasPreviouslyReady = false;
  25320. };
  25321. Material.prototype._preBind = function (effect) {
  25322. var engine = this._scene.getEngine();
  25323. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25324. engine.enableEffect(effect ? effect : this._effect);
  25325. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25326. };
  25327. Material.prototype.bind = function (world, mesh) {
  25328. };
  25329. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25330. };
  25331. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25332. };
  25333. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25334. sceneUbo.bindToEffect(effect, "Scene");
  25335. };
  25336. Material.prototype.bindView = function (effect) {
  25337. if (!this._useUBO) {
  25338. effect.setMatrix("view", this.getScene().getViewMatrix());
  25339. }
  25340. else {
  25341. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25342. }
  25343. };
  25344. Material.prototype.bindViewProjection = function (effect) {
  25345. if (!this._useUBO) {
  25346. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25347. }
  25348. else {
  25349. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25350. }
  25351. };
  25352. Material.prototype._afterBind = function (mesh) {
  25353. this._scene._cachedMaterial = this;
  25354. if (mesh) {
  25355. this._scene._cachedVisibility = mesh.visibility;
  25356. }
  25357. else {
  25358. this._scene._cachedVisibility = 1;
  25359. }
  25360. this.onBindObservable.notifyObservers(mesh);
  25361. if (this.disableDepthWrite) {
  25362. var engine = this._scene.getEngine();
  25363. this._cachedDepthWriteState = engine.getDepthWrite();
  25364. engine.setDepthWrite(false);
  25365. }
  25366. };
  25367. Material.prototype.unbind = function () {
  25368. this.onUnBindObservable.notifyObservers(this);
  25369. if (this.disableDepthWrite) {
  25370. var engine = this._scene.getEngine();
  25371. engine.setDepthWrite(this._cachedDepthWriteState);
  25372. }
  25373. };
  25374. Material.prototype.getActiveTextures = function () {
  25375. return [];
  25376. };
  25377. Material.prototype.hasTexture = function (texture) {
  25378. return false;
  25379. };
  25380. Material.prototype.clone = function (name) {
  25381. return null;
  25382. };
  25383. Material.prototype.getBindedMeshes = function () {
  25384. var result = new Array();
  25385. for (var index = 0; index < this._scene.meshes.length; index++) {
  25386. var mesh = this._scene.meshes[index];
  25387. if (mesh.material === this) {
  25388. result.push(mesh);
  25389. }
  25390. }
  25391. return result;
  25392. };
  25393. /**
  25394. * Force shader compilation including textures ready check
  25395. */
  25396. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25397. var _this = this;
  25398. var subMesh = new BABYLON.BaseSubMesh();
  25399. var scene = this.getScene();
  25400. var engine = scene.getEngine();
  25401. var checkReady = function () {
  25402. if (!_this._scene || !_this._scene.getEngine()) {
  25403. return;
  25404. }
  25405. if (subMesh._materialDefines) {
  25406. subMesh._materialDefines._renderId = -1;
  25407. }
  25408. var alphaTestState = engine.getAlphaTesting();
  25409. var clipPlaneState = scene.clipPlane;
  25410. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25411. if (options && options.clipPlane) {
  25412. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25413. }
  25414. if (_this.storeEffectOnSubMeshes) {
  25415. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25416. if (onCompiled) {
  25417. onCompiled(_this);
  25418. }
  25419. }
  25420. else {
  25421. setTimeout(checkReady, 16);
  25422. }
  25423. }
  25424. else {
  25425. if (_this.isReady(mesh)) {
  25426. if (onCompiled) {
  25427. onCompiled(_this);
  25428. }
  25429. }
  25430. else {
  25431. setTimeout(checkReady, 16);
  25432. }
  25433. }
  25434. engine.setAlphaTesting(alphaTestState);
  25435. if (options && options.clipPlane) {
  25436. scene.clipPlane = clipPlaneState;
  25437. }
  25438. };
  25439. checkReady();
  25440. };
  25441. Material.prototype.markAsDirty = function (flag) {
  25442. if (flag & Material.TextureDirtyFlag) {
  25443. this._markAllSubMeshesAsTexturesDirty();
  25444. }
  25445. if (flag & Material.LightDirtyFlag) {
  25446. this._markAllSubMeshesAsLightsDirty();
  25447. }
  25448. if (flag & Material.FresnelDirtyFlag) {
  25449. this._markAllSubMeshesAsFresnelDirty();
  25450. }
  25451. if (flag & Material.AttributesDirtyFlag) {
  25452. this._markAllSubMeshesAsAttributesDirty();
  25453. }
  25454. if (flag & Material.MiscDirtyFlag) {
  25455. this._markAllSubMeshesAsMiscDirty();
  25456. }
  25457. this.getScene().resetCachedMaterial();
  25458. };
  25459. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25460. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25461. var mesh = _a[_i];
  25462. if (!mesh.subMeshes) {
  25463. continue;
  25464. }
  25465. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25466. var subMesh = _c[_b];
  25467. if (subMesh.getMaterial() !== this) {
  25468. continue;
  25469. }
  25470. if (!subMesh._materialDefines) {
  25471. continue;
  25472. }
  25473. func(subMesh._materialDefines);
  25474. }
  25475. }
  25476. };
  25477. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25478. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25479. };
  25480. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25481. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25482. };
  25483. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25484. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25485. };
  25486. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25487. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25488. };
  25489. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25490. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25491. };
  25492. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25493. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25494. };
  25495. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25496. // Animations
  25497. this.getScene().stopAnimation(this);
  25498. // Remove from scene
  25499. var index = this._scene.materials.indexOf(this);
  25500. if (index >= 0) {
  25501. this._scene.materials.splice(index, 1);
  25502. }
  25503. // Remove from meshes
  25504. for (index = 0; index < this._scene.meshes.length; index++) {
  25505. var mesh = this._scene.meshes[index];
  25506. if (mesh.material === this) {
  25507. mesh.material = null;
  25508. if (mesh.geometry) {
  25509. var geometry = mesh.geometry;
  25510. if (this.storeEffectOnSubMeshes) {
  25511. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25512. var subMesh = _a[_i];
  25513. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25514. }
  25515. }
  25516. else {
  25517. geometry._releaseVertexArrayObject(this._effect);
  25518. }
  25519. }
  25520. }
  25521. }
  25522. this._uniformBuffer.dispose();
  25523. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25524. if (forceDisposeEffect && this._effect) {
  25525. if (this.storeEffectOnSubMeshes) {
  25526. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25527. var subMesh = _c[_b];
  25528. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25529. }
  25530. }
  25531. else {
  25532. this._scene.getEngine()._releaseEffect(this._effect);
  25533. }
  25534. this._effect = null;
  25535. }
  25536. // Callback
  25537. this.onDisposeObservable.notifyObservers(this);
  25538. this.onDisposeObservable.clear();
  25539. this.onBindObservable.clear();
  25540. this.onUnBindObservable.clear();
  25541. };
  25542. Material.prototype.serialize = function () {
  25543. return BABYLON.SerializationHelper.Serialize(this);
  25544. };
  25545. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25546. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25547. multiMaterial.id = parsedMultiMaterial.id;
  25548. if (BABYLON.Tags) {
  25549. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25550. }
  25551. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25552. var subMatId = parsedMultiMaterial.materials[matIndex];
  25553. if (subMatId) {
  25554. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25555. }
  25556. else {
  25557. multiMaterial.subMaterials.push(null);
  25558. }
  25559. }
  25560. return multiMaterial;
  25561. };
  25562. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25563. if (!parsedMaterial.customType) {
  25564. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25565. }
  25566. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25567. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25568. if (!BABYLON.LegacyPBRMaterial) {
  25569. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25570. return;
  25571. }
  25572. }
  25573. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25574. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25575. ;
  25576. };
  25577. Material._TriangleFillMode = 0;
  25578. Material._WireFrameFillMode = 1;
  25579. Material._PointFillMode = 2;
  25580. Material._ClockWiseSideOrientation = 0;
  25581. Material._CounterClockWiseSideOrientation = 1;
  25582. Material._TextureDirtyFlag = 1;
  25583. Material._LightDirtyFlag = 2;
  25584. Material._FresnelDirtyFlag = 4;
  25585. Material._AttributesDirtyFlag = 8;
  25586. Material._MiscDirtyFlag = 16;
  25587. __decorate([
  25588. BABYLON.serialize()
  25589. ], Material.prototype, "id", void 0);
  25590. __decorate([
  25591. BABYLON.serialize()
  25592. ], Material.prototype, "name", void 0);
  25593. __decorate([
  25594. BABYLON.serialize()
  25595. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25596. __decorate([
  25597. BABYLON.serialize()
  25598. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25599. __decorate([
  25600. BABYLON.serialize()
  25601. ], Material.prototype, "state", void 0);
  25602. __decorate([
  25603. BABYLON.serialize()
  25604. ], Material.prototype, "alpha", void 0);
  25605. __decorate([
  25606. BABYLON.serialize("backFaceCulling")
  25607. ], Material.prototype, "_backFaceCulling", void 0);
  25608. __decorate([
  25609. BABYLON.serialize()
  25610. ], Material.prototype, "sideOrientation", void 0);
  25611. __decorate([
  25612. BABYLON.serialize()
  25613. ], Material.prototype, "alphaMode", void 0);
  25614. __decorate([
  25615. BABYLON.serialize()
  25616. ], Material.prototype, "disableDepthWrite", void 0);
  25617. __decorate([
  25618. BABYLON.serialize("fogEnabled")
  25619. ], Material.prototype, "_fogEnabled", void 0);
  25620. __decorate([
  25621. BABYLON.serialize()
  25622. ], Material.prototype, "pointSize", void 0);
  25623. __decorate([
  25624. BABYLON.serialize()
  25625. ], Material.prototype, "zOffset", void 0);
  25626. __decorate([
  25627. BABYLON.serialize()
  25628. ], Material.prototype, "wireframe", null);
  25629. __decorate([
  25630. BABYLON.serialize()
  25631. ], Material.prototype, "pointsCloud", null);
  25632. __decorate([
  25633. BABYLON.serialize()
  25634. ], Material.prototype, "fillMode", null);
  25635. return Material;
  25636. }());
  25637. BABYLON.Material = Material;
  25638. })(BABYLON || (BABYLON = {}));
  25639. //# sourceMappingURL=babylon.material.js.map
  25640. var BABYLON;
  25641. (function (BABYLON) {
  25642. var UniformBuffer = (function () {
  25643. /**
  25644. * Uniform buffer objects.
  25645. *
  25646. * Handles blocks of uniform on the GPU.
  25647. *
  25648. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25649. *
  25650. * For more information, please refer to :
  25651. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25652. */
  25653. function UniformBuffer(engine, data, dynamic) {
  25654. this._engine = engine;
  25655. this._noUBO = engine.webGLVersion === 1;
  25656. this._dynamic = dynamic;
  25657. this._data = data || [];
  25658. this._uniformLocations = {};
  25659. this._uniformSizes = {};
  25660. this._uniformLocationPointer = 0;
  25661. this._needSync = false;
  25662. if (this._noUBO) {
  25663. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25664. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25665. this.updateFloat = this._updateFloatForEffect;
  25666. this.updateFloat2 = this._updateFloat2ForEffect;
  25667. this.updateFloat3 = this._updateFloat3ForEffect;
  25668. this.updateFloat4 = this._updateFloat4ForEffect;
  25669. this.updateMatrix = this._updateMatrixForEffect;
  25670. this.updateVector3 = this._updateVector3ForEffect;
  25671. this.updateVector4 = this._updateVector4ForEffect;
  25672. this.updateColor3 = this._updateColor3ForEffect;
  25673. this.updateColor4 = this._updateColor4ForEffect;
  25674. }
  25675. else {
  25676. this._engine._uniformBuffers.push(this);
  25677. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25678. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25679. this.updateFloat = this._updateFloatForUniform;
  25680. this.updateFloat2 = this._updateFloat2ForUniform;
  25681. this.updateFloat3 = this._updateFloat3ForUniform;
  25682. this.updateFloat4 = this._updateFloat4ForUniform;
  25683. this.updateMatrix = this._updateMatrixForUniform;
  25684. this.updateVector3 = this._updateVector3ForUniform;
  25685. this.updateVector4 = this._updateVector4ForUniform;
  25686. this.updateColor3 = this._updateColor3ForUniform;
  25687. this.updateColor4 = this._updateColor4ForUniform;
  25688. }
  25689. }
  25690. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25691. // Properties
  25692. /**
  25693. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25694. * or just falling back on setUniformXXX calls.
  25695. */
  25696. get: function () {
  25697. return !this._noUBO;
  25698. },
  25699. enumerable: true,
  25700. configurable: true
  25701. });
  25702. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25703. /**
  25704. * Indicates if the WebGL underlying uniform buffer is in sync
  25705. * with the javascript cache data.
  25706. */
  25707. get: function () {
  25708. return !this._needSync;
  25709. },
  25710. enumerable: true,
  25711. configurable: true
  25712. });
  25713. /**
  25714. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25715. * Also, a dynamic UniformBuffer will disable cache verification and always
  25716. * update the underlying WebGL uniform buffer to the GPU.
  25717. */
  25718. UniformBuffer.prototype.isDynamic = function () {
  25719. return this._dynamic;
  25720. };
  25721. /**
  25722. * The data cache on JS side.
  25723. */
  25724. UniformBuffer.prototype.getData = function () {
  25725. return this._bufferData;
  25726. };
  25727. /**
  25728. * The underlying WebGL Uniform buffer.
  25729. */
  25730. UniformBuffer.prototype.getBuffer = function () {
  25731. return this._buffer;
  25732. };
  25733. /**
  25734. * std140 layout specifies how to align data within an UBO structure.
  25735. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25736. * for specs.
  25737. */
  25738. UniformBuffer.prototype._fillAlignment = function (size) {
  25739. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  25740. // and 4x4 matrices
  25741. // TODO : change if other types are used
  25742. var alignment;
  25743. if (size <= 2) {
  25744. alignment = size;
  25745. }
  25746. else {
  25747. alignment = 4;
  25748. }
  25749. if ((this._uniformLocationPointer % alignment) !== 0) {
  25750. var oldPointer = this._uniformLocationPointer;
  25751. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  25752. var diff = this._uniformLocationPointer - oldPointer;
  25753. for (var i = 0; i < diff; i++) {
  25754. this._data.push(0);
  25755. }
  25756. }
  25757. };
  25758. /**
  25759. * Adds an uniform in the buffer.
  25760. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  25761. * for the layout to be correct !
  25762. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25763. * @param {number|number[]} size Data size, or data directly.
  25764. */
  25765. UniformBuffer.prototype.addUniform = function (name, size) {
  25766. if (this._noUBO) {
  25767. return;
  25768. }
  25769. if (this._uniformLocations[name] !== undefined) {
  25770. // Already existing uniform
  25771. return;
  25772. }
  25773. // This function must be called in the order of the shader layout !
  25774. // size can be the size of the uniform, or data directly
  25775. var data;
  25776. if (size instanceof Array) {
  25777. data = size;
  25778. size = data.length;
  25779. }
  25780. else {
  25781. size = size;
  25782. data = [];
  25783. // Fill with zeros
  25784. for (var i = 0; i < size; i++) {
  25785. data.push(0);
  25786. }
  25787. }
  25788. this._fillAlignment(size);
  25789. this._uniformSizes[name] = size;
  25790. this._uniformLocations[name] = this._uniformLocationPointer;
  25791. this._uniformLocationPointer += size;
  25792. for (var i = 0; i < size; i++) {
  25793. this._data.push(data[i]);
  25794. }
  25795. this._needSync = true;
  25796. };
  25797. /**
  25798. * Wrapper for addUniform.
  25799. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25800. * @param {Matrix} mat A 4x4 matrix.
  25801. */
  25802. UniformBuffer.prototype.addMatrix = function (name, mat) {
  25803. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  25804. };
  25805. /**
  25806. * Wrapper for addUniform.
  25807. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25808. * @param {number} x
  25809. * @param {number} y
  25810. */
  25811. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  25812. var temp = [x, y];
  25813. this.addUniform(name, temp);
  25814. };
  25815. /**
  25816. * Wrapper for addUniform.
  25817. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25818. * @param {number} x
  25819. * @param {number} y
  25820. * @param {number} z
  25821. */
  25822. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  25823. var temp = [x, y, z];
  25824. this.addUniform(name, temp);
  25825. };
  25826. /**
  25827. * Wrapper for addUniform.
  25828. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25829. * @param {Color3} color
  25830. */
  25831. UniformBuffer.prototype.addColor3 = function (name, color) {
  25832. var temp = [];
  25833. color.toArray(temp);
  25834. this.addUniform(name, temp);
  25835. };
  25836. /**
  25837. * Wrapper for addUniform.
  25838. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25839. * @param {Color3} color
  25840. * @param {number} alpha
  25841. */
  25842. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  25843. var temp = [];
  25844. color.toArray(temp);
  25845. temp.push(alpha);
  25846. this.addUniform(name, temp);
  25847. };
  25848. /**
  25849. * Wrapper for addUniform.
  25850. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25851. * @param {Vector3} vector
  25852. */
  25853. UniformBuffer.prototype.addVector3 = function (name, vector) {
  25854. var temp = [];
  25855. vector.toArray(temp);
  25856. this.addUniform(name, temp);
  25857. };
  25858. /**
  25859. * Wrapper for addUniform.
  25860. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25861. */
  25862. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  25863. this.addUniform(name, 12);
  25864. };
  25865. /**
  25866. * Wrapper for addUniform.
  25867. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25868. */
  25869. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  25870. this.addUniform(name, 8);
  25871. };
  25872. /**
  25873. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  25874. */
  25875. UniformBuffer.prototype.create = function () {
  25876. if (this._noUBO) {
  25877. return;
  25878. }
  25879. if (this._buffer) {
  25880. return; // nothing to do
  25881. }
  25882. // See spec, alignment must be filled as a vec4
  25883. this._fillAlignment(4);
  25884. this._bufferData = new Float32Array(this._data);
  25885. this._rebuild();
  25886. this._needSync = true;
  25887. };
  25888. UniformBuffer.prototype._rebuild = function () {
  25889. if (this._noUBO) {
  25890. return;
  25891. }
  25892. if (this._dynamic) {
  25893. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  25894. }
  25895. else {
  25896. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  25897. }
  25898. };
  25899. /**
  25900. * Updates the WebGL Uniform Buffer on the GPU.
  25901. * If the `dynamic` flag is set to true, no cache comparison is done.
  25902. * Otherwise, the buffer will be updated only if the cache differs.
  25903. */
  25904. UniformBuffer.prototype.update = function () {
  25905. if (!this._buffer) {
  25906. this.create();
  25907. return;
  25908. }
  25909. if (!this._dynamic && !this._needSync) {
  25910. return;
  25911. }
  25912. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  25913. this._needSync = false;
  25914. };
  25915. /**
  25916. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  25917. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25918. * @param {number[]|Float32Array} data Flattened data
  25919. * @param {number} size Size of the data.
  25920. */
  25921. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  25922. var location = this._uniformLocations[uniformName];
  25923. if (location === undefined) {
  25924. if (this._buffer) {
  25925. // Cannot add an uniform if the buffer is already created
  25926. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  25927. return;
  25928. }
  25929. this.addUniform(uniformName, size);
  25930. location = this._uniformLocations[uniformName];
  25931. }
  25932. if (!this._buffer) {
  25933. this.create();
  25934. }
  25935. if (!this._dynamic) {
  25936. // Cache for static uniform buffers
  25937. var changed = false;
  25938. for (var i = 0; i < size; i++) {
  25939. if (this._bufferData[location + i] !== data[i]) {
  25940. changed = true;
  25941. this._bufferData[location + i] = data[i];
  25942. }
  25943. }
  25944. this._needSync = this._needSync || changed;
  25945. }
  25946. else {
  25947. // No cache for dynamic
  25948. for (var i = 0; i < size; i++) {
  25949. this._bufferData[location + i] = data[i];
  25950. }
  25951. }
  25952. };
  25953. // Update methods
  25954. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  25955. // To match std140, matrix must be realigned
  25956. for (var i = 0; i < 3; i++) {
  25957. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  25958. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  25959. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  25960. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  25961. }
  25962. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  25963. };
  25964. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  25965. this._currentEffect.setMatrix3x3(name, matrix);
  25966. };
  25967. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  25968. this._currentEffect.setMatrix2x2(name, matrix);
  25969. };
  25970. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  25971. // To match std140, matrix must be realigned
  25972. for (var i = 0; i < 2; i++) {
  25973. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  25974. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  25975. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  25976. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  25977. }
  25978. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  25979. };
  25980. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  25981. this._currentEffect.setFloat(name, x);
  25982. };
  25983. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  25984. UniformBuffer._tempBuffer[0] = x;
  25985. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  25986. };
  25987. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  25988. if (suffix === void 0) { suffix = ""; }
  25989. this._currentEffect.setFloat2(name + suffix, x, y);
  25990. };
  25991. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  25992. if (suffix === void 0) { suffix = ""; }
  25993. UniformBuffer._tempBuffer[0] = x;
  25994. UniformBuffer._tempBuffer[1] = y;
  25995. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  25996. };
  25997. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  25998. if (suffix === void 0) { suffix = ""; }
  25999. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26000. };
  26001. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26002. if (suffix === void 0) { suffix = ""; }
  26003. UniformBuffer._tempBuffer[0] = x;
  26004. UniformBuffer._tempBuffer[1] = y;
  26005. UniformBuffer._tempBuffer[2] = z;
  26006. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26007. };
  26008. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26009. if (suffix === void 0) { suffix = ""; }
  26010. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26011. };
  26012. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26013. if (suffix === void 0) { suffix = ""; }
  26014. UniformBuffer._tempBuffer[0] = x;
  26015. UniformBuffer._tempBuffer[1] = y;
  26016. UniformBuffer._tempBuffer[2] = z;
  26017. UniformBuffer._tempBuffer[3] = w;
  26018. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26019. };
  26020. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26021. this._currentEffect.setMatrix(name, mat);
  26022. };
  26023. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26024. this.updateUniform(name, mat.toArray(), 16);
  26025. };
  26026. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26027. this._currentEffect.setVector3(name, vector);
  26028. };
  26029. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26030. vector.toArray(UniformBuffer._tempBuffer);
  26031. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26032. };
  26033. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26034. this._currentEffect.setVector4(name, vector);
  26035. };
  26036. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26037. vector.toArray(UniformBuffer._tempBuffer);
  26038. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26039. };
  26040. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26041. if (suffix === void 0) { suffix = ""; }
  26042. this._currentEffect.setColor3(name + suffix, color);
  26043. };
  26044. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26045. if (suffix === void 0) { suffix = ""; }
  26046. color.toArray(UniformBuffer._tempBuffer);
  26047. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26048. };
  26049. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26050. if (suffix === void 0) { suffix = ""; }
  26051. this._currentEffect.setColor4(name + suffix, color, alpha);
  26052. };
  26053. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26054. if (suffix === void 0) { suffix = ""; }
  26055. color.toArray(UniformBuffer._tempBuffer);
  26056. UniformBuffer._tempBuffer[3] = alpha;
  26057. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26058. };
  26059. /**
  26060. * Sets a sampler uniform on the effect.
  26061. * @param {string} name Name of the sampler.
  26062. * @param {Texture} texture
  26063. */
  26064. UniformBuffer.prototype.setTexture = function (name, texture) {
  26065. this._currentEffect.setTexture(name, texture);
  26066. };
  26067. /**
  26068. * Directly updates the value of the uniform in the cache AND on the GPU.
  26069. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26070. * @param {number[]|Float32Array} data Flattened data
  26071. */
  26072. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26073. this.updateUniform(uniformName, data, data.length);
  26074. this.update();
  26075. };
  26076. /**
  26077. * Binds this uniform buffer to an effect.
  26078. * @param {Effect} effect
  26079. * @param {string} name Name of the uniform block in the shader.
  26080. */
  26081. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26082. this._currentEffect = effect;
  26083. if (this._noUBO) {
  26084. return;
  26085. }
  26086. effect.bindUniformBuffer(this._buffer, name);
  26087. };
  26088. /**
  26089. * Disposes the uniform buffer.
  26090. */
  26091. UniformBuffer.prototype.dispose = function () {
  26092. if (this._noUBO) {
  26093. return;
  26094. }
  26095. var index = this._engine._uniformBuffers.indexOf(this);
  26096. if (index !== -1) {
  26097. this._engine._uniformBuffers.splice(index, 1);
  26098. }
  26099. if (!this._buffer) {
  26100. return;
  26101. }
  26102. if (this._engine._releaseBuffer(this._buffer)) {
  26103. this._buffer = null;
  26104. }
  26105. };
  26106. // Pool for avoiding memory leaks
  26107. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26108. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26109. return UniformBuffer;
  26110. }());
  26111. BABYLON.UniformBuffer = UniformBuffer;
  26112. })(BABYLON || (BABYLON = {}));
  26113. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26114. var BABYLON;
  26115. (function (BABYLON) {
  26116. var PushMaterial = (function (_super) {
  26117. __extends(PushMaterial, _super);
  26118. function PushMaterial(name, scene) {
  26119. var _this = _super.call(this, name, scene) || this;
  26120. _this.storeEffectOnSubMeshes = true;
  26121. return _this;
  26122. }
  26123. PushMaterial.prototype.getEffect = function () {
  26124. return this._activeEffect;
  26125. };
  26126. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26127. if (!mesh) {
  26128. return false;
  26129. }
  26130. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26131. return true;
  26132. }
  26133. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26134. };
  26135. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26136. this._activeEffect.setMatrix("world", world);
  26137. };
  26138. PushMaterial.prototype.bind = function (world, mesh) {
  26139. if (!mesh) {
  26140. return;
  26141. }
  26142. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26143. };
  26144. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26145. _super.prototype._afterBind.call(this, mesh);
  26146. this.getScene()._cachedEffect = effect;
  26147. };
  26148. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26149. if (visibility === void 0) { visibility = 1; }
  26150. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26151. };
  26152. return PushMaterial;
  26153. }(BABYLON.Material));
  26154. BABYLON.PushMaterial = PushMaterial;
  26155. })(BABYLON || (BABYLON = {}));
  26156. //# sourceMappingURL=babylon.pushMaterial.js.map
  26157. var BABYLON;
  26158. (function (BABYLON) {
  26159. var VertexData = (function () {
  26160. function VertexData() {
  26161. }
  26162. VertexData.prototype.set = function (data, kind) {
  26163. switch (kind) {
  26164. case BABYLON.VertexBuffer.PositionKind:
  26165. this.positions = data;
  26166. break;
  26167. case BABYLON.VertexBuffer.NormalKind:
  26168. this.normals = data;
  26169. break;
  26170. case BABYLON.VertexBuffer.TangentKind:
  26171. this.tangents = data;
  26172. break;
  26173. case BABYLON.VertexBuffer.UVKind:
  26174. this.uvs = data;
  26175. break;
  26176. case BABYLON.VertexBuffer.UV2Kind:
  26177. this.uvs2 = data;
  26178. break;
  26179. case BABYLON.VertexBuffer.UV3Kind:
  26180. this.uvs3 = data;
  26181. break;
  26182. case BABYLON.VertexBuffer.UV4Kind:
  26183. this.uvs4 = data;
  26184. break;
  26185. case BABYLON.VertexBuffer.UV5Kind:
  26186. this.uvs5 = data;
  26187. break;
  26188. case BABYLON.VertexBuffer.UV6Kind:
  26189. this.uvs6 = data;
  26190. break;
  26191. case BABYLON.VertexBuffer.ColorKind:
  26192. this.colors = data;
  26193. break;
  26194. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26195. this.matricesIndices = data;
  26196. break;
  26197. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26198. this.matricesWeights = data;
  26199. break;
  26200. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26201. this.matricesIndicesExtra = data;
  26202. break;
  26203. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26204. this.matricesWeightsExtra = data;
  26205. break;
  26206. }
  26207. };
  26208. /**
  26209. * Associates the vertexData to the passed Mesh.
  26210. * Sets it as updatable or not (default `false`).
  26211. * Returns the VertexData.
  26212. */
  26213. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26214. this._applyTo(mesh, updatable);
  26215. return this;
  26216. };
  26217. /**
  26218. * Associates the vertexData to the passed Geometry.
  26219. * Sets it as updatable or not (default `false`).
  26220. * Returns the VertexData.
  26221. */
  26222. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26223. this._applyTo(geometry, updatable);
  26224. return this;
  26225. };
  26226. /**
  26227. * Updates the associated mesh.
  26228. * Returns the VertexData.
  26229. */
  26230. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26231. this._update(mesh);
  26232. return this;
  26233. };
  26234. /**
  26235. * Updates the associated geometry.
  26236. * Returns the VertexData.
  26237. */
  26238. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26239. this._update(geometry);
  26240. return this;
  26241. };
  26242. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26243. if (this.positions) {
  26244. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26245. }
  26246. if (this.normals) {
  26247. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26248. }
  26249. if (this.tangents) {
  26250. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26251. }
  26252. if (this.uvs) {
  26253. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26254. }
  26255. if (this.uvs2) {
  26256. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26257. }
  26258. if (this.uvs3) {
  26259. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26260. }
  26261. if (this.uvs4) {
  26262. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26263. }
  26264. if (this.uvs5) {
  26265. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26266. }
  26267. if (this.uvs6) {
  26268. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26269. }
  26270. if (this.colors) {
  26271. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26272. }
  26273. if (this.matricesIndices) {
  26274. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26275. }
  26276. if (this.matricesWeights) {
  26277. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26278. }
  26279. if (this.matricesIndicesExtra) {
  26280. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26281. }
  26282. if (this.matricesWeightsExtra) {
  26283. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26284. }
  26285. if (this.indices) {
  26286. meshOrGeometry.setIndices(this.indices);
  26287. }
  26288. return this;
  26289. };
  26290. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26291. if (this.positions) {
  26292. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26293. }
  26294. if (this.normals) {
  26295. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26296. }
  26297. if (this.tangents) {
  26298. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26299. }
  26300. if (this.uvs) {
  26301. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26302. }
  26303. if (this.uvs2) {
  26304. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26305. }
  26306. if (this.uvs3) {
  26307. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26308. }
  26309. if (this.uvs4) {
  26310. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26311. }
  26312. if (this.uvs5) {
  26313. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26314. }
  26315. if (this.uvs6) {
  26316. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26317. }
  26318. if (this.colors) {
  26319. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26320. }
  26321. if (this.matricesIndices) {
  26322. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26323. }
  26324. if (this.matricesWeights) {
  26325. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26326. }
  26327. if (this.matricesIndicesExtra) {
  26328. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26329. }
  26330. if (this.matricesWeightsExtra) {
  26331. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26332. }
  26333. if (this.indices) {
  26334. meshOrGeometry.setIndices(this.indices);
  26335. }
  26336. return this;
  26337. };
  26338. /**
  26339. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26340. * Returns the VertexData.
  26341. */
  26342. VertexData.prototype.transform = function (matrix) {
  26343. var transformed = BABYLON.Vector3.Zero();
  26344. var index;
  26345. if (this.positions) {
  26346. var position = BABYLON.Vector3.Zero();
  26347. for (index = 0; index < this.positions.length; index += 3) {
  26348. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26349. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26350. this.positions[index] = transformed.x;
  26351. this.positions[index + 1] = transformed.y;
  26352. this.positions[index + 2] = transformed.z;
  26353. }
  26354. }
  26355. if (this.normals) {
  26356. var normal = BABYLON.Vector3.Zero();
  26357. for (index = 0; index < this.normals.length; index += 3) {
  26358. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26359. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26360. this.normals[index] = transformed.x;
  26361. this.normals[index + 1] = transformed.y;
  26362. this.normals[index + 2] = transformed.z;
  26363. }
  26364. }
  26365. if (this.tangents) {
  26366. var tangent = BABYLON.Vector4.Zero();
  26367. var tangentTransformed = BABYLON.Vector4.Zero();
  26368. for (index = 0; index < this.tangents.length; index += 4) {
  26369. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26370. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26371. this.tangents[index] = tangentTransformed.x;
  26372. this.tangents[index + 1] = tangentTransformed.y;
  26373. this.tangents[index + 2] = tangentTransformed.z;
  26374. this.tangents[index + 3] = tangentTransformed.w;
  26375. }
  26376. }
  26377. return this;
  26378. };
  26379. /**
  26380. * Merges the passed VertexData into the current one.
  26381. * Returns the modified VertexData.
  26382. */
  26383. VertexData.prototype.merge = function (other) {
  26384. if (other.indices) {
  26385. if (!this.indices) {
  26386. this.indices = [];
  26387. }
  26388. var offset = this.positions ? this.positions.length / 3 : 0;
  26389. for (var index = 0; index < other.indices.length; index++) {
  26390. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26391. this.indices.push(other.indices[index] + offset);
  26392. }
  26393. }
  26394. this.positions = this._mergeElement(this.positions, other.positions);
  26395. this.normals = this._mergeElement(this.normals, other.normals);
  26396. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26397. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26398. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26399. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26400. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26401. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26402. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26403. this.colors = this._mergeElement(this.colors, other.colors);
  26404. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26405. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26406. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26407. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26408. return this;
  26409. };
  26410. VertexData.prototype._mergeElement = function (source, other) {
  26411. if (!other)
  26412. return source;
  26413. if (!source)
  26414. return other;
  26415. var len = other.length + source.length;
  26416. var isSrcTypedArray = source instanceof Float32Array;
  26417. var isOthTypedArray = other instanceof Float32Array;
  26418. // use non-loop method when the source is Float32Array
  26419. if (isSrcTypedArray) {
  26420. var ret32 = new Float32Array(len);
  26421. ret32.set(source);
  26422. ret32.set(other, source.length);
  26423. return ret32;
  26424. // source is number[], when other is also use concat
  26425. }
  26426. else if (!isOthTypedArray) {
  26427. return source.concat(other);
  26428. // source is a number[], but other is a Float32Array, loop required
  26429. }
  26430. else {
  26431. var ret = source.slice(0); // copy source to a separate array
  26432. for (var i = 0, len = other.length; i < len; i++) {
  26433. ret.push(other[i]);
  26434. }
  26435. return ret;
  26436. }
  26437. };
  26438. /**
  26439. * Serializes the VertexData.
  26440. * Returns a serialized object.
  26441. */
  26442. VertexData.prototype.serialize = function () {
  26443. var serializationObject = this.serialize();
  26444. if (this.positions) {
  26445. serializationObject.positions = this.positions;
  26446. }
  26447. if (this.normals) {
  26448. serializationObject.normals = this.normals;
  26449. }
  26450. if (this.tangents) {
  26451. serializationObject.tangents = this.tangents;
  26452. }
  26453. if (this.uvs) {
  26454. serializationObject.uvs = this.uvs;
  26455. }
  26456. if (this.uvs2) {
  26457. serializationObject.uvs2 = this.uvs2;
  26458. }
  26459. if (this.uvs3) {
  26460. serializationObject.uvs3 = this.uvs3;
  26461. }
  26462. if (this.uvs4) {
  26463. serializationObject.uvs4 = this.uvs4;
  26464. }
  26465. if (this.uvs5) {
  26466. serializationObject.uvs5 = this.uvs5;
  26467. }
  26468. if (this.uvs6) {
  26469. serializationObject.uvs6 = this.uvs6;
  26470. }
  26471. if (this.colors) {
  26472. serializationObject.colors = this.colors;
  26473. }
  26474. if (this.matricesIndices) {
  26475. serializationObject.matricesIndices = this.matricesIndices;
  26476. serializationObject.matricesIndices._isExpanded = true;
  26477. }
  26478. if (this.matricesWeights) {
  26479. serializationObject.matricesWeights = this.matricesWeights;
  26480. }
  26481. if (this.matricesIndicesExtra) {
  26482. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26483. serializationObject.matricesIndicesExtra._isExpanded = true;
  26484. }
  26485. if (this.matricesWeightsExtra) {
  26486. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26487. }
  26488. serializationObject.indices = this.indices;
  26489. return serializationObject;
  26490. };
  26491. // Statics
  26492. /**
  26493. * Returns the object VertexData associated to the passed mesh.
  26494. */
  26495. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26496. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26497. };
  26498. /**
  26499. * Returns the object VertexData associated to the passed geometry.
  26500. */
  26501. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26502. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26503. };
  26504. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26505. var result = new VertexData();
  26506. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26507. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26508. }
  26509. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26510. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26511. }
  26512. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26513. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26514. }
  26515. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26516. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26517. }
  26518. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26519. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26520. }
  26521. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26522. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26523. }
  26524. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26525. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26526. }
  26527. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26528. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26529. }
  26530. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26531. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26532. }
  26533. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26534. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26535. }
  26536. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26537. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26538. }
  26539. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26540. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26541. }
  26542. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26543. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26544. }
  26545. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26546. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26547. }
  26548. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26549. return result;
  26550. };
  26551. /**
  26552. * Creates the vertexData of the Ribbon.
  26553. */
  26554. VertexData.CreateRibbon = function (options) {
  26555. var pathArray = options.pathArray;
  26556. var closeArray = options.closeArray || false;
  26557. var closePath = options.closePath || false;
  26558. var invertUV = options.invertUV || false;
  26559. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26560. var offset = options.offset || defaultOffset;
  26561. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26562. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26563. var customUV = options.uvs;
  26564. var customColors = options.colors;
  26565. var positions = [];
  26566. var indices = [];
  26567. var normals = [];
  26568. var uvs = [];
  26569. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26570. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26571. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26572. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26573. var minlg; // minimal length among all paths from pathArray
  26574. var lg = []; // array of path lengths : nb of vertex per path
  26575. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26576. var p; // path iterator
  26577. var i; // point iterator
  26578. var j; // point iterator
  26579. // if single path in pathArray
  26580. if (pathArray.length < 2) {
  26581. var ar1 = [];
  26582. var ar2 = [];
  26583. for (i = 0; i < pathArray[0].length - offset; i++) {
  26584. ar1.push(pathArray[0][i]);
  26585. ar2.push(pathArray[0][i + offset]);
  26586. }
  26587. pathArray = [ar1, ar2];
  26588. }
  26589. // positions and horizontal distances (u)
  26590. var idc = 0;
  26591. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26592. var path;
  26593. var l;
  26594. minlg = pathArray[0].length;
  26595. var vectlg;
  26596. var dist;
  26597. for (p = 0; p < pathArray.length; p++) {
  26598. uTotalDistance[p] = 0;
  26599. us[p] = [0];
  26600. path = pathArray[p];
  26601. l = path.length;
  26602. minlg = (minlg < l) ? minlg : l;
  26603. j = 0;
  26604. while (j < l) {
  26605. positions.push(path[j].x, path[j].y, path[j].z);
  26606. if (j > 0) {
  26607. vectlg = path[j].subtract(path[j - 1]).length();
  26608. dist = vectlg + uTotalDistance[p];
  26609. us[p].push(dist);
  26610. uTotalDistance[p] = dist;
  26611. }
  26612. j++;
  26613. }
  26614. if (closePath) {
  26615. j--;
  26616. positions.push(path[0].x, path[0].y, path[0].z);
  26617. vectlg = path[j].subtract(path[0]).length();
  26618. dist = vectlg + uTotalDistance[p];
  26619. us[p].push(dist);
  26620. uTotalDistance[p] = dist;
  26621. }
  26622. lg[p] = l + closePathCorr;
  26623. idx[p] = idc;
  26624. idc += (l + closePathCorr);
  26625. }
  26626. // vertical distances (v)
  26627. var path1;
  26628. var path2;
  26629. var vertex1;
  26630. var vertex2;
  26631. for (i = 0; i < minlg + closePathCorr; i++) {
  26632. vTotalDistance[i] = 0;
  26633. vs[i] = [0];
  26634. for (p = 0; p < pathArray.length - 1; p++) {
  26635. path1 = pathArray[p];
  26636. path2 = pathArray[p + 1];
  26637. if (i === minlg) {
  26638. vertex1 = path1[0];
  26639. vertex2 = path2[0];
  26640. }
  26641. else {
  26642. vertex1 = path1[i];
  26643. vertex2 = path2[i];
  26644. }
  26645. vectlg = vertex2.subtract(vertex1).length();
  26646. dist = vectlg + vTotalDistance[i];
  26647. vs[i].push(dist);
  26648. vTotalDistance[i] = dist;
  26649. }
  26650. if (closeArray) {
  26651. path1 = pathArray[p];
  26652. path2 = pathArray[0];
  26653. if (i === minlg) {
  26654. vertex2 = path2[0];
  26655. }
  26656. vectlg = vertex2.subtract(vertex1).length();
  26657. dist = vectlg + vTotalDistance[i];
  26658. vTotalDistance[i] = dist;
  26659. }
  26660. }
  26661. // uvs
  26662. var u;
  26663. var v;
  26664. if (customUV) {
  26665. for (p = 0; p < customUV.length; p++) {
  26666. uvs.push(customUV[p].x, customUV[p].y);
  26667. }
  26668. }
  26669. else {
  26670. for (p = 0; p < pathArray.length; p++) {
  26671. for (i = 0; i < minlg + closePathCorr; i++) {
  26672. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26673. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26674. if (invertUV) {
  26675. uvs.push(v, u);
  26676. }
  26677. else {
  26678. uvs.push(u, v);
  26679. }
  26680. }
  26681. }
  26682. }
  26683. // indices
  26684. p = 0; // path index
  26685. var pi = 0; // positions array index
  26686. var l1 = lg[p] - 1; // path1 length
  26687. var l2 = lg[p + 1] - 1; // path2 length
  26688. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26689. var shft = idx[1] - idx[0]; // shift
  26690. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26691. while (pi <= min && p < path1nb) {
  26692. // 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
  26693. indices.push(pi, pi + shft, pi + 1);
  26694. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26695. pi += 1;
  26696. if (pi === min) {
  26697. p++;
  26698. if (p === lg.length - 1) {
  26699. shft = idx[0] - idx[p];
  26700. l1 = lg[p] - 1;
  26701. l2 = lg[0] - 1;
  26702. }
  26703. else {
  26704. shft = idx[p + 1] - idx[p];
  26705. l1 = lg[p] - 1;
  26706. l2 = lg[p + 1] - 1;
  26707. }
  26708. pi = idx[p];
  26709. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26710. }
  26711. }
  26712. // normals
  26713. VertexData.ComputeNormals(positions, indices, normals);
  26714. if (closePath) {
  26715. var indexFirst = 0;
  26716. var indexLast = 0;
  26717. for (p = 0; p < pathArray.length; p++) {
  26718. indexFirst = idx[p] * 3;
  26719. if (p + 1 < pathArray.length) {
  26720. indexLast = (idx[p + 1] - 1) * 3;
  26721. }
  26722. else {
  26723. indexLast = normals.length - 3;
  26724. }
  26725. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26726. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26727. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26728. normals[indexLast] = normals[indexFirst];
  26729. normals[indexLast + 1] = normals[indexFirst + 1];
  26730. normals[indexLast + 2] = normals[indexFirst + 2];
  26731. }
  26732. }
  26733. // sides
  26734. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26735. // Colors
  26736. if (customColors) {
  26737. var colors = new Float32Array(customColors.length * 4);
  26738. for (var c = 0; c < customColors.length; c++) {
  26739. colors[c * 4] = customColors[c].r;
  26740. colors[c * 4 + 1] = customColors[c].g;
  26741. colors[c * 4 + 2] = customColors[c].b;
  26742. colors[c * 4 + 3] = customColors[c].a;
  26743. }
  26744. }
  26745. // Result
  26746. var vertexData = new VertexData();
  26747. var positions32 = new Float32Array(positions);
  26748. var normals32 = new Float32Array(normals);
  26749. var uvs32 = new Float32Array(uvs);
  26750. vertexData.indices = indices;
  26751. vertexData.positions = positions32;
  26752. vertexData.normals = normals32;
  26753. vertexData.uvs = uvs32;
  26754. if (customColors) {
  26755. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  26756. }
  26757. if (closePath) {
  26758. vertexData._idx = idx;
  26759. }
  26760. return vertexData;
  26761. };
  26762. /**
  26763. * Creates the VertexData of the Box.
  26764. */
  26765. VertexData.CreateBox = function (options) {
  26766. var normalsSource = [
  26767. new BABYLON.Vector3(0, 0, 1),
  26768. new BABYLON.Vector3(0, 0, -1),
  26769. new BABYLON.Vector3(1, 0, 0),
  26770. new BABYLON.Vector3(-1, 0, 0),
  26771. new BABYLON.Vector3(0, 1, 0),
  26772. new BABYLON.Vector3(0, -1, 0)
  26773. ];
  26774. var indices = [];
  26775. var positions = [];
  26776. var normals = [];
  26777. var uvs = [];
  26778. var width = options.width || options.size || 1;
  26779. var height = options.height || options.size || 1;
  26780. var depth = options.depth || options.size || 1;
  26781. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26782. var faceUV = options.faceUV || new Array(6);
  26783. var faceColors = options.faceColors;
  26784. var colors = [];
  26785. // default face colors and UV if undefined
  26786. for (var f = 0; f < 6; f++) {
  26787. if (faceUV[f] === undefined) {
  26788. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26789. }
  26790. if (faceColors && faceColors[f] === undefined) {
  26791. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26792. }
  26793. }
  26794. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26795. // Create each face in turn.
  26796. for (var index = 0; index < normalsSource.length; index++) {
  26797. var normal = normalsSource[index];
  26798. // Get two vectors perpendicular to the face normal and to each other.
  26799. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26800. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26801. // Six indices (two triangles) per face.
  26802. var verticesLength = positions.length / 3;
  26803. indices.push(verticesLength);
  26804. indices.push(verticesLength + 1);
  26805. indices.push(verticesLength + 2);
  26806. indices.push(verticesLength);
  26807. indices.push(verticesLength + 2);
  26808. indices.push(verticesLength + 3);
  26809. // Four vertices per face.
  26810. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26811. positions.push(vertex.x, vertex.y, vertex.z);
  26812. normals.push(normal.x, normal.y, normal.z);
  26813. uvs.push(faceUV[index].z, faceUV[index].w);
  26814. if (faceColors) {
  26815. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26816. }
  26817. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26818. positions.push(vertex.x, vertex.y, vertex.z);
  26819. normals.push(normal.x, normal.y, normal.z);
  26820. uvs.push(faceUV[index].x, faceUV[index].w);
  26821. if (faceColors) {
  26822. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26823. }
  26824. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26825. positions.push(vertex.x, vertex.y, vertex.z);
  26826. normals.push(normal.x, normal.y, normal.z);
  26827. uvs.push(faceUV[index].x, faceUV[index].y);
  26828. if (faceColors) {
  26829. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26830. }
  26831. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26832. positions.push(vertex.x, vertex.y, vertex.z);
  26833. normals.push(normal.x, normal.y, normal.z);
  26834. uvs.push(faceUV[index].z, faceUV[index].y);
  26835. if (faceColors) {
  26836. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26837. }
  26838. }
  26839. // sides
  26840. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26841. // Result
  26842. var vertexData = new VertexData();
  26843. vertexData.indices = indices;
  26844. vertexData.positions = positions;
  26845. vertexData.normals = normals;
  26846. vertexData.uvs = uvs;
  26847. if (faceColors) {
  26848. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26849. vertexData.colors = totalColors;
  26850. }
  26851. return vertexData;
  26852. };
  26853. /**
  26854. * Creates the VertexData of the Sphere.
  26855. */
  26856. VertexData.CreateSphere = function (options) {
  26857. var segments = options.segments || 32;
  26858. var diameterX = options.diameterX || options.diameter || 1;
  26859. var diameterY = options.diameterY || options.diameter || 1;
  26860. var diameterZ = options.diameterZ || options.diameter || 1;
  26861. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26862. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26863. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26864. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26865. var totalZRotationSteps = 2 + segments;
  26866. var totalYRotationSteps = 2 * totalZRotationSteps;
  26867. var indices = [];
  26868. var positions = [];
  26869. var normals = [];
  26870. var uvs = [];
  26871. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26872. var normalizedZ = zRotationStep / totalZRotationSteps;
  26873. var angleZ = normalizedZ * Math.PI * slice;
  26874. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26875. var normalizedY = yRotationStep / totalYRotationSteps;
  26876. var angleY = normalizedY * Math.PI * 2 * arc;
  26877. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26878. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26879. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26880. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26881. var vertex = complete.multiply(radius);
  26882. var normal = complete.divide(radius).normalize();
  26883. positions.push(vertex.x, vertex.y, vertex.z);
  26884. normals.push(normal.x, normal.y, normal.z);
  26885. uvs.push(normalizedY, normalizedZ);
  26886. }
  26887. if (zRotationStep > 0) {
  26888. var verticesCount = positions.length / 3;
  26889. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26890. indices.push((firstIndex));
  26891. indices.push((firstIndex + 1));
  26892. indices.push(firstIndex + totalYRotationSteps + 1);
  26893. indices.push((firstIndex + totalYRotationSteps + 1));
  26894. indices.push((firstIndex + 1));
  26895. indices.push((firstIndex + totalYRotationSteps + 2));
  26896. }
  26897. }
  26898. }
  26899. // Sides
  26900. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26901. // Result
  26902. var vertexData = new VertexData();
  26903. vertexData.indices = indices;
  26904. vertexData.positions = positions;
  26905. vertexData.normals = normals;
  26906. vertexData.uvs = uvs;
  26907. return vertexData;
  26908. };
  26909. /**
  26910. * Creates the VertexData of the Cylinder or Cone.
  26911. */
  26912. VertexData.CreateCylinder = function (options) {
  26913. var height = options.height || 2;
  26914. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  26915. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  26916. var tessellation = options.tessellation || 24;
  26917. var subdivisions = options.subdivisions || 1;
  26918. var hasRings = options.hasRings;
  26919. var enclose = options.enclose;
  26920. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26921. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26922. var faceUV = options.faceUV || new Array(3);
  26923. var faceColors = options.faceColors;
  26924. // default face colors and UV if undefined
  26925. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  26926. var ringNb = (hasRings) ? subdivisions : 1;
  26927. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  26928. var f;
  26929. for (f = 0; f < surfaceNb; f++) {
  26930. if (faceColors && faceColors[f] === undefined) {
  26931. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26932. }
  26933. }
  26934. for (f = 0; f < surfaceNb; f++) {
  26935. if (faceUV && faceUV[f] === undefined) {
  26936. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26937. }
  26938. }
  26939. var indices = [];
  26940. var positions = [];
  26941. var normals = [];
  26942. var uvs = [];
  26943. var colors = [];
  26944. var angle_step = Math.PI * 2 * arc / tessellation;
  26945. var angle;
  26946. var h;
  26947. var radius;
  26948. var tan = (diameterBottom - diameterTop) / 2 / height;
  26949. var ringVertex = BABYLON.Vector3.Zero();
  26950. var ringNormal = BABYLON.Vector3.Zero();
  26951. var ringFirstVertex = BABYLON.Vector3.Zero();
  26952. var ringFirstNormal = BABYLON.Vector3.Zero();
  26953. var quadNormal = BABYLON.Vector3.Zero();
  26954. var Y = BABYLON.Axis.Y;
  26955. // positions, normals, uvs
  26956. var i;
  26957. var j;
  26958. var r;
  26959. var ringIdx = 1;
  26960. var s = 1; // surface index
  26961. var cs = 0;
  26962. var v = 0;
  26963. for (i = 0; i <= subdivisions; i++) {
  26964. h = i / subdivisions;
  26965. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26966. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  26967. for (r = 0; r < ringIdx; r++) {
  26968. if (hasRings) {
  26969. s += r;
  26970. }
  26971. if (enclose) {
  26972. s += 2 * r;
  26973. }
  26974. for (j = 0; j <= tessellation; j++) {
  26975. angle = j * angle_step;
  26976. // position
  26977. ringVertex.x = Math.cos(-angle) * radius;
  26978. ringVertex.y = -height / 2 + h * height;
  26979. ringVertex.z = Math.sin(-angle) * radius;
  26980. // normal
  26981. if (diameterTop === 0 && i === subdivisions) {
  26982. // if no top cap, reuse former normals
  26983. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26984. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26985. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26986. }
  26987. else {
  26988. ringNormal.x = ringVertex.x;
  26989. ringNormal.z = ringVertex.z;
  26990. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26991. ringNormal.normalize();
  26992. }
  26993. // keep first ring vertex values for enclose
  26994. if (j === 0) {
  26995. ringFirstVertex.copyFrom(ringVertex);
  26996. ringFirstNormal.copyFrom(ringNormal);
  26997. }
  26998. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26999. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27000. if (hasRings) {
  27001. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27002. }
  27003. else {
  27004. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27005. }
  27006. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27007. if (faceColors) {
  27008. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27009. }
  27010. }
  27011. // if enclose, add four vertices and their dedicated normals
  27012. if (arc !== 1 && enclose) {
  27013. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27014. positions.push(0, ringVertex.y, 0);
  27015. positions.push(0, ringVertex.y, 0);
  27016. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27017. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27018. quadNormal.normalize();
  27019. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27020. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27021. quadNormal.normalize();
  27022. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27023. if (hasRings) {
  27024. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27025. }
  27026. else {
  27027. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27028. }
  27029. uvs.push(faceUV[s + 1].x, v);
  27030. uvs.push(faceUV[s + 1].z, v);
  27031. if (hasRings) {
  27032. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27033. }
  27034. else {
  27035. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27036. }
  27037. uvs.push(faceUV[s + 2].x, v);
  27038. uvs.push(faceUV[s + 2].z, v);
  27039. if (faceColors) {
  27040. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27041. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27042. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27043. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27044. }
  27045. }
  27046. if (cs !== s) {
  27047. cs = s;
  27048. }
  27049. }
  27050. }
  27051. // indices
  27052. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27053. var s;
  27054. i = 0;
  27055. for (s = 0; s < subdivisions; s++) {
  27056. for (j = 0; j < tessellation; j++) {
  27057. var i0 = i * (e + 1) + j;
  27058. var i1 = (i + 1) * (e + 1) + j;
  27059. var i2 = i * (e + 1) + (j + 1);
  27060. var i3 = (i + 1) * (e + 1) + (j + 1);
  27061. indices.push(i0, i1, i2);
  27062. indices.push(i3, i2, i1);
  27063. }
  27064. if (arc !== 1 && enclose) {
  27065. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27066. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27067. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27068. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27069. }
  27070. i = (hasRings) ? (i + 2) : (i + 1);
  27071. }
  27072. // Caps
  27073. var createCylinderCap = function (isTop) {
  27074. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27075. if (radius === 0) {
  27076. return;
  27077. }
  27078. // Cap positions, normals & uvs
  27079. var angle;
  27080. var circleVector;
  27081. var i;
  27082. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27083. var c;
  27084. if (faceColors) {
  27085. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27086. }
  27087. // cap center
  27088. var vbase = positions.length / 3;
  27089. var offset = isTop ? height / 2 : -height / 2;
  27090. var center = new BABYLON.Vector3(0, offset, 0);
  27091. positions.push(center.x, center.y, center.z);
  27092. normals.push(0, isTop ? 1 : -1, 0);
  27093. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27094. if (faceColors) {
  27095. colors.push(c.r, c.g, c.b, c.a);
  27096. }
  27097. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27098. for (i = 0; i <= tessellation; i++) {
  27099. angle = Math.PI * 2 * i * arc / tessellation;
  27100. var cos = Math.cos(-angle);
  27101. var sin = Math.sin(-angle);
  27102. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27103. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27104. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27105. normals.push(0, isTop ? 1 : -1, 0);
  27106. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27107. if (faceColors) {
  27108. colors.push(c.r, c.g, c.b, c.a);
  27109. }
  27110. }
  27111. // Cap indices
  27112. for (i = 0; i < tessellation; i++) {
  27113. if (!isTop) {
  27114. indices.push(vbase);
  27115. indices.push(vbase + (i + 1));
  27116. indices.push(vbase + (i + 2));
  27117. }
  27118. else {
  27119. indices.push(vbase);
  27120. indices.push(vbase + (i + 2));
  27121. indices.push(vbase + (i + 1));
  27122. }
  27123. }
  27124. };
  27125. // add caps to geometry
  27126. createCylinderCap(false);
  27127. createCylinderCap(true);
  27128. // Sides
  27129. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27130. var vertexData = new VertexData();
  27131. vertexData.indices = indices;
  27132. vertexData.positions = positions;
  27133. vertexData.normals = normals;
  27134. vertexData.uvs = uvs;
  27135. if (faceColors) {
  27136. vertexData.colors = colors;
  27137. }
  27138. return vertexData;
  27139. };
  27140. /**
  27141. * Creates the VertexData of the Torus.
  27142. */
  27143. VertexData.CreateTorus = function (options) {
  27144. var indices = [];
  27145. var positions = [];
  27146. var normals = [];
  27147. var uvs = [];
  27148. var diameter = options.diameter || 1;
  27149. var thickness = options.thickness || 0.5;
  27150. var tessellation = options.tessellation || 16;
  27151. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27152. var stride = tessellation + 1;
  27153. for (var i = 0; i <= tessellation; i++) {
  27154. var u = i / tessellation;
  27155. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27156. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27157. for (var j = 0; j <= tessellation; j++) {
  27158. var v = 1 - j / tessellation;
  27159. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27160. var dx = Math.cos(innerAngle);
  27161. var dy = Math.sin(innerAngle);
  27162. // Create a vertex.
  27163. var normal = new BABYLON.Vector3(dx, dy, 0);
  27164. var position = normal.scale(thickness / 2);
  27165. var textureCoordinate = new BABYLON.Vector2(u, v);
  27166. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27167. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27168. positions.push(position.x, position.y, position.z);
  27169. normals.push(normal.x, normal.y, normal.z);
  27170. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27171. // And create indices for two triangles.
  27172. var nextI = (i + 1) % stride;
  27173. var nextJ = (j + 1) % stride;
  27174. indices.push(i * stride + j);
  27175. indices.push(i * stride + nextJ);
  27176. indices.push(nextI * stride + j);
  27177. indices.push(i * stride + nextJ);
  27178. indices.push(nextI * stride + nextJ);
  27179. indices.push(nextI * stride + j);
  27180. }
  27181. }
  27182. // Sides
  27183. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27184. // Result
  27185. var vertexData = new VertexData();
  27186. vertexData.indices = indices;
  27187. vertexData.positions = positions;
  27188. vertexData.normals = normals;
  27189. vertexData.uvs = uvs;
  27190. return vertexData;
  27191. };
  27192. /**
  27193. * Creates the VertexData of the LineSystem.
  27194. */
  27195. VertexData.CreateLineSystem = function (options) {
  27196. var indices = [];
  27197. var positions = [];
  27198. var lines = options.lines;
  27199. var idx = 0;
  27200. for (var l = 0; l < lines.length; l++) {
  27201. var points = lines[l];
  27202. for (var index = 0; index < points.length; index++) {
  27203. positions.push(points[index].x, points[index].y, points[index].z);
  27204. if (index > 0) {
  27205. indices.push(idx - 1);
  27206. indices.push(idx);
  27207. }
  27208. idx++;
  27209. }
  27210. }
  27211. var vertexData = new VertexData();
  27212. vertexData.indices = indices;
  27213. vertexData.positions = positions;
  27214. return vertexData;
  27215. };
  27216. /**
  27217. * Create the VertexData of the DashedLines.
  27218. */
  27219. VertexData.CreateDashedLines = function (options) {
  27220. var dashSize = options.dashSize || 3;
  27221. var gapSize = options.gapSize || 1;
  27222. var dashNb = options.dashNb || 200;
  27223. var points = options.points;
  27224. var positions = new Array();
  27225. var indices = new Array();
  27226. var curvect = BABYLON.Vector3.Zero();
  27227. var lg = 0;
  27228. var nb = 0;
  27229. var shft = 0;
  27230. var dashshft = 0;
  27231. var curshft = 0;
  27232. var idx = 0;
  27233. var i = 0;
  27234. for (i = 0; i < points.length - 1; i++) {
  27235. points[i + 1].subtractToRef(points[i], curvect);
  27236. lg += curvect.length();
  27237. }
  27238. shft = lg / dashNb;
  27239. dashshft = dashSize * shft / (dashSize + gapSize);
  27240. for (i = 0; i < points.length - 1; i++) {
  27241. points[i + 1].subtractToRef(points[i], curvect);
  27242. nb = Math.floor(curvect.length() / shft);
  27243. curvect.normalize();
  27244. for (var j = 0; j < nb; j++) {
  27245. curshft = shft * j;
  27246. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27247. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27248. indices.push(idx, idx + 1);
  27249. idx += 2;
  27250. }
  27251. }
  27252. // Result
  27253. var vertexData = new VertexData();
  27254. vertexData.positions = positions;
  27255. vertexData.indices = indices;
  27256. return vertexData;
  27257. };
  27258. /**
  27259. * Creates the VertexData of the Ground.
  27260. */
  27261. VertexData.CreateGround = function (options) {
  27262. var indices = [];
  27263. var positions = [];
  27264. var normals = [];
  27265. var uvs = [];
  27266. var row, col;
  27267. var width = options.width || 1;
  27268. var height = options.height || 1;
  27269. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27270. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27271. for (row = 0; row <= subdivisionsY; row++) {
  27272. for (col = 0; col <= subdivisionsX; col++) {
  27273. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27274. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27275. positions.push(position.x, position.y, position.z);
  27276. normals.push(normal.x, normal.y, normal.z);
  27277. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27278. }
  27279. }
  27280. for (row = 0; row < subdivisionsY; row++) {
  27281. for (col = 0; col < subdivisionsX; col++) {
  27282. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27283. indices.push(col + 1 + row * (subdivisionsX + 1));
  27284. indices.push(col + row * (subdivisionsX + 1));
  27285. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27286. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27287. indices.push(col + row * (subdivisionsX + 1));
  27288. }
  27289. }
  27290. // Result
  27291. var vertexData = new VertexData();
  27292. vertexData.indices = indices;
  27293. vertexData.positions = positions;
  27294. vertexData.normals = normals;
  27295. vertexData.uvs = uvs;
  27296. return vertexData;
  27297. };
  27298. /**
  27299. * Creates the VertexData of the TiledGround.
  27300. */
  27301. VertexData.CreateTiledGround = function (options) {
  27302. var xmin = options.xmin || -1.0;
  27303. var zmin = options.zmin || -1.0;
  27304. var xmax = options.xmax || 1.0;
  27305. var zmax = options.zmax || 1.0;
  27306. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27307. var precision = options.precision || { w: 1, h: 1 };
  27308. var indices = [];
  27309. var positions = [];
  27310. var normals = [];
  27311. var uvs = [];
  27312. var row, col, tileRow, tileCol;
  27313. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27314. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27315. precision.w = (precision.w < 1) ? 1 : precision.w;
  27316. precision.h = (precision.h < 1) ? 1 : precision.h;
  27317. var tileSize = {
  27318. 'w': (xmax - xmin) / subdivisions.w,
  27319. 'h': (zmax - zmin) / subdivisions.h
  27320. };
  27321. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27322. // Indices
  27323. var base = positions.length / 3;
  27324. var rowLength = precision.w + 1;
  27325. for (row = 0; row < precision.h; row++) {
  27326. for (col = 0; col < precision.w; col++) {
  27327. var square = [
  27328. base + col + row * rowLength,
  27329. base + (col + 1) + row * rowLength,
  27330. base + (col + 1) + (row + 1) * rowLength,
  27331. base + col + (row + 1) * rowLength
  27332. ];
  27333. indices.push(square[1]);
  27334. indices.push(square[2]);
  27335. indices.push(square[3]);
  27336. indices.push(square[0]);
  27337. indices.push(square[1]);
  27338. indices.push(square[3]);
  27339. }
  27340. }
  27341. // Position, normals and uvs
  27342. var position = BABYLON.Vector3.Zero();
  27343. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27344. for (row = 0; row <= precision.h; row++) {
  27345. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27346. for (col = 0; col <= precision.w; col++) {
  27347. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27348. position.y = 0;
  27349. positions.push(position.x, position.y, position.z);
  27350. normals.push(normal.x, normal.y, normal.z);
  27351. uvs.push(col / precision.w, row / precision.h);
  27352. }
  27353. }
  27354. }
  27355. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27356. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27357. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27358. }
  27359. }
  27360. // Result
  27361. var vertexData = new VertexData();
  27362. vertexData.indices = indices;
  27363. vertexData.positions = positions;
  27364. vertexData.normals = normals;
  27365. vertexData.uvs = uvs;
  27366. return vertexData;
  27367. };
  27368. /**
  27369. * Creates the VertexData of the Ground designed from a heightmap.
  27370. */
  27371. VertexData.CreateGroundFromHeightMap = function (options) {
  27372. var indices = [];
  27373. var positions = [];
  27374. var normals = [];
  27375. var uvs = [];
  27376. var row, col;
  27377. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27378. // Vertices
  27379. for (row = 0; row <= options.subdivisions; row++) {
  27380. for (col = 0; col <= options.subdivisions; col++) {
  27381. 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));
  27382. // Compute height
  27383. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27384. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27385. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27386. var r = options.buffer[pos] / 255.0;
  27387. var g = options.buffer[pos + 1] / 255.0;
  27388. var b = options.buffer[pos + 2] / 255.0;
  27389. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27390. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27391. // Add vertex
  27392. positions.push(position.x, position.y, position.z);
  27393. normals.push(0, 0, 0);
  27394. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27395. }
  27396. }
  27397. // Indices
  27398. for (row = 0; row < options.subdivisions; row++) {
  27399. for (col = 0; col < options.subdivisions; col++) {
  27400. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27401. indices.push(col + 1 + row * (options.subdivisions + 1));
  27402. indices.push(col + row * (options.subdivisions + 1));
  27403. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27404. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27405. indices.push(col + row * (options.subdivisions + 1));
  27406. }
  27407. }
  27408. // Normals
  27409. VertexData.ComputeNormals(positions, indices, normals);
  27410. // Result
  27411. var vertexData = new VertexData();
  27412. vertexData.indices = indices;
  27413. vertexData.positions = positions;
  27414. vertexData.normals = normals;
  27415. vertexData.uvs = uvs;
  27416. return vertexData;
  27417. };
  27418. /**
  27419. * Creates the VertexData of the Plane.
  27420. */
  27421. VertexData.CreatePlane = function (options) {
  27422. var indices = [];
  27423. var positions = [];
  27424. var normals = [];
  27425. var uvs = [];
  27426. var width = options.width || options.size || 1;
  27427. var height = options.height || options.size || 1;
  27428. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27429. // Vertices
  27430. var halfWidth = width / 2.0;
  27431. var halfHeight = height / 2.0;
  27432. positions.push(-halfWidth, -halfHeight, 0);
  27433. normals.push(0, 0, -1.0);
  27434. uvs.push(0.0, 0.0);
  27435. positions.push(halfWidth, -halfHeight, 0);
  27436. normals.push(0, 0, -1.0);
  27437. uvs.push(1.0, 0.0);
  27438. positions.push(halfWidth, halfHeight, 0);
  27439. normals.push(0, 0, -1.0);
  27440. uvs.push(1.0, 1.0);
  27441. positions.push(-halfWidth, halfHeight, 0);
  27442. normals.push(0, 0, -1.0);
  27443. uvs.push(0.0, 1.0);
  27444. // Indices
  27445. indices.push(0);
  27446. indices.push(1);
  27447. indices.push(2);
  27448. indices.push(0);
  27449. indices.push(2);
  27450. indices.push(3);
  27451. // Sides
  27452. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27453. // Result
  27454. var vertexData = new VertexData();
  27455. vertexData.indices = indices;
  27456. vertexData.positions = positions;
  27457. vertexData.normals = normals;
  27458. vertexData.uvs = uvs;
  27459. return vertexData;
  27460. };
  27461. /**
  27462. * Creates the VertexData of the Disc or regular Polygon.
  27463. */
  27464. VertexData.CreateDisc = function (options) {
  27465. var positions = [];
  27466. var indices = [];
  27467. var normals = [];
  27468. var uvs = [];
  27469. var radius = options.radius || 0.5;
  27470. var tessellation = options.tessellation || 64;
  27471. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27472. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27473. // positions and uvs
  27474. positions.push(0, 0, 0); // disc center first
  27475. uvs.push(0.5, 0.5);
  27476. var theta = Math.PI * 2 * arc;
  27477. var step = theta / tessellation;
  27478. for (var a = 0; a < theta; a += step) {
  27479. var x = Math.cos(a);
  27480. var y = Math.sin(a);
  27481. var u = (x + 1) / 2;
  27482. var v = (1 - y) / 2;
  27483. positions.push(radius * x, radius * y, 0);
  27484. uvs.push(u, v);
  27485. }
  27486. if (arc === 1) {
  27487. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27488. uvs.push(uvs[2], uvs[3]);
  27489. }
  27490. //indices
  27491. var vertexNb = positions.length / 3;
  27492. for (var i = 1; i < vertexNb - 1; i++) {
  27493. indices.push(i + 1, 0, i);
  27494. }
  27495. // result
  27496. VertexData.ComputeNormals(positions, indices, normals);
  27497. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27498. var vertexData = new VertexData();
  27499. vertexData.indices = indices;
  27500. vertexData.positions = positions;
  27501. vertexData.normals = normals;
  27502. vertexData.uvs = uvs;
  27503. return vertexData;
  27504. };
  27505. /**
  27506. * Re-creates the VertexData of the Polygon for sideOrientation.
  27507. */
  27508. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27509. var faceUV = fUV || new Array(3);
  27510. var faceColors = fColors;
  27511. var colors = [];
  27512. // default face colors and UV if undefined
  27513. for (var f = 0; f < 3; f++) {
  27514. if (faceUV[f] === undefined) {
  27515. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27516. }
  27517. if (faceColors && faceColors[f] === undefined) {
  27518. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27519. }
  27520. }
  27521. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27522. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27523. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27524. var indices = polygon.getIndices();
  27525. // set face colours and textures
  27526. var idx = 0;
  27527. var face = 0;
  27528. for (var index = 0; index < normals.length; index += 3) {
  27529. //Edge Face no. 1
  27530. if (Math.abs(normals[index + 1]) < 0.001) {
  27531. face = 1;
  27532. }
  27533. //Top Face no. 0
  27534. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27535. face = 0;
  27536. }
  27537. //Bottom Face no. 2
  27538. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27539. face = 2;
  27540. }
  27541. idx = index / 3;
  27542. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27543. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27544. if (faceColors) {
  27545. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27546. }
  27547. }
  27548. // sides
  27549. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27550. // Result
  27551. var vertexData = new VertexData();
  27552. vertexData.indices = indices;
  27553. vertexData.positions = positions;
  27554. vertexData.normals = normals;
  27555. vertexData.uvs = uvs;
  27556. if (faceColors) {
  27557. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27558. vertexData.colors = totalColors;
  27559. }
  27560. return vertexData;
  27561. };
  27562. /**
  27563. * Creates the VertexData of the IcoSphere.
  27564. */
  27565. VertexData.CreateIcoSphere = function (options) {
  27566. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27567. var radius = options.radius || 1;
  27568. var flat = (options.flat === undefined) ? true : options.flat;
  27569. var subdivisions = options.subdivisions || 4;
  27570. var radiusX = options.radiusX || radius;
  27571. var radiusY = options.radiusY || radius;
  27572. var radiusZ = options.radiusZ || radius;
  27573. var t = (1 + Math.sqrt(5)) / 2;
  27574. // 12 vertex x,y,z
  27575. var ico_vertices = [
  27576. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27577. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27578. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27579. ];
  27580. // index of 3 vertex makes a face of icopshere
  27581. var ico_indices = [
  27582. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27583. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27584. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27585. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27586. ];
  27587. // vertex for uv have aliased position, not for UV
  27588. var vertices_unalias_id = [
  27589. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27590. // vertex alias
  27591. 0,
  27592. 2,
  27593. 3,
  27594. 3,
  27595. 3,
  27596. 4,
  27597. 7,
  27598. 8,
  27599. 9,
  27600. 9,
  27601. 10,
  27602. 11 // 23: B + 12
  27603. ];
  27604. // uv as integer step (not pixels !)
  27605. var ico_vertexuv = [
  27606. 5, 1, 3, 1, 6, 4, 0, 0,
  27607. 5, 3, 4, 2, 2, 2, 4, 0,
  27608. 2, 0, 1, 1, 6, 0, 6, 2,
  27609. // vertex alias (for same vertex on different faces)
  27610. 0, 4,
  27611. 3, 3,
  27612. 4, 4,
  27613. 3, 1,
  27614. 4, 2,
  27615. 4, 4,
  27616. 0, 2,
  27617. 1, 1,
  27618. 2, 2,
  27619. 3, 3,
  27620. 1, 3,
  27621. 2, 4 // 23: B + 12
  27622. ];
  27623. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27624. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27625. // First island of uv mapping
  27626. // v = 4h 3+ 2
  27627. // v = 3h 9+ 4
  27628. // v = 2h 9+ 5 B
  27629. // v = 1h 9 1 0
  27630. // v = 0h 3 8 7 A
  27631. // u = 0 1 2 3 4 5 6 *a
  27632. // Second island of uv mapping
  27633. // v = 4h 0+ B+ 4+
  27634. // v = 3h A+ 2+
  27635. // v = 2h 7+ 6 3+
  27636. // v = 1h 8+ 3+
  27637. // v = 0h
  27638. // u = 0 1 2 3 4 5 6 *a
  27639. // Face layout on texture UV mapping
  27640. // ============
  27641. // \ 4 /\ 16 / ======
  27642. // \ / \ / /\ 11 /
  27643. // \/ 7 \/ / \ /
  27644. // ======= / 10 \/
  27645. // /\ 17 /\ =======
  27646. // / \ / \ \ 15 /\
  27647. // / 8 \/ 12 \ \ / \
  27648. // ============ \/ 6 \
  27649. // \ 18 /\ ============
  27650. // \ / \ \ 5 /\ 0 /
  27651. // \/ 13 \ \ / \ /
  27652. // ======= \/ 1 \/
  27653. // =============
  27654. // /\ 19 /\ 2 /\
  27655. // / \ / \ / \
  27656. // / 14 \/ 9 \/ 3 \
  27657. // ===================
  27658. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27659. var ustep = 138 / 1024;
  27660. var vstep = 239 / 1024;
  27661. var uoffset = 60 / 1024;
  27662. var voffset = 26 / 1024;
  27663. // Second island should have margin, not to touch the first island
  27664. // avoid any borderline artefact in pixel rounding
  27665. var island_u_offset = -40 / 1024;
  27666. var island_v_offset = +20 / 1024;
  27667. // face is either island 0 or 1 :
  27668. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27669. var island = [
  27670. 0, 0, 0, 0, 1,
  27671. 0, 0, 1, 1, 0,
  27672. 0, 0, 1, 1, 0,
  27673. 0, 1, 1, 1, 0 // 15 - 19
  27674. ];
  27675. var indices = [];
  27676. var positions = [];
  27677. var normals = [];
  27678. var uvs = [];
  27679. var current_indice = 0;
  27680. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27681. var face_vertex_pos = new Array(3);
  27682. var face_vertex_uv = new Array(3);
  27683. var v012;
  27684. for (v012 = 0; v012 < 3; v012++) {
  27685. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27686. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27687. }
  27688. // create all with normals
  27689. for (var face = 0; face < 20; face++) {
  27690. // 3 vertex per face
  27691. for (v012 = 0; v012 < 3; v012++) {
  27692. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27693. var v_id = ico_indices[3 * face + v012];
  27694. // vertex have 3D position (x,y,z)
  27695. 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]);
  27696. // Normalize to get normal, then scale to radius
  27697. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27698. // uv Coordinates from vertex ID
  27699. 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);
  27700. }
  27701. // Subdivide the face (interpolate pos, norm, uv)
  27702. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27703. // - norm is linear interpolation of vertex corner normal
  27704. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27705. // - uv is linear interpolation
  27706. //
  27707. // Topology is as below for sub-divide by 2
  27708. // vertex shown as v0,v1,v2
  27709. // interp index is i1 to progress in range [v0,v1[
  27710. // interp index is i2 to progress in range [v0,v2[
  27711. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27712. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27713. //
  27714. //
  27715. // i2 v2
  27716. // ^ ^
  27717. // / / \
  27718. // / / \
  27719. // / / \
  27720. // / / (0,1) \
  27721. // / #---------\
  27722. // / / \ (0,0)'/ \
  27723. // / / \ / \
  27724. // / / \ / \
  27725. // / / (0,0) \ / (1,0) \
  27726. // / #---------#---------\
  27727. // v0 v1
  27728. //
  27729. // --------------------> i1
  27730. //
  27731. // interp of (i1,i2):
  27732. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27733. // along i1 : lerp(x0,x1, i1/(S-i2))
  27734. //
  27735. // centroid of triangle is needed to get help normal computation
  27736. // (c1,c2) are used for centroid location
  27737. var interp_vertex = function (i1, i2, c1, c2) {
  27738. // vertex is interpolated from
  27739. // - face_vertex_pos[0..2]
  27740. // - face_vertex_uv[0..2]
  27741. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27742. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27743. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27744. pos_interp.normalize();
  27745. var vertex_normal;
  27746. if (flat) {
  27747. // in flat mode, recalculate normal as face centroid normal
  27748. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27749. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27750. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27751. }
  27752. else {
  27753. // in smooth mode, recalculate normal from each single vertex position
  27754. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27755. }
  27756. // Vertex normal need correction due to X,Y,Z radius scaling
  27757. vertex_normal.x /= radiusX;
  27758. vertex_normal.y /= radiusY;
  27759. vertex_normal.z /= radiusZ;
  27760. vertex_normal.normalize();
  27761. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27762. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27763. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27764. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27765. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27766. uvs.push(uv_interp.x, uv_interp.y);
  27767. // push each vertex has member of a face
  27768. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27769. indices.push(current_indice);
  27770. current_indice++;
  27771. };
  27772. for (var i2 = 0; i2 < subdivisions; i2++) {
  27773. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27774. // face : (i1,i2) for /\ :
  27775. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27776. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27777. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27778. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27779. if (i1 + i2 + 1 < subdivisions) {
  27780. // face : (i1,i2)' for \/ :
  27781. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27782. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27783. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27784. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27785. }
  27786. }
  27787. }
  27788. }
  27789. // Sides
  27790. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27791. // Result
  27792. var vertexData = new VertexData();
  27793. vertexData.indices = indices;
  27794. vertexData.positions = positions;
  27795. vertexData.normals = normals;
  27796. vertexData.uvs = uvs;
  27797. return vertexData;
  27798. };
  27799. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27800. /**
  27801. * Creates the VertexData of the Polyhedron.
  27802. */
  27803. VertexData.CreatePolyhedron = function (options) {
  27804. // provided polyhedron types :
  27805. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27806. // 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)
  27807. var polyhedra = [];
  27808. 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]] };
  27809. 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]] };
  27810. polyhedra[2] = {
  27811. 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]],
  27812. 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]]
  27813. };
  27814. polyhedra[3] = {
  27815. 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]],
  27816. 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]]
  27817. };
  27818. polyhedra[4] = {
  27819. 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]],
  27820. 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]]
  27821. };
  27822. 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]] };
  27823. 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]] };
  27824. 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]] };
  27825. 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]] };
  27826. 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]] };
  27827. 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]] };
  27828. 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]] };
  27829. 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]] };
  27830. 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]] };
  27831. polyhedra[14] = {
  27832. 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]],
  27833. 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]]
  27834. };
  27835. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27836. var size = options.size;
  27837. var sizeX = options.sizeX || size || 1;
  27838. var sizeY = options.sizeY || size || 1;
  27839. var sizeZ = options.sizeZ || size || 1;
  27840. var data = options.custom || polyhedra[type];
  27841. var nbfaces = data.face.length;
  27842. var faceUV = options.faceUV || new Array(nbfaces);
  27843. var faceColors = options.faceColors;
  27844. var flat = (options.flat === undefined) ? true : options.flat;
  27845. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27846. var positions = [];
  27847. var indices = [];
  27848. var normals = [];
  27849. var uvs = [];
  27850. var colors = [];
  27851. var index = 0;
  27852. var faceIdx = 0; // face cursor in the array "indexes"
  27853. var indexes = [];
  27854. var i = 0;
  27855. var f = 0;
  27856. var u, v, ang, x, y, tmp;
  27857. // default face colors and UV if undefined
  27858. if (flat) {
  27859. for (f = 0; f < nbfaces; f++) {
  27860. if (faceColors && faceColors[f] === undefined) {
  27861. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27862. }
  27863. if (faceUV && faceUV[f] === undefined) {
  27864. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27865. }
  27866. }
  27867. }
  27868. if (!flat) {
  27869. for (i = 0; i < data.vertex.length; i++) {
  27870. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27871. uvs.push(0, 0);
  27872. }
  27873. for (f = 0; f < nbfaces; f++) {
  27874. for (i = 0; i < data.face[f].length - 2; i++) {
  27875. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27876. }
  27877. }
  27878. }
  27879. else {
  27880. for (f = 0; f < nbfaces; f++) {
  27881. var fl = data.face[f].length; // number of vertices of the current face
  27882. ang = 2 * Math.PI / fl;
  27883. x = 0.5 * Math.tan(ang / 2);
  27884. y = 0.5;
  27885. // positions, uvs, colors
  27886. for (i = 0; i < fl; i++) {
  27887. // positions
  27888. 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);
  27889. indexes.push(index);
  27890. index++;
  27891. // uvs
  27892. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27893. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27894. uvs.push(u, v);
  27895. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27896. y = x * Math.sin(ang) + y * Math.cos(ang);
  27897. x = tmp;
  27898. // colors
  27899. if (faceColors) {
  27900. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27901. }
  27902. }
  27903. // indices from indexes
  27904. for (i = 0; i < fl - 2; i++) {
  27905. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27906. }
  27907. faceIdx += fl;
  27908. }
  27909. }
  27910. VertexData.ComputeNormals(positions, indices, normals);
  27911. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27912. var vertexData = new VertexData();
  27913. vertexData.positions = positions;
  27914. vertexData.indices = indices;
  27915. vertexData.normals = normals;
  27916. vertexData.uvs = uvs;
  27917. if (faceColors && flat) {
  27918. vertexData.colors = colors;
  27919. }
  27920. return vertexData;
  27921. };
  27922. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27923. /**
  27924. * Creates the VertexData of the Torus Knot.
  27925. */
  27926. VertexData.CreateTorusKnot = function (options) {
  27927. var indices = [];
  27928. var positions = [];
  27929. var normals = [];
  27930. var uvs = [];
  27931. var radius = options.radius || 2;
  27932. var tube = options.tube || 0.5;
  27933. var radialSegments = options.radialSegments || 32;
  27934. var tubularSegments = options.tubularSegments || 32;
  27935. var p = options.p || 2;
  27936. var q = options.q || 3;
  27937. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27938. // Helper
  27939. var getPos = function (angle) {
  27940. var cu = Math.cos(angle);
  27941. var su = Math.sin(angle);
  27942. var quOverP = q / p * angle;
  27943. var cs = Math.cos(quOverP);
  27944. var tx = radius * (2 + cs) * 0.5 * cu;
  27945. var ty = radius * (2 + cs) * su * 0.5;
  27946. var tz = radius * Math.sin(quOverP) * 0.5;
  27947. return new BABYLON.Vector3(tx, ty, tz);
  27948. };
  27949. // Vertices
  27950. var i;
  27951. var j;
  27952. for (i = 0; i <= radialSegments; i++) {
  27953. var modI = i % radialSegments;
  27954. var u = modI / radialSegments * 2 * p * Math.PI;
  27955. var p1 = getPos(u);
  27956. var p2 = getPos(u + 0.01);
  27957. var tang = p2.subtract(p1);
  27958. var n = p2.add(p1);
  27959. var bitan = BABYLON.Vector3.Cross(tang, n);
  27960. n = BABYLON.Vector3.Cross(bitan, tang);
  27961. bitan.normalize();
  27962. n.normalize();
  27963. for (j = 0; j < tubularSegments; j++) {
  27964. var modJ = j % tubularSegments;
  27965. var v = modJ / tubularSegments * 2 * Math.PI;
  27966. var cx = -tube * Math.cos(v);
  27967. var cy = tube * Math.sin(v);
  27968. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27969. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27970. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27971. uvs.push(i / radialSegments);
  27972. uvs.push(j / tubularSegments);
  27973. }
  27974. }
  27975. for (i = 0; i < radialSegments; i++) {
  27976. for (j = 0; j < tubularSegments; j++) {
  27977. var jNext = (j + 1) % tubularSegments;
  27978. var a = i * tubularSegments + j;
  27979. var b = (i + 1) * tubularSegments + j;
  27980. var c = (i + 1) * tubularSegments + jNext;
  27981. var d = i * tubularSegments + jNext;
  27982. indices.push(d);
  27983. indices.push(b);
  27984. indices.push(a);
  27985. indices.push(d);
  27986. indices.push(c);
  27987. indices.push(b);
  27988. }
  27989. }
  27990. // Normals
  27991. VertexData.ComputeNormals(positions, indices, normals);
  27992. // Sides
  27993. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27994. // Result
  27995. var vertexData = new VertexData();
  27996. vertexData.indices = indices;
  27997. vertexData.positions = positions;
  27998. vertexData.normals = normals;
  27999. vertexData.uvs = uvs;
  28000. return vertexData;
  28001. };
  28002. // Tools
  28003. /**
  28004. * @param {any} - positions (number[] or Float32Array)
  28005. * @param {any} - indices (number[] or Uint16Array)
  28006. * @param {any} - normals (number[] or Float32Array)
  28007. * options (optional) :
  28008. * facetPositions : optional array of facet positions (vector3)
  28009. * facetNormals : optional array of facet normals (vector3)
  28010. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28011. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28012. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28013. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28014. * bInfo : optional bounding info, required for facetPartitioning computation
  28015. */
  28016. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28017. // temporary scalar variables
  28018. var index = 0; // facet index
  28019. var p1p2x = 0.0; // p1p2 vector x coordinate
  28020. var p1p2y = 0.0; // p1p2 vector y coordinate
  28021. var p1p2z = 0.0; // p1p2 vector z coordinate
  28022. var p3p2x = 0.0; // p3p2 vector x coordinate
  28023. var p3p2y = 0.0; // p3p2 vector y coordinate
  28024. var p3p2z = 0.0; // p3p2 vector z coordinate
  28025. var faceNormalx = 0.0; // facet normal x coordinate
  28026. var faceNormaly = 0.0; // facet normal y coordinate
  28027. var faceNormalz = 0.0; // facet normal z coordinate
  28028. var length = 0.0; // facet normal length before normalization
  28029. var v1x = 0; // vector1 x index in the positions array
  28030. var v1y = 0; // vector1 y index in the positions array
  28031. var v1z = 0; // vector1 z index in the positions array
  28032. var v2x = 0; // vector2 x index in the positions array
  28033. var v2y = 0; // vector2 y index in the positions array
  28034. var v2z = 0; // vector2 z index in the positions array
  28035. var v3x = 0; // vector3 x index in the positions array
  28036. var v3y = 0; // vector3 y index in the positions array
  28037. var v3z = 0; // vector3 z index in the positions array
  28038. var computeFacetNormals = false;
  28039. var computeFacetPositions = false;
  28040. var computeFacetPartitioning = false;
  28041. var faceNormalSign = 1;
  28042. if (options) {
  28043. computeFacetNormals = (options.facetNormals) ? true : false;
  28044. computeFacetPositions = (options.facetPositions) ? true : false;
  28045. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28046. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28047. }
  28048. // facetPartitioning reinit if needed
  28049. if (computeFacetPartitioning) {
  28050. var ox = 0; // X partitioning index for facet position
  28051. var oy = 0; // Y partinioning index for facet position
  28052. var oz = 0; // Z partinioning index for facet position
  28053. var b1x = 0; // X partitioning index for facet v1 vertex
  28054. var b1y = 0; // Y partitioning index for facet v1 vertex
  28055. var b1z = 0; // z partitioning index for facet v1 vertex
  28056. var b2x = 0; // X partitioning index for facet v2 vertex
  28057. var b2y = 0; // Y partitioning index for facet v2 vertex
  28058. var b2z = 0; // Z partitioning index for facet v2 vertex
  28059. var b3x = 0; // X partitioning index for facet v3 vertex
  28060. var b3y = 0; // Y partitioning index for facet v3 vertex
  28061. var b3z = 0; // Z partitioning index for facet v3 vertex
  28062. var block_idx_o = 0; // facet barycenter block index
  28063. var block_idx_v1 = 0; // v1 vertex block index
  28064. var block_idx_v2 = 0; // v2 vertex block index
  28065. var block_idx_v3 = 0; // v3 vertex block index
  28066. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28067. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28068. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28069. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28070. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28071. var subSq = options.subDiv.max * options.subDiv.max;
  28072. options.facetPartitioning.length = 0;
  28073. }
  28074. // reset the normals
  28075. for (index = 0; index < positions.length; index++) {
  28076. normals[index] = 0.0;
  28077. }
  28078. // Loop : 1 indice triplet = 1 facet
  28079. var nbFaces = indices.length / 3;
  28080. for (index = 0; index < nbFaces; index++) {
  28081. // get the indexes of the coordinates of each vertex of the facet
  28082. v1x = indices[index * 3] * 3;
  28083. v1y = v1x + 1;
  28084. v1z = v1x + 2;
  28085. v2x = indices[index * 3 + 1] * 3;
  28086. v2y = v2x + 1;
  28087. v2z = v2x + 2;
  28088. v3x = indices[index * 3 + 2] * 3;
  28089. v3y = v3x + 1;
  28090. v3z = v3x + 2;
  28091. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28092. p1p2y = positions[v1y] - positions[v2y];
  28093. p1p2z = positions[v1z] - positions[v2z];
  28094. p3p2x = positions[v3x] - positions[v2x];
  28095. p3p2y = positions[v3y] - positions[v2y];
  28096. p3p2z = positions[v3z] - positions[v2z];
  28097. // compute the face normal with the cross product
  28098. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28099. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28100. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28101. // normalize this normal and store it in the array facetData
  28102. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28103. length = (length === 0) ? 1.0 : length;
  28104. faceNormalx /= length;
  28105. faceNormaly /= length;
  28106. faceNormalz /= length;
  28107. if (computeFacetNormals) {
  28108. options.facetNormals[index].x = faceNormalx;
  28109. options.facetNormals[index].y = faceNormaly;
  28110. options.facetNormals[index].z = faceNormalz;
  28111. }
  28112. if (computeFacetPositions) {
  28113. // compute and the facet barycenter coordinates in the array facetPositions
  28114. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28115. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28116. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28117. }
  28118. if (computeFacetPartitioning) {
  28119. // store the facet indexes in arrays in the main facetPartitioning array :
  28120. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28121. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28122. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28123. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28124. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28125. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28126. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28127. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28128. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28129. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28130. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28131. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28132. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28133. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28134. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28135. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28136. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28137. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28138. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28139. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28140. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28141. // push each facet index in each block containing the vertex
  28142. options.facetPartitioning[block_idx_v1].push(index);
  28143. if (block_idx_v2 != block_idx_v1) {
  28144. options.facetPartitioning[block_idx_v2].push(index);
  28145. }
  28146. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28147. options.facetPartitioning[block_idx_v3].push(index);
  28148. }
  28149. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28150. options.facetPartitioning[block_idx_o].push(index);
  28151. }
  28152. }
  28153. // compute the normals anyway
  28154. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28155. normals[v1y] += faceNormaly;
  28156. normals[v1z] += faceNormalz;
  28157. normals[v2x] += faceNormalx;
  28158. normals[v2y] += faceNormaly;
  28159. normals[v2z] += faceNormalz;
  28160. normals[v3x] += faceNormalx;
  28161. normals[v3y] += faceNormaly;
  28162. normals[v3z] += faceNormalz;
  28163. }
  28164. // last normalization of each normal
  28165. for (index = 0; index < normals.length / 3; index++) {
  28166. faceNormalx = normals[index * 3];
  28167. faceNormaly = normals[index * 3 + 1];
  28168. faceNormalz = normals[index * 3 + 2];
  28169. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28170. length = (length === 0) ? 1.0 : length;
  28171. faceNormalx /= length;
  28172. faceNormaly /= length;
  28173. faceNormalz /= length;
  28174. normals[index * 3] = faceNormalx;
  28175. normals[index * 3 + 1] = faceNormaly;
  28176. normals[index * 3 + 2] = faceNormalz;
  28177. }
  28178. };
  28179. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28180. var li = indices.length;
  28181. var ln = normals.length;
  28182. var i;
  28183. var n;
  28184. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28185. switch (sideOrientation) {
  28186. case BABYLON.Mesh.FRONTSIDE:
  28187. // nothing changed
  28188. break;
  28189. case BABYLON.Mesh.BACKSIDE:
  28190. var tmp;
  28191. // indices
  28192. for (i = 0; i < li; i += 3) {
  28193. tmp = indices[i];
  28194. indices[i] = indices[i + 2];
  28195. indices[i + 2] = tmp;
  28196. }
  28197. // normals
  28198. for (n = 0; n < ln; n++) {
  28199. normals[n] = -normals[n];
  28200. }
  28201. break;
  28202. case BABYLON.Mesh.DOUBLESIDE:
  28203. // positions
  28204. var lp = positions.length;
  28205. var l = lp / 3;
  28206. for (var p = 0; p < lp; p++) {
  28207. positions[lp + p] = positions[p];
  28208. }
  28209. // indices
  28210. for (i = 0; i < li; i += 3) {
  28211. indices[i + li] = indices[i + 2] + l;
  28212. indices[i + 1 + li] = indices[i + 1] + l;
  28213. indices[i + 2 + li] = indices[i] + l;
  28214. }
  28215. // normals
  28216. for (n = 0; n < ln; n++) {
  28217. normals[ln + n] = -normals[n];
  28218. }
  28219. // uvs
  28220. var lu = uvs.length;
  28221. var u = 0;
  28222. for (u = 0; u < lu; u++) {
  28223. uvs[u + lu] = uvs[u];
  28224. }
  28225. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28226. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28227. u = 0;
  28228. for (i = 0; i < lu / 2; i++) {
  28229. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28230. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28231. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28232. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28233. u += 2;
  28234. }
  28235. break;
  28236. }
  28237. };
  28238. /**
  28239. * Creates a new VertexData from the imported parameters.
  28240. */
  28241. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28242. var vertexData = new VertexData();
  28243. // positions
  28244. var positions = parsedVertexData.positions;
  28245. if (positions) {
  28246. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28247. }
  28248. // normals
  28249. var normals = parsedVertexData.normals;
  28250. if (normals) {
  28251. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28252. }
  28253. // tangents
  28254. var tangents = parsedVertexData.tangents;
  28255. if (tangents) {
  28256. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28257. }
  28258. // uvs
  28259. var uvs = parsedVertexData.uvs;
  28260. if (uvs) {
  28261. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28262. }
  28263. // uv2s
  28264. var uv2s = parsedVertexData.uv2s;
  28265. if (uv2s) {
  28266. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28267. }
  28268. // uv3s
  28269. var uv3s = parsedVertexData.uv3s;
  28270. if (uv3s) {
  28271. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28272. }
  28273. // uv4s
  28274. var uv4s = parsedVertexData.uv4s;
  28275. if (uv4s) {
  28276. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28277. }
  28278. // uv5s
  28279. var uv5s = parsedVertexData.uv5s;
  28280. if (uv5s) {
  28281. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28282. }
  28283. // uv6s
  28284. var uv6s = parsedVertexData.uv6s;
  28285. if (uv6s) {
  28286. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28287. }
  28288. // colors
  28289. var colors = parsedVertexData.colors;
  28290. if (colors) {
  28291. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28292. }
  28293. // matricesIndices
  28294. var matricesIndices = parsedVertexData.matricesIndices;
  28295. if (matricesIndices) {
  28296. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28297. }
  28298. // matricesWeights
  28299. var matricesWeights = parsedVertexData.matricesWeights;
  28300. if (matricesWeights) {
  28301. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28302. }
  28303. // indices
  28304. var indices = parsedVertexData.indices;
  28305. if (indices) {
  28306. vertexData.indices = indices;
  28307. }
  28308. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28309. };
  28310. return VertexData;
  28311. }());
  28312. BABYLON.VertexData = VertexData;
  28313. })(BABYLON || (BABYLON = {}));
  28314. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28315. var BABYLON;
  28316. (function (BABYLON) {
  28317. var Geometry = (function () {
  28318. function Geometry(id, scene, vertexData, updatable, mesh) {
  28319. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28320. this._totalVertices = 0;
  28321. this._isDisposed = false;
  28322. this.id = id;
  28323. this._engine = scene.getEngine();
  28324. this._meshes = [];
  28325. this._scene = scene;
  28326. //Init vertex buffer cache
  28327. this._vertexBuffers = {};
  28328. this._indices = [];
  28329. this._updatable = updatable;
  28330. // vertexData
  28331. if (vertexData) {
  28332. this.setAllVerticesData(vertexData, updatable);
  28333. }
  28334. else {
  28335. this._totalVertices = 0;
  28336. this._indices = [];
  28337. }
  28338. if (this._engine.getCaps().vertexArrayObject) {
  28339. this._vertexArrayObjects = {};
  28340. }
  28341. // applyToMesh
  28342. if (mesh) {
  28343. if (mesh.getClassName() === "LinesMesh") {
  28344. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28345. this.updateExtend();
  28346. }
  28347. this.applyToMesh(mesh);
  28348. mesh.computeWorldMatrix(true);
  28349. }
  28350. }
  28351. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28352. /**
  28353. * 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
  28354. * @returns The Bias Vector
  28355. */
  28356. get: function () {
  28357. return this._boundingBias;
  28358. },
  28359. set: function (value) {
  28360. if (this._boundingBias && this._boundingBias.equals(value)) {
  28361. return;
  28362. }
  28363. this._boundingBias = value.clone();
  28364. this.updateBoundingInfo(true, null);
  28365. },
  28366. enumerable: true,
  28367. configurable: true
  28368. });
  28369. Object.defineProperty(Geometry.prototype, "extend", {
  28370. get: function () {
  28371. return this._extend;
  28372. },
  28373. enumerable: true,
  28374. configurable: true
  28375. });
  28376. Geometry.prototype.getScene = function () {
  28377. return this._scene;
  28378. };
  28379. Geometry.prototype.getEngine = function () {
  28380. return this._engine;
  28381. };
  28382. Geometry.prototype.isReady = function () {
  28383. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28384. };
  28385. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28386. get: function () {
  28387. for (var index = 0; index < this._meshes.length; index++) {
  28388. if (!this._meshes[index].doNotSerialize) {
  28389. return false;
  28390. }
  28391. }
  28392. return true;
  28393. },
  28394. enumerable: true,
  28395. configurable: true
  28396. });
  28397. Geometry.prototype._rebuild = function () {
  28398. if (this._vertexArrayObjects) {
  28399. this._vertexArrayObjects = {};
  28400. }
  28401. // Index buffer
  28402. if (this._meshes.length !== 0 && this._indices) {
  28403. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28404. }
  28405. // Vertex buffers
  28406. for (var key in this._vertexBuffers) {
  28407. var vertexBuffer = this._vertexBuffers[key];
  28408. vertexBuffer._rebuild();
  28409. }
  28410. };
  28411. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28412. vertexData.applyToGeometry(this, updatable);
  28413. this.notifyUpdate();
  28414. };
  28415. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28416. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28417. this.setVerticesBuffer(buffer);
  28418. };
  28419. Geometry.prototype.removeVerticesData = function (kind) {
  28420. if (this._vertexBuffers[kind]) {
  28421. this._vertexBuffers[kind].dispose();
  28422. delete this._vertexBuffers[kind];
  28423. }
  28424. };
  28425. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28426. var kind = buffer.getKind();
  28427. if (this._vertexBuffers[kind]) {
  28428. this._vertexBuffers[kind].dispose();
  28429. }
  28430. this._vertexBuffers[kind] = buffer;
  28431. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28432. var data = buffer.getData();
  28433. var stride = buffer.getStrideSize();
  28434. this._totalVertices = data.length / stride;
  28435. this.updateExtend(data, stride);
  28436. this._resetPointsArrayCache();
  28437. var meshes = this._meshes;
  28438. var numOfMeshes = meshes.length;
  28439. for (var index = 0; index < numOfMeshes; index++) {
  28440. var mesh = meshes[index];
  28441. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28442. mesh._createGlobalSubMesh(false);
  28443. mesh.computeWorldMatrix(true);
  28444. }
  28445. }
  28446. this.notifyUpdate(kind);
  28447. if (this._vertexArrayObjects) {
  28448. this._disposeVertexArrayObjects();
  28449. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28450. }
  28451. };
  28452. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28453. var vertexBuffer = this.getVertexBuffer(kind);
  28454. if (!vertexBuffer) {
  28455. return;
  28456. }
  28457. vertexBuffer.updateDirectly(data, offset);
  28458. this.notifyUpdate(kind);
  28459. };
  28460. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28461. var vertexBuffer = this.getVertexBuffer(kind);
  28462. if (!vertexBuffer) {
  28463. return;
  28464. }
  28465. vertexBuffer.update(data);
  28466. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28467. var stride = vertexBuffer.getStrideSize();
  28468. this._totalVertices = data.length / stride;
  28469. this.updateBoundingInfo(updateExtends, data);
  28470. }
  28471. this.notifyUpdate(kind);
  28472. };
  28473. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28474. if (updateExtends) {
  28475. this.updateExtend(data);
  28476. }
  28477. var meshes = this._meshes;
  28478. var numOfMeshes = meshes.length;
  28479. this._resetPointsArrayCache();
  28480. for (var index = 0; index < numOfMeshes; index++) {
  28481. var mesh = meshes[index];
  28482. if (updateExtends) {
  28483. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28484. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28485. var subMesh = mesh.subMeshes[subIndex];
  28486. subMesh.refreshBoundingInfo();
  28487. }
  28488. }
  28489. }
  28490. };
  28491. Geometry.prototype._bind = function (effect, indexToBind) {
  28492. if (indexToBind === void 0) { indexToBind = undefined; }
  28493. if (indexToBind === undefined) {
  28494. indexToBind = this._indexBuffer;
  28495. }
  28496. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28497. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28498. return;
  28499. }
  28500. // Using VAO
  28501. if (!this._vertexArrayObjects[effect.key]) {
  28502. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28503. }
  28504. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28505. };
  28506. Geometry.prototype.getTotalVertices = function () {
  28507. if (!this.isReady()) {
  28508. return 0;
  28509. }
  28510. return this._totalVertices;
  28511. };
  28512. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28513. var vertexBuffer = this.getVertexBuffer(kind);
  28514. if (!vertexBuffer) {
  28515. return null;
  28516. }
  28517. var orig = vertexBuffer.getData();
  28518. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28519. return orig;
  28520. }
  28521. else {
  28522. var len = orig.length;
  28523. var copy = [];
  28524. for (var i = 0; i < len; i++) {
  28525. copy.push(orig[i]);
  28526. }
  28527. return copy;
  28528. }
  28529. };
  28530. Geometry.prototype.getVertexBuffer = function (kind) {
  28531. if (!this.isReady()) {
  28532. return null;
  28533. }
  28534. return this._vertexBuffers[kind];
  28535. };
  28536. Geometry.prototype.getVertexBuffers = function () {
  28537. if (!this.isReady()) {
  28538. return null;
  28539. }
  28540. return this._vertexBuffers;
  28541. };
  28542. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28543. if (!this._vertexBuffers) {
  28544. if (this._delayInfo) {
  28545. return this._delayInfo.indexOf(kind) !== -1;
  28546. }
  28547. return false;
  28548. }
  28549. return this._vertexBuffers[kind] !== undefined;
  28550. };
  28551. Geometry.prototype.getVerticesDataKinds = function () {
  28552. var result = [];
  28553. var kind;
  28554. if (!this._vertexBuffers && this._delayInfo) {
  28555. for (kind in this._delayInfo) {
  28556. result.push(kind);
  28557. }
  28558. }
  28559. else {
  28560. for (kind in this._vertexBuffers) {
  28561. result.push(kind);
  28562. }
  28563. }
  28564. return result;
  28565. };
  28566. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28567. if (this._indexBuffer) {
  28568. this._engine._releaseBuffer(this._indexBuffer);
  28569. }
  28570. this._disposeVertexArrayObjects();
  28571. this._indices = indices;
  28572. if (this._meshes.length !== 0 && this._indices) {
  28573. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28574. }
  28575. if (totalVertices !== undefined) {
  28576. this._totalVertices = totalVertices;
  28577. }
  28578. var meshes = this._meshes;
  28579. var numOfMeshes = meshes.length;
  28580. for (var index = 0; index < numOfMeshes; index++) {
  28581. meshes[index]._createGlobalSubMesh(true);
  28582. }
  28583. this.notifyUpdate();
  28584. };
  28585. Geometry.prototype.getTotalIndices = function () {
  28586. if (!this.isReady()) {
  28587. return 0;
  28588. }
  28589. return this._indices.length;
  28590. };
  28591. Geometry.prototype.getIndices = function (copyWhenShared) {
  28592. if (!this.isReady()) {
  28593. return null;
  28594. }
  28595. var orig = this._indices;
  28596. if (!copyWhenShared || this._meshes.length === 1) {
  28597. return orig;
  28598. }
  28599. else {
  28600. var len = orig.length;
  28601. var copy = [];
  28602. for (var i = 0; i < len; i++) {
  28603. copy.push(orig[i]);
  28604. }
  28605. return copy;
  28606. }
  28607. };
  28608. Geometry.prototype.getIndexBuffer = function () {
  28609. if (!this.isReady()) {
  28610. return null;
  28611. }
  28612. return this._indexBuffer;
  28613. };
  28614. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28615. if (!effect || !this._vertexArrayObjects) {
  28616. return;
  28617. }
  28618. if (this._vertexArrayObjects[effect.key]) {
  28619. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28620. delete this._vertexArrayObjects[effect.key];
  28621. }
  28622. };
  28623. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28624. var meshes = this._meshes;
  28625. var index = meshes.indexOf(mesh);
  28626. if (index === -1) {
  28627. return;
  28628. }
  28629. meshes.splice(index, 1);
  28630. mesh._geometry = null;
  28631. if (meshes.length === 0 && shouldDispose) {
  28632. this.dispose();
  28633. }
  28634. };
  28635. Geometry.prototype.applyToMesh = function (mesh) {
  28636. if (mesh._geometry === this) {
  28637. return;
  28638. }
  28639. var previousGeometry = mesh._geometry;
  28640. if (previousGeometry) {
  28641. previousGeometry.releaseForMesh(mesh);
  28642. }
  28643. var meshes = this._meshes;
  28644. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28645. mesh._geometry = this;
  28646. this._scene.pushGeometry(this);
  28647. meshes.push(mesh);
  28648. if (this.isReady()) {
  28649. this._applyToMesh(mesh);
  28650. }
  28651. else {
  28652. mesh._boundingInfo = this._boundingInfo;
  28653. }
  28654. };
  28655. Geometry.prototype.updateExtend = function (data, stride) {
  28656. if (data === void 0) { data = null; }
  28657. if (!data) {
  28658. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28659. }
  28660. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28661. };
  28662. Geometry.prototype._applyToMesh = function (mesh) {
  28663. var numOfMeshes = this._meshes.length;
  28664. // vertexBuffers
  28665. for (var kind in this._vertexBuffers) {
  28666. if (numOfMeshes === 1) {
  28667. this._vertexBuffers[kind].create();
  28668. }
  28669. var buffer = this._vertexBuffers[kind].getBuffer();
  28670. if (buffer)
  28671. buffer.references = numOfMeshes;
  28672. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28673. if (!this._extend) {
  28674. this.updateExtend(this._vertexBuffers[kind].getData());
  28675. }
  28676. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28677. mesh._createGlobalSubMesh(false);
  28678. //bounding info was just created again, world matrix should be applied again.
  28679. mesh._updateBoundingInfo();
  28680. }
  28681. }
  28682. // indexBuffer
  28683. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28684. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28685. }
  28686. if (this._indexBuffer) {
  28687. this._indexBuffer.references = numOfMeshes;
  28688. }
  28689. };
  28690. Geometry.prototype.notifyUpdate = function (kind) {
  28691. if (this.onGeometryUpdated) {
  28692. this.onGeometryUpdated(this, kind);
  28693. }
  28694. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28695. var mesh = _a[_i];
  28696. mesh._markSubMeshesAsAttributesDirty();
  28697. }
  28698. };
  28699. Geometry.prototype.load = function (scene, onLoaded) {
  28700. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28701. return;
  28702. }
  28703. if (this.isReady()) {
  28704. if (onLoaded) {
  28705. onLoaded();
  28706. }
  28707. return;
  28708. }
  28709. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28710. this._queueLoad(scene, onLoaded);
  28711. };
  28712. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28713. var _this = this;
  28714. scene._addPendingData(this);
  28715. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28716. _this._delayLoadingFunction(JSON.parse(data), _this);
  28717. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28718. _this._delayInfo = [];
  28719. scene._removePendingData(_this);
  28720. var meshes = _this._meshes;
  28721. var numOfMeshes = meshes.length;
  28722. for (var index = 0; index < numOfMeshes; index++) {
  28723. _this._applyToMesh(meshes[index]);
  28724. }
  28725. if (onLoaded) {
  28726. onLoaded();
  28727. }
  28728. }, function () { }, scene.database);
  28729. };
  28730. /**
  28731. * Invert the geometry to move from a right handed system to a left handed one.
  28732. */
  28733. Geometry.prototype.toLeftHanded = function () {
  28734. // Flip faces
  28735. var tIndices = this.getIndices(false);
  28736. if (tIndices != null && tIndices.length > 0) {
  28737. for (var i = 0; i < tIndices.length; i += 3) {
  28738. var tTemp = tIndices[i + 0];
  28739. tIndices[i + 0] = tIndices[i + 2];
  28740. tIndices[i + 2] = tTemp;
  28741. }
  28742. this.setIndices(tIndices);
  28743. }
  28744. // Negate position.z
  28745. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  28746. if (tPositions != null && tPositions.length > 0) {
  28747. for (var i = 0; i < tPositions.length; i += 3) {
  28748. tPositions[i + 2] = -tPositions[i + 2];
  28749. }
  28750. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  28751. }
  28752. // Negate normal.z
  28753. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  28754. if (tNormals != null && tNormals.length > 0) {
  28755. for (var i = 0; i < tNormals.length; i += 3) {
  28756. tNormals[i + 2] = -tNormals[i + 2];
  28757. }
  28758. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  28759. }
  28760. };
  28761. // Cache
  28762. Geometry.prototype._resetPointsArrayCache = function () {
  28763. this._positions = null;
  28764. };
  28765. Geometry.prototype._generatePointsArray = function () {
  28766. if (this._positions)
  28767. return true;
  28768. this._positions = [];
  28769. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28770. if (!data) {
  28771. return false;
  28772. }
  28773. for (var index = 0; index < data.length; index += 3) {
  28774. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  28775. }
  28776. return true;
  28777. };
  28778. Geometry.prototype.isDisposed = function () {
  28779. return this._isDisposed;
  28780. };
  28781. Geometry.prototype._disposeVertexArrayObjects = function () {
  28782. if (this._vertexArrayObjects) {
  28783. for (var kind in this._vertexArrayObjects) {
  28784. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  28785. }
  28786. this._vertexArrayObjects = {};
  28787. }
  28788. };
  28789. Geometry.prototype.dispose = function () {
  28790. var meshes = this._meshes;
  28791. var numOfMeshes = meshes.length;
  28792. var index;
  28793. for (index = 0; index < numOfMeshes; index++) {
  28794. this.releaseForMesh(meshes[index]);
  28795. }
  28796. this._meshes = [];
  28797. this._disposeVertexArrayObjects();
  28798. for (var kind in this._vertexBuffers) {
  28799. this._vertexBuffers[kind].dispose();
  28800. }
  28801. this._vertexBuffers = {};
  28802. this._totalVertices = 0;
  28803. if (this._indexBuffer) {
  28804. this._engine._releaseBuffer(this._indexBuffer);
  28805. }
  28806. this._indexBuffer = null;
  28807. this._indices = [];
  28808. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28809. this.delayLoadingFile = null;
  28810. this._delayLoadingFunction = null;
  28811. this._delayInfo = [];
  28812. this._boundingInfo = null;
  28813. this._scene.removeGeometry(this);
  28814. this._isDisposed = true;
  28815. };
  28816. Geometry.prototype.copy = function (id) {
  28817. var vertexData = new BABYLON.VertexData();
  28818. vertexData.indices = [];
  28819. var indices = this.getIndices();
  28820. for (var index = 0; index < indices.length; index++) {
  28821. vertexData.indices.push(indices[index]);
  28822. }
  28823. var updatable = false;
  28824. var stopChecking = false;
  28825. var kind;
  28826. for (kind in this._vertexBuffers) {
  28827. // using slice() to make a copy of the array and not just reference it
  28828. var data = this.getVerticesData(kind);
  28829. if (data instanceof Float32Array) {
  28830. vertexData.set(new Float32Array(data), kind);
  28831. }
  28832. else {
  28833. vertexData.set(data.slice(0), kind);
  28834. }
  28835. if (!stopChecking) {
  28836. updatable = this.getVertexBuffer(kind).isUpdatable();
  28837. stopChecking = !updatable;
  28838. }
  28839. }
  28840. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28841. geometry.delayLoadState = this.delayLoadState;
  28842. geometry.delayLoadingFile = this.delayLoadingFile;
  28843. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28844. for (kind in this._delayInfo) {
  28845. geometry._delayInfo = geometry._delayInfo || [];
  28846. geometry._delayInfo.push(kind);
  28847. }
  28848. // Bounding info
  28849. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28850. return geometry;
  28851. };
  28852. Geometry.prototype.serialize = function () {
  28853. var serializationObject = {};
  28854. serializationObject.id = this.id;
  28855. serializationObject.updatable = this._updatable;
  28856. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28857. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28858. }
  28859. return serializationObject;
  28860. };
  28861. Geometry.prototype.toNumberArray = function (origin) {
  28862. if (Array.isArray(origin)) {
  28863. return origin;
  28864. }
  28865. else {
  28866. return Array.prototype.slice.call(origin);
  28867. }
  28868. };
  28869. Geometry.prototype.serializeVerticeData = function () {
  28870. var serializationObject = this.serialize();
  28871. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28872. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  28873. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  28874. serializationObject.positions._updatable = true;
  28875. }
  28876. }
  28877. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28878. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  28879. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  28880. serializationObject.normals._updatable = true;
  28881. }
  28882. }
  28883. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28884. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  28885. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  28886. serializationObject.uvs._updatable = true;
  28887. }
  28888. }
  28889. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28890. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  28891. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  28892. serializationObject.uv2s._updatable = true;
  28893. }
  28894. }
  28895. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28896. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  28897. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  28898. serializationObject.uv3s._updatable = true;
  28899. }
  28900. }
  28901. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28902. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  28903. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  28904. serializationObject.uv4s._updatable = true;
  28905. }
  28906. }
  28907. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28908. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  28909. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  28910. serializationObject.uv5s._updatable = true;
  28911. }
  28912. }
  28913. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28914. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  28915. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  28916. serializationObject.uv6s._updatable = true;
  28917. }
  28918. }
  28919. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28920. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  28921. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  28922. serializationObject.colors._updatable = true;
  28923. }
  28924. }
  28925. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28926. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  28927. serializationObject.matricesIndices._isExpanded = true;
  28928. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  28929. serializationObject.matricesIndices._updatable = true;
  28930. }
  28931. }
  28932. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28933. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  28934. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  28935. serializationObject.matricesWeights._updatable = true;
  28936. }
  28937. }
  28938. serializationObject.indices = this.toNumberArray(this.getIndices());
  28939. return serializationObject;
  28940. };
  28941. // Statics
  28942. Geometry.ExtractFromMesh = function (mesh, id) {
  28943. var geometry = mesh._geometry;
  28944. if (!geometry) {
  28945. return null;
  28946. }
  28947. return geometry.copy(id);
  28948. };
  28949. /**
  28950. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  28951. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28952. * Be aware Math.random() could cause collisions, but:
  28953. * "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"
  28954. */
  28955. Geometry.RandomId = function () {
  28956. return BABYLON.Tools.RandomId();
  28957. };
  28958. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28959. var scene = mesh.getScene();
  28960. // Geometry
  28961. var geometryId = parsedGeometry.geometryId;
  28962. if (geometryId) {
  28963. var geometry = scene.getGeometryByID(geometryId);
  28964. if (geometry) {
  28965. geometry.applyToMesh(mesh);
  28966. }
  28967. }
  28968. else if (parsedGeometry instanceof ArrayBuffer) {
  28969. var binaryInfo = mesh._binaryInfo;
  28970. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28971. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28972. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28973. }
  28974. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28975. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28976. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28977. }
  28978. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28979. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28980. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28981. }
  28982. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28983. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28984. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28985. }
  28986. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28987. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28988. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28989. }
  28990. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28991. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28992. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28993. }
  28994. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28995. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28996. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28997. }
  28998. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28999. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29000. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29001. }
  29002. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29003. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29004. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29005. }
  29006. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29007. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29008. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29009. }
  29010. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29011. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29012. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29013. }
  29014. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29015. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29016. mesh.setIndices(indicesData);
  29017. }
  29018. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29019. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29020. mesh.subMeshes = [];
  29021. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29022. var materialIndex = subMeshesData[(i * 5) + 0];
  29023. var verticesStart = subMeshesData[(i * 5) + 1];
  29024. var verticesCount = subMeshesData[(i * 5) + 2];
  29025. var indexStart = subMeshesData[(i * 5) + 3];
  29026. var indexCount = subMeshesData[(i * 5) + 4];
  29027. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29028. }
  29029. }
  29030. }
  29031. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29032. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29033. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29034. if (parsedGeometry.uvs) {
  29035. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29036. }
  29037. if (parsedGeometry.uvs2) {
  29038. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29039. }
  29040. if (parsedGeometry.uvs3) {
  29041. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29042. }
  29043. if (parsedGeometry.uvs4) {
  29044. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29045. }
  29046. if (parsedGeometry.uvs5) {
  29047. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29048. }
  29049. if (parsedGeometry.uvs6) {
  29050. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29051. }
  29052. if (parsedGeometry.colors) {
  29053. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29054. }
  29055. if (parsedGeometry.matricesIndices) {
  29056. if (!parsedGeometry.matricesIndices._isExpanded) {
  29057. var floatIndices = [];
  29058. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29059. var matricesIndex = parsedGeometry.matricesIndices[i];
  29060. floatIndices.push(matricesIndex & 0x000000FF);
  29061. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29062. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29063. floatIndices.push(matricesIndex >> 24);
  29064. }
  29065. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29066. }
  29067. else {
  29068. delete parsedGeometry.matricesIndices._isExpanded;
  29069. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29070. }
  29071. }
  29072. if (parsedGeometry.matricesIndicesExtra) {
  29073. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29074. var floatIndices = [];
  29075. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29076. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29077. floatIndices.push(matricesIndex & 0x000000FF);
  29078. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29079. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29080. floatIndices.push(matricesIndex >> 24);
  29081. }
  29082. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29083. }
  29084. else {
  29085. delete parsedGeometry.matricesIndices._isExpanded;
  29086. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29087. }
  29088. }
  29089. if (parsedGeometry.matricesWeights) {
  29090. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29091. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29092. }
  29093. if (parsedGeometry.matricesWeightsExtra) {
  29094. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29095. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29096. }
  29097. mesh.setIndices(parsedGeometry.indices);
  29098. }
  29099. // SubMeshes
  29100. if (parsedGeometry.subMeshes) {
  29101. mesh.subMeshes = [];
  29102. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29103. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29104. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29105. }
  29106. }
  29107. // Flat shading
  29108. if (mesh._shouldGenerateFlatShading) {
  29109. mesh.convertToFlatShadedMesh();
  29110. delete mesh._shouldGenerateFlatShading;
  29111. }
  29112. // Update
  29113. mesh.computeWorldMatrix(true);
  29114. // Octree
  29115. if (scene['_selectionOctree']) {
  29116. scene['_selectionOctree'].addMesh(mesh);
  29117. }
  29118. };
  29119. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29120. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29121. return;
  29122. }
  29123. var size = matricesWeights.length;
  29124. for (var i = 0; i < size; i += influencers) {
  29125. var weight = 0;
  29126. var biggerIndex = i;
  29127. var biggerWeight = 0;
  29128. for (var j = 0; j < influencers - 1; j++) {
  29129. weight += matricesWeights[i + j];
  29130. if (matricesWeights[i + j] > biggerWeight) {
  29131. biggerWeight = matricesWeights[i + j];
  29132. biggerIndex = i + j;
  29133. }
  29134. }
  29135. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29136. }
  29137. };
  29138. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29139. if (scene.getGeometryByID(parsedVertexData.id)) {
  29140. return null; // null since geometry could be something else than a box...
  29141. }
  29142. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29143. if (BABYLON.Tags) {
  29144. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29145. }
  29146. if (parsedVertexData.delayLoadingFile) {
  29147. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29148. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29149. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29150. geometry._delayInfo = [];
  29151. if (parsedVertexData.hasUVs) {
  29152. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29153. }
  29154. if (parsedVertexData.hasUVs2) {
  29155. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29156. }
  29157. if (parsedVertexData.hasUVs3) {
  29158. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29159. }
  29160. if (parsedVertexData.hasUVs4) {
  29161. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29162. }
  29163. if (parsedVertexData.hasUVs5) {
  29164. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29165. }
  29166. if (parsedVertexData.hasUVs6) {
  29167. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29168. }
  29169. if (parsedVertexData.hasColors) {
  29170. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29171. }
  29172. if (parsedVertexData.hasMatricesIndices) {
  29173. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29174. }
  29175. if (parsedVertexData.hasMatricesWeights) {
  29176. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29177. }
  29178. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29179. }
  29180. else {
  29181. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29182. }
  29183. scene.pushGeometry(geometry, true);
  29184. return geometry;
  29185. };
  29186. return Geometry;
  29187. }());
  29188. BABYLON.Geometry = Geometry;
  29189. /////// Primitives //////////////////////////////////////////////
  29190. (function (Geometry) {
  29191. var Primitives;
  29192. (function (Primitives) {
  29193. /// Abstract class
  29194. var _Primitive = (function (_super) {
  29195. __extends(_Primitive, _super);
  29196. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29197. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29198. _this._canBeRegenerated = _canBeRegenerated;
  29199. _this._beingRegenerated = true;
  29200. _this.regenerate();
  29201. _this._beingRegenerated = false;
  29202. return _this;
  29203. }
  29204. _Primitive.prototype.canBeRegenerated = function () {
  29205. return this._canBeRegenerated;
  29206. };
  29207. _Primitive.prototype.regenerate = function () {
  29208. if (!this._canBeRegenerated) {
  29209. return;
  29210. }
  29211. this._beingRegenerated = true;
  29212. this.setAllVerticesData(this._regenerateVertexData(), false);
  29213. this._beingRegenerated = false;
  29214. };
  29215. _Primitive.prototype.asNewGeometry = function (id) {
  29216. return _super.prototype.copy.call(this, id);
  29217. };
  29218. // overrides
  29219. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29220. if (!this._beingRegenerated) {
  29221. return;
  29222. }
  29223. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29224. };
  29225. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29226. if (!this._beingRegenerated) {
  29227. return;
  29228. }
  29229. _super.prototype.setVerticesData.call(this, kind, data, false);
  29230. };
  29231. // to override
  29232. // protected
  29233. _Primitive.prototype._regenerateVertexData = function () {
  29234. throw new Error("Abstract method");
  29235. };
  29236. _Primitive.prototype.copy = function (id) {
  29237. throw new Error("Must be overriden in sub-classes.");
  29238. };
  29239. _Primitive.prototype.serialize = function () {
  29240. var serializationObject = _super.prototype.serialize.call(this);
  29241. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29242. return serializationObject;
  29243. };
  29244. return _Primitive;
  29245. }(Geometry));
  29246. Primitives._Primitive = _Primitive;
  29247. var Ribbon = (function (_super) {
  29248. __extends(Ribbon, _super);
  29249. // Members
  29250. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29251. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29252. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29253. _this.pathArray = pathArray;
  29254. _this.closeArray = closeArray;
  29255. _this.closePath = closePath;
  29256. _this.offset = offset;
  29257. _this.side = side;
  29258. return _this;
  29259. }
  29260. Ribbon.prototype._regenerateVertexData = function () {
  29261. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29262. };
  29263. Ribbon.prototype.copy = function (id) {
  29264. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29265. };
  29266. return Ribbon;
  29267. }(_Primitive));
  29268. Primitives.Ribbon = Ribbon;
  29269. var Box = (function (_super) {
  29270. __extends(Box, _super);
  29271. // Members
  29272. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29273. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29274. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29275. _this.size = size;
  29276. _this.side = side;
  29277. return _this;
  29278. }
  29279. Box.prototype._regenerateVertexData = function () {
  29280. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29281. };
  29282. Box.prototype.copy = function (id) {
  29283. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29284. };
  29285. Box.prototype.serialize = function () {
  29286. var serializationObject = _super.prototype.serialize.call(this);
  29287. serializationObject.size = this.size;
  29288. return serializationObject;
  29289. };
  29290. Box.Parse = function (parsedBox, scene) {
  29291. if (scene.getGeometryByID(parsedBox.id)) {
  29292. return null; // null since geometry could be something else than a box...
  29293. }
  29294. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29295. if (BABYLON.Tags) {
  29296. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29297. }
  29298. scene.pushGeometry(box, true);
  29299. return box;
  29300. };
  29301. return Box;
  29302. }(_Primitive));
  29303. Primitives.Box = Box;
  29304. var Sphere = (function (_super) {
  29305. __extends(Sphere, _super);
  29306. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29307. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29308. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29309. _this.segments = segments;
  29310. _this.diameter = diameter;
  29311. _this.side = side;
  29312. return _this;
  29313. }
  29314. Sphere.prototype._regenerateVertexData = function () {
  29315. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29316. };
  29317. Sphere.prototype.copy = function (id) {
  29318. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29319. };
  29320. Sphere.prototype.serialize = function () {
  29321. var serializationObject = _super.prototype.serialize.call(this);
  29322. serializationObject.segments = this.segments;
  29323. serializationObject.diameter = this.diameter;
  29324. return serializationObject;
  29325. };
  29326. Sphere.Parse = function (parsedSphere, scene) {
  29327. if (scene.getGeometryByID(parsedSphere.id)) {
  29328. return null; // null since geometry could be something else than a sphere...
  29329. }
  29330. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29331. if (BABYLON.Tags) {
  29332. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29333. }
  29334. scene.pushGeometry(sphere, true);
  29335. return sphere;
  29336. };
  29337. return Sphere;
  29338. }(_Primitive));
  29339. Primitives.Sphere = Sphere;
  29340. var Disc = (function (_super) {
  29341. __extends(Disc, _super);
  29342. // Members
  29343. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29344. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29345. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29346. _this.radius = radius;
  29347. _this.tessellation = tessellation;
  29348. _this.side = side;
  29349. return _this;
  29350. }
  29351. Disc.prototype._regenerateVertexData = function () {
  29352. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29353. };
  29354. Disc.prototype.copy = function (id) {
  29355. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29356. };
  29357. return Disc;
  29358. }(_Primitive));
  29359. Primitives.Disc = Disc;
  29360. var Cylinder = (function (_super) {
  29361. __extends(Cylinder, _super);
  29362. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29363. if (subdivisions === void 0) { subdivisions = 1; }
  29364. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29365. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29366. _this.height = height;
  29367. _this.diameterTop = diameterTop;
  29368. _this.diameterBottom = diameterBottom;
  29369. _this.tessellation = tessellation;
  29370. _this.subdivisions = subdivisions;
  29371. _this.side = side;
  29372. return _this;
  29373. }
  29374. Cylinder.prototype._regenerateVertexData = function () {
  29375. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29376. };
  29377. Cylinder.prototype.copy = function (id) {
  29378. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29379. };
  29380. Cylinder.prototype.serialize = function () {
  29381. var serializationObject = _super.prototype.serialize.call(this);
  29382. serializationObject.height = this.height;
  29383. serializationObject.diameterTop = this.diameterTop;
  29384. serializationObject.diameterBottom = this.diameterBottom;
  29385. serializationObject.tessellation = this.tessellation;
  29386. return serializationObject;
  29387. };
  29388. Cylinder.Parse = function (parsedCylinder, scene) {
  29389. if (scene.getGeometryByID(parsedCylinder.id)) {
  29390. return null; // null since geometry could be something else than a cylinder...
  29391. }
  29392. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29393. if (BABYLON.Tags) {
  29394. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29395. }
  29396. scene.pushGeometry(cylinder, true);
  29397. return cylinder;
  29398. };
  29399. return Cylinder;
  29400. }(_Primitive));
  29401. Primitives.Cylinder = Cylinder;
  29402. var Torus = (function (_super) {
  29403. __extends(Torus, _super);
  29404. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29405. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29406. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29407. _this.diameter = diameter;
  29408. _this.thickness = thickness;
  29409. _this.tessellation = tessellation;
  29410. _this.side = side;
  29411. return _this;
  29412. }
  29413. Torus.prototype._regenerateVertexData = function () {
  29414. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29415. };
  29416. Torus.prototype.copy = function (id) {
  29417. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29418. };
  29419. Torus.prototype.serialize = function () {
  29420. var serializationObject = _super.prototype.serialize.call(this);
  29421. serializationObject.diameter = this.diameter;
  29422. serializationObject.thickness = this.thickness;
  29423. serializationObject.tessellation = this.tessellation;
  29424. return serializationObject;
  29425. };
  29426. Torus.Parse = function (parsedTorus, scene) {
  29427. if (scene.getGeometryByID(parsedTorus.id)) {
  29428. return null; // null since geometry could be something else than a torus...
  29429. }
  29430. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29431. if (BABYLON.Tags) {
  29432. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29433. }
  29434. scene.pushGeometry(torus, true);
  29435. return torus;
  29436. };
  29437. return Torus;
  29438. }(_Primitive));
  29439. Primitives.Torus = Torus;
  29440. var Ground = (function (_super) {
  29441. __extends(Ground, _super);
  29442. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29443. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29444. _this.width = width;
  29445. _this.height = height;
  29446. _this.subdivisions = subdivisions;
  29447. return _this;
  29448. }
  29449. Ground.prototype._regenerateVertexData = function () {
  29450. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29451. };
  29452. Ground.prototype.copy = function (id) {
  29453. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29454. };
  29455. Ground.prototype.serialize = function () {
  29456. var serializationObject = _super.prototype.serialize.call(this);
  29457. serializationObject.width = this.width;
  29458. serializationObject.height = this.height;
  29459. serializationObject.subdivisions = this.subdivisions;
  29460. return serializationObject;
  29461. };
  29462. Ground.Parse = function (parsedGround, scene) {
  29463. if (scene.getGeometryByID(parsedGround.id)) {
  29464. return null; // null since geometry could be something else than a ground...
  29465. }
  29466. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29467. if (BABYLON.Tags) {
  29468. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29469. }
  29470. scene.pushGeometry(ground, true);
  29471. return ground;
  29472. };
  29473. return Ground;
  29474. }(_Primitive));
  29475. Primitives.Ground = Ground;
  29476. var TiledGround = (function (_super) {
  29477. __extends(TiledGround, _super);
  29478. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29479. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29480. _this.xmin = xmin;
  29481. _this.zmin = zmin;
  29482. _this.xmax = xmax;
  29483. _this.zmax = zmax;
  29484. _this.subdivisions = subdivisions;
  29485. _this.precision = precision;
  29486. return _this;
  29487. }
  29488. TiledGround.prototype._regenerateVertexData = function () {
  29489. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29490. };
  29491. TiledGround.prototype.copy = function (id) {
  29492. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29493. };
  29494. return TiledGround;
  29495. }(_Primitive));
  29496. Primitives.TiledGround = TiledGround;
  29497. var Plane = (function (_super) {
  29498. __extends(Plane, _super);
  29499. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29500. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29501. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29502. _this.size = size;
  29503. _this.side = side;
  29504. return _this;
  29505. }
  29506. Plane.prototype._regenerateVertexData = function () {
  29507. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29508. };
  29509. Plane.prototype.copy = function (id) {
  29510. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29511. };
  29512. Plane.prototype.serialize = function () {
  29513. var serializationObject = _super.prototype.serialize.call(this);
  29514. serializationObject.size = this.size;
  29515. return serializationObject;
  29516. };
  29517. Plane.Parse = function (parsedPlane, scene) {
  29518. if (scene.getGeometryByID(parsedPlane.id)) {
  29519. return null; // null since geometry could be something else than a ground...
  29520. }
  29521. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29522. if (BABYLON.Tags) {
  29523. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29524. }
  29525. scene.pushGeometry(plane, true);
  29526. return plane;
  29527. };
  29528. return Plane;
  29529. }(_Primitive));
  29530. Primitives.Plane = Plane;
  29531. var TorusKnot = (function (_super) {
  29532. __extends(TorusKnot, _super);
  29533. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29534. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29535. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29536. _this.radius = radius;
  29537. _this.tube = tube;
  29538. _this.radialSegments = radialSegments;
  29539. _this.tubularSegments = tubularSegments;
  29540. _this.p = p;
  29541. _this.q = q;
  29542. _this.side = side;
  29543. return _this;
  29544. }
  29545. TorusKnot.prototype._regenerateVertexData = function () {
  29546. 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 });
  29547. };
  29548. TorusKnot.prototype.copy = function (id) {
  29549. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29550. };
  29551. TorusKnot.prototype.serialize = function () {
  29552. var serializationObject = _super.prototype.serialize.call(this);
  29553. serializationObject.radius = this.radius;
  29554. serializationObject.tube = this.tube;
  29555. serializationObject.radialSegments = this.radialSegments;
  29556. serializationObject.tubularSegments = this.tubularSegments;
  29557. serializationObject.p = this.p;
  29558. serializationObject.q = this.q;
  29559. return serializationObject;
  29560. };
  29561. ;
  29562. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29563. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29564. return null; // null since geometry could be something else than a ground...
  29565. }
  29566. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29567. if (BABYLON.Tags) {
  29568. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29569. }
  29570. scene.pushGeometry(torusKnot, true);
  29571. return torusKnot;
  29572. };
  29573. return TorusKnot;
  29574. }(_Primitive));
  29575. Primitives.TorusKnot = TorusKnot;
  29576. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29577. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29578. })(BABYLON || (BABYLON = {}));
  29579. //# sourceMappingURL=babylon.geometry.js.map
  29580. var BABYLON;
  29581. (function (BABYLON) {
  29582. var PostProcessManager = (function () {
  29583. function PostProcessManager(scene) {
  29584. this._vertexBuffers = {};
  29585. this._scene = scene;
  29586. }
  29587. PostProcessManager.prototype._prepareBuffers = function () {
  29588. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29589. return;
  29590. }
  29591. // VBO
  29592. var vertices = [];
  29593. vertices.push(1, 1);
  29594. vertices.push(-1, 1);
  29595. vertices.push(-1, -1);
  29596. vertices.push(1, -1);
  29597. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29598. // Indices
  29599. var indices = [];
  29600. indices.push(0);
  29601. indices.push(1);
  29602. indices.push(2);
  29603. indices.push(0);
  29604. indices.push(2);
  29605. indices.push(3);
  29606. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29607. };
  29608. // Methods
  29609. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29610. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29611. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29612. return false;
  29613. }
  29614. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29615. return true;
  29616. };
  29617. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  29618. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  29619. var engine = this._scene.getEngine();
  29620. for (var index = 0; index < postProcesses.length; index++) {
  29621. if (index < postProcesses.length - 1) {
  29622. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29623. }
  29624. else {
  29625. if (targetTexture) {
  29626. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  29627. }
  29628. else {
  29629. engine.restoreDefaultFramebuffer();
  29630. }
  29631. }
  29632. var pp = postProcesses[index];
  29633. var effect = pp.apply();
  29634. if (effect) {
  29635. pp.onBeforeRenderObservable.notifyObservers(effect);
  29636. // VBOs
  29637. this._prepareBuffers();
  29638. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29639. // Draw order
  29640. engine.draw(true, 0, 6);
  29641. pp.onAfterRenderObservable.notifyObservers(effect);
  29642. }
  29643. }
  29644. // Restore depth buffer
  29645. engine.setDepthBuffer(true);
  29646. engine.setDepthWrite(true);
  29647. };
  29648. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29649. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29650. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29651. return;
  29652. }
  29653. var engine = this._scene.getEngine();
  29654. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29655. if (index < len - 1) {
  29656. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29657. }
  29658. else {
  29659. if (targetTexture) {
  29660. engine.bindFramebuffer(targetTexture, faceIndex);
  29661. }
  29662. else {
  29663. engine.restoreDefaultFramebuffer();
  29664. }
  29665. }
  29666. if (doNotPresent) {
  29667. break;
  29668. }
  29669. var pp = postProcesses[index];
  29670. var effect = pp.apply();
  29671. if (effect) {
  29672. pp.onBeforeRenderObservable.notifyObservers(effect);
  29673. // VBOs
  29674. this._prepareBuffers();
  29675. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29676. // Draw order
  29677. engine.draw(true, 0, 6);
  29678. pp.onAfterRenderObservable.notifyObservers(effect);
  29679. }
  29680. }
  29681. // Restore states
  29682. engine.setDepthBuffer(true);
  29683. engine.setDepthWrite(true);
  29684. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29685. };
  29686. PostProcessManager.prototype.dispose = function () {
  29687. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29688. if (buffer) {
  29689. buffer.dispose();
  29690. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29691. }
  29692. if (this._indexBuffer) {
  29693. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29694. this._indexBuffer = null;
  29695. }
  29696. };
  29697. return PostProcessManager;
  29698. }());
  29699. BABYLON.PostProcessManager = PostProcessManager;
  29700. })(BABYLON || (BABYLON = {}));
  29701. //# sourceMappingURL=babylon.postProcessManager.js.map
  29702. var BABYLON;
  29703. (function (BABYLON) {
  29704. /**
  29705. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29706. */
  29707. var PerformanceMonitor = (function () {
  29708. /**
  29709. * constructor
  29710. * @param frameSampleSize The number of samples required to saturate the sliding window
  29711. */
  29712. function PerformanceMonitor(frameSampleSize) {
  29713. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29714. this._enabled = true;
  29715. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29716. }
  29717. /**
  29718. * Samples current frame
  29719. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29720. */
  29721. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29722. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29723. if (!this._enabled)
  29724. return;
  29725. if (this._lastFrameTimeMs != null) {
  29726. var dt = timeMs - this._lastFrameTimeMs;
  29727. this._rollingFrameTime.add(dt);
  29728. }
  29729. this._lastFrameTimeMs = timeMs;
  29730. };
  29731. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  29732. /**
  29733. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29734. * @return Average frame time in milliseconds
  29735. */
  29736. get: function () {
  29737. return this._rollingFrameTime.average;
  29738. },
  29739. enumerable: true,
  29740. configurable: true
  29741. });
  29742. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  29743. /**
  29744. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29745. * @return Frame time variance in milliseconds squared
  29746. */
  29747. get: function () {
  29748. return this._rollingFrameTime.variance;
  29749. },
  29750. enumerable: true,
  29751. configurable: true
  29752. });
  29753. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  29754. /**
  29755. * Returns the frame time of the most recent frame
  29756. * @return Frame time in milliseconds
  29757. */
  29758. get: function () {
  29759. return this._rollingFrameTime.history(0);
  29760. },
  29761. enumerable: true,
  29762. configurable: true
  29763. });
  29764. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  29765. /**
  29766. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  29767. * @return Framerate in frames per second
  29768. */
  29769. get: function () {
  29770. return 1000.0 / this._rollingFrameTime.average;
  29771. },
  29772. enumerable: true,
  29773. configurable: true
  29774. });
  29775. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  29776. /**
  29777. * Returns the average framerate in frames per second using the most recent frame time
  29778. * @return Framerate in frames per second
  29779. */
  29780. get: function () {
  29781. return 1000.0 / this._rollingFrameTime.history(0);
  29782. },
  29783. enumerable: true,
  29784. configurable: true
  29785. });
  29786. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  29787. /**
  29788. * Returns true if enough samples have been taken to completely fill the sliding window
  29789. * @return true if saturated
  29790. */
  29791. get: function () {
  29792. return this._rollingFrameTime.isSaturated();
  29793. },
  29794. enumerable: true,
  29795. configurable: true
  29796. });
  29797. /**
  29798. * Enables contributions to the sliding window sample set
  29799. */
  29800. PerformanceMonitor.prototype.enable = function () {
  29801. this._enabled = true;
  29802. };
  29803. /**
  29804. * Disables contributions to the sliding window sample set
  29805. * Samples will not be interpolated over the disabled period
  29806. */
  29807. PerformanceMonitor.prototype.disable = function () {
  29808. this._enabled = false;
  29809. //clear last sample to avoid interpolating over the disabled period when next enabled
  29810. this._lastFrameTimeMs = null;
  29811. this._lastChangeTimeMs = null;
  29812. };
  29813. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  29814. /**
  29815. * Returns true if sampling is enabled
  29816. * @return true if enabled
  29817. */
  29818. get: function () {
  29819. return this._enabled;
  29820. },
  29821. enumerable: true,
  29822. configurable: true
  29823. });
  29824. /**
  29825. * Resets performance monitor
  29826. */
  29827. PerformanceMonitor.prototype.reset = function () {
  29828. //clear last sample to avoid interpolating over the disabled period when next enabled
  29829. this._lastFrameTimeMs = null;
  29830. this._lastChangeTimeMs = null;
  29831. //wipe record
  29832. this._rollingFrameTime.reset();
  29833. };
  29834. return PerformanceMonitor;
  29835. }());
  29836. BABYLON.PerformanceMonitor = PerformanceMonitor;
  29837. /**
  29838. * RollingAverage
  29839. *
  29840. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  29841. */
  29842. var RollingAverage = (function () {
  29843. /**
  29844. * constructor
  29845. * @param length The number of samples required to saturate the sliding window
  29846. */
  29847. function RollingAverage(length) {
  29848. this._samples = new Array(length);
  29849. this.reset();
  29850. }
  29851. /**
  29852. * Adds a sample to the sample set
  29853. * @param v The sample value
  29854. */
  29855. RollingAverage.prototype.add = function (v) {
  29856. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  29857. var delta;
  29858. //we need to check if we've already wrapped round
  29859. if (this.isSaturated()) {
  29860. //remove bottom of stack from mean
  29861. var bottomValue = this._samples[this._pos];
  29862. delta = bottomValue - this.average;
  29863. this.average -= delta / (this._sampleCount - 1);
  29864. this._m2 -= delta * (bottomValue - this.average);
  29865. }
  29866. else {
  29867. this._sampleCount++;
  29868. }
  29869. //add new value to mean
  29870. delta = v - this.average;
  29871. this.average += delta / (this._sampleCount);
  29872. this._m2 += delta * (v - this.average);
  29873. //set the new variance
  29874. this.variance = this._m2 / (this._sampleCount - 1);
  29875. this._samples[this._pos] = v;
  29876. this._pos++;
  29877. this._pos %= this._samples.length; //positive wrap around
  29878. };
  29879. /**
  29880. * Returns previously added values or null if outside of history or outside the sliding window domain
  29881. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  29882. * @return Value previously recorded with add() or null if outside of range
  29883. */
  29884. RollingAverage.prototype.history = function (i) {
  29885. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  29886. return null;
  29887. }
  29888. var i0 = this._wrapPosition(this._pos - 1.0);
  29889. return this._samples[this._wrapPosition(i0 - i)];
  29890. };
  29891. /**
  29892. * Returns true if enough samples have been taken to completely fill the sliding window
  29893. * @return true if sample-set saturated
  29894. */
  29895. RollingAverage.prototype.isSaturated = function () {
  29896. return this._sampleCount >= this._samples.length;
  29897. };
  29898. /**
  29899. * Resets the rolling average (equivalent to 0 samples taken so far)
  29900. */
  29901. RollingAverage.prototype.reset = function () {
  29902. this.average = 0;
  29903. this.variance = 0;
  29904. this._sampleCount = 0;
  29905. this._pos = 0;
  29906. this._m2 = 0;
  29907. };
  29908. /**
  29909. * Wraps a value around the sample range boundaries
  29910. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  29911. * @return Wrapped position in sample range
  29912. */
  29913. RollingAverage.prototype._wrapPosition = function (i) {
  29914. var max = this._samples.length;
  29915. return ((i % max) + max) % max;
  29916. };
  29917. return RollingAverage;
  29918. }());
  29919. BABYLON.RollingAverage = RollingAverage;
  29920. })(BABYLON || (BABYLON = {}));
  29921. //# sourceMappingURL=babylon.performanceMonitor.js.map
  29922. var BABYLON;
  29923. (function (BABYLON) {
  29924. var AnimationRange = (function () {
  29925. function AnimationRange(name, from, to) {
  29926. this.name = name;
  29927. this.from = from;
  29928. this.to = to;
  29929. }
  29930. AnimationRange.prototype.clone = function () {
  29931. return new AnimationRange(this.name, this.from, this.to);
  29932. };
  29933. return AnimationRange;
  29934. }());
  29935. BABYLON.AnimationRange = AnimationRange;
  29936. /**
  29937. * Composed of a frame, and an action function
  29938. */
  29939. var AnimationEvent = (function () {
  29940. function AnimationEvent(frame, action, onlyOnce) {
  29941. this.frame = frame;
  29942. this.action = action;
  29943. this.onlyOnce = onlyOnce;
  29944. this.isDone = false;
  29945. }
  29946. return AnimationEvent;
  29947. }());
  29948. BABYLON.AnimationEvent = AnimationEvent;
  29949. var PathCursor = (function () {
  29950. function PathCursor(path) {
  29951. this.path = path;
  29952. this._onchange = new Array();
  29953. this.value = 0;
  29954. this.animations = new Array();
  29955. }
  29956. PathCursor.prototype.getPoint = function () {
  29957. var point = this.path.getPointAtLengthPosition(this.value);
  29958. return new BABYLON.Vector3(point.x, 0, point.y);
  29959. };
  29960. PathCursor.prototype.moveAhead = function (step) {
  29961. if (step === void 0) { step = 0.002; }
  29962. this.move(step);
  29963. return this;
  29964. };
  29965. PathCursor.prototype.moveBack = function (step) {
  29966. if (step === void 0) { step = 0.002; }
  29967. this.move(-step);
  29968. return this;
  29969. };
  29970. PathCursor.prototype.move = function (step) {
  29971. if (Math.abs(step) > 1) {
  29972. throw "step size should be less than 1.";
  29973. }
  29974. this.value += step;
  29975. this.ensureLimits();
  29976. this.raiseOnChange();
  29977. return this;
  29978. };
  29979. PathCursor.prototype.ensureLimits = function () {
  29980. while (this.value > 1) {
  29981. this.value -= 1;
  29982. }
  29983. while (this.value < 0) {
  29984. this.value += 1;
  29985. }
  29986. return this;
  29987. };
  29988. // used by animation engine
  29989. PathCursor.prototype.markAsDirty = function (propertyName) {
  29990. this.ensureLimits();
  29991. this.raiseOnChange();
  29992. return this;
  29993. };
  29994. PathCursor.prototype.raiseOnChange = function () {
  29995. var _this = this;
  29996. this._onchange.forEach(function (f) { return f(_this); });
  29997. return this;
  29998. };
  29999. PathCursor.prototype.onchange = function (f) {
  30000. this._onchange.push(f);
  30001. return this;
  30002. };
  30003. return PathCursor;
  30004. }());
  30005. BABYLON.PathCursor = PathCursor;
  30006. var Animation = (function () {
  30007. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  30008. this.name = name;
  30009. this.targetProperty = targetProperty;
  30010. this.framePerSecond = framePerSecond;
  30011. this.dataType = dataType;
  30012. this.loopMode = loopMode;
  30013. this.enableBlending = enableBlending;
  30014. this._offsetsCache = {};
  30015. this._highLimitsCache = {};
  30016. this._stopped = false;
  30017. this._blendingFactor = 0;
  30018. // The set of event that will be linked to this animation
  30019. this._events = new Array();
  30020. this.allowMatricesInterpolation = false;
  30021. this.blendingSpeed = 0.01;
  30022. this._ranges = {};
  30023. this.targetPropertyPath = targetProperty.split(".");
  30024. this.dataType = dataType;
  30025. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  30026. }
  30027. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  30028. var dataType = undefined;
  30029. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  30030. dataType = Animation.ANIMATIONTYPE_FLOAT;
  30031. }
  30032. else if (from instanceof BABYLON.Quaternion) {
  30033. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  30034. }
  30035. else if (from instanceof BABYLON.Vector3) {
  30036. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  30037. }
  30038. else if (from instanceof BABYLON.Vector2) {
  30039. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  30040. }
  30041. else if (from instanceof BABYLON.Color3) {
  30042. dataType = Animation.ANIMATIONTYPE_COLOR3;
  30043. }
  30044. else if (from instanceof BABYLON.Size) {
  30045. dataType = Animation.ANIMATIONTYPE_SIZE;
  30046. }
  30047. if (dataType == undefined) {
  30048. return null;
  30049. }
  30050. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  30051. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  30052. animation.setKeys(keys);
  30053. if (easingFunction !== undefined) {
  30054. animation.setEasingFunction(easingFunction);
  30055. }
  30056. return animation;
  30057. };
  30058. /**
  30059. * Sets up an animation.
  30060. * @param property the property to animate
  30061. * @param animationType the animation type to apply
  30062. * @param easingFunction the easing function used in the animation
  30063. * @returns The created animation
  30064. */
  30065. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  30066. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30067. animation.setEasingFunction(easingFunction);
  30068. return animation;
  30069. };
  30070. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30071. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30072. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30073. };
  30074. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30075. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30076. node.animations.push(animation);
  30077. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30078. };
  30079. /**
  30080. * Transition property of the Camera to the target Value.
  30081. * @param property The property to transition
  30082. * @param targetValue The target Value of the property
  30083. * @param host The object where the property to animate belongs
  30084. * @param scene Scene used to run the animation
  30085. * @param frameRate Framerate (in frame/s) to use
  30086. * @param transition The transition type we want to use
  30087. * @param duration The duration of the animation, in milliseconds
  30088. * @param onAnimationEnd Call back trigger at the end of the animation.
  30089. */
  30090. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  30091. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  30092. if (duration <= 0) {
  30093. host[property] = targetValue;
  30094. if (onAnimationEnd) {
  30095. onAnimationEnd();
  30096. }
  30097. return;
  30098. }
  30099. var endFrame = frameRate * (duration / 1000);
  30100. transition.setKeys([{
  30101. frame: 0,
  30102. value: host[property].clone ? host[property].clone() : host[property]
  30103. },
  30104. {
  30105. frame: endFrame,
  30106. value: targetValue
  30107. }]);
  30108. if (!host.animations) {
  30109. host.animations = [];
  30110. }
  30111. host.animations.push(transition);
  30112. var animation = scene.beginAnimation(host, 0, endFrame, false);
  30113. animation.onAnimationEnd = onAnimationEnd;
  30114. return animation;
  30115. };
  30116. // Methods
  30117. /**
  30118. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30119. */
  30120. Animation.prototype.toString = function (fullDetails) {
  30121. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  30122. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  30123. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  30124. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30125. if (fullDetails) {
  30126. ret += ", Ranges: {";
  30127. var first = true;
  30128. for (var name in this._ranges) {
  30129. if (first) {
  30130. ret += ", ";
  30131. first = false;
  30132. }
  30133. ret += name;
  30134. }
  30135. ret += "}";
  30136. }
  30137. return ret;
  30138. };
  30139. /**
  30140. * Add an event to this animation.
  30141. */
  30142. Animation.prototype.addEvent = function (event) {
  30143. this._events.push(event);
  30144. };
  30145. /**
  30146. * Remove all events found at the given frame
  30147. * @param frame
  30148. */
  30149. Animation.prototype.removeEvents = function (frame) {
  30150. for (var index = 0; index < this._events.length; index++) {
  30151. if (this._events[index].frame === frame) {
  30152. this._events.splice(index, 1);
  30153. index--;
  30154. }
  30155. }
  30156. };
  30157. Animation.prototype.createRange = function (name, from, to) {
  30158. // check name not already in use; could happen for bones after serialized
  30159. if (!this._ranges[name]) {
  30160. this._ranges[name] = new AnimationRange(name, from, to);
  30161. }
  30162. };
  30163. Animation.prototype.deleteRange = function (name, deleteFrames) {
  30164. if (deleteFrames === void 0) { deleteFrames = true; }
  30165. if (this._ranges[name]) {
  30166. if (deleteFrames) {
  30167. var from = this._ranges[name].from;
  30168. var to = this._ranges[name].to;
  30169. // this loop MUST go high to low for multiple splices to work
  30170. for (var key = this._keys.length - 1; key >= 0; key--) {
  30171. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  30172. this._keys.splice(key, 1);
  30173. }
  30174. }
  30175. }
  30176. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30177. }
  30178. };
  30179. Animation.prototype.getRange = function (name) {
  30180. return this._ranges[name];
  30181. };
  30182. Animation.prototype.reset = function () {
  30183. this._offsetsCache = {};
  30184. this._highLimitsCache = {};
  30185. this.currentFrame = 0;
  30186. this._blendingFactor = 0;
  30187. this._originalBlendValue = null;
  30188. };
  30189. Animation.prototype.isStopped = function () {
  30190. return this._stopped;
  30191. };
  30192. Animation.prototype.getKeys = function () {
  30193. return this._keys;
  30194. };
  30195. Animation.prototype.getHighestFrame = function () {
  30196. var ret = 0;
  30197. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  30198. if (ret < this._keys[key].frame) {
  30199. ret = this._keys[key].frame;
  30200. }
  30201. }
  30202. return ret;
  30203. };
  30204. Animation.prototype.getEasingFunction = function () {
  30205. return this._easingFunction;
  30206. };
  30207. Animation.prototype.setEasingFunction = function (easingFunction) {
  30208. this._easingFunction = easingFunction;
  30209. };
  30210. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  30211. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  30212. };
  30213. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30214. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30215. };
  30216. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  30217. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  30218. };
  30219. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30220. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  30221. };
  30222. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  30223. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  30224. };
  30225. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30226. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30227. };
  30228. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  30229. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  30230. };
  30231. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30232. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30233. };
  30234. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  30235. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  30236. };
  30237. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  30238. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  30239. };
  30240. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30241. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30242. };
  30243. Animation.prototype.clone = function () {
  30244. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30245. clone.enableBlending = this.enableBlending;
  30246. clone.blendingSpeed = this.blendingSpeed;
  30247. if (this._keys) {
  30248. clone.setKeys(this._keys);
  30249. }
  30250. if (this._ranges) {
  30251. clone._ranges = {};
  30252. for (var name in this._ranges) {
  30253. clone._ranges[name] = this._ranges[name].clone();
  30254. }
  30255. }
  30256. return clone;
  30257. };
  30258. Animation.prototype.setKeys = function (values) {
  30259. this._keys = values.slice(0);
  30260. this._offsetsCache = {};
  30261. this._highLimitsCache = {};
  30262. };
  30263. Animation.prototype._getKeyValue = function (value) {
  30264. if (typeof value === "function") {
  30265. return value();
  30266. }
  30267. return value;
  30268. };
  30269. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30270. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30271. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30272. }
  30273. this.currentFrame = currentFrame;
  30274. // Try to get a hash to find the right key
  30275. 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));
  30276. if (this._keys[startKeyIndex].frame >= currentFrame) {
  30277. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  30278. startKeyIndex--;
  30279. }
  30280. }
  30281. for (var key = startKeyIndex; key < this._keys.length; key++) {
  30282. var endKey = this._keys[key + 1];
  30283. if (endKey.frame >= currentFrame) {
  30284. var startKey = this._keys[key];
  30285. var startValue = this._getKeyValue(startKey.value);
  30286. var endValue = this._getKeyValue(endKey.value);
  30287. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  30288. var frameDelta = endKey.frame - startKey.frame;
  30289. // gradient : percent of currentFrame between the frame inf and the frame sup
  30290. var gradient = (currentFrame - startKey.frame) / frameDelta;
  30291. // check for easingFunction and correction of gradient
  30292. if (this._easingFunction != null) {
  30293. gradient = this._easingFunction.ease(gradient);
  30294. }
  30295. switch (this.dataType) {
  30296. // Float
  30297. case Animation.ANIMATIONTYPE_FLOAT:
  30298. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  30299. switch (loopMode) {
  30300. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30301. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30302. return floatValue;
  30303. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30304. return offsetValue * repeatCount + floatValue;
  30305. }
  30306. break;
  30307. // Quaternion
  30308. case Animation.ANIMATIONTYPE_QUATERNION:
  30309. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30310. switch (loopMode) {
  30311. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30312. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30313. return quatValue;
  30314. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30315. return quatValue.add(offsetValue.scale(repeatCount));
  30316. }
  30317. return quatValue;
  30318. // Vector3
  30319. case Animation.ANIMATIONTYPE_VECTOR3:
  30320. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  30321. switch (loopMode) {
  30322. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30323. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30324. return vec3Value;
  30325. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30326. return vec3Value.add(offsetValue.scale(repeatCount));
  30327. }
  30328. // Vector2
  30329. case Animation.ANIMATIONTYPE_VECTOR2:
  30330. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  30331. switch (loopMode) {
  30332. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30333. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30334. return vec2Value;
  30335. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30336. return vec2Value.add(offsetValue.scale(repeatCount));
  30337. }
  30338. // Size
  30339. case Animation.ANIMATIONTYPE_SIZE:
  30340. switch (loopMode) {
  30341. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30342. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30343. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30344. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30345. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30346. }
  30347. // Color3
  30348. case Animation.ANIMATIONTYPE_COLOR3:
  30349. switch (loopMode) {
  30350. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30351. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30352. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30353. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30354. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30355. }
  30356. // Matrix
  30357. case Animation.ANIMATIONTYPE_MATRIX:
  30358. switch (loopMode) {
  30359. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30360. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30361. if (this.allowMatricesInterpolation) {
  30362. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30363. }
  30364. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30365. return startValue;
  30366. }
  30367. default:
  30368. break;
  30369. }
  30370. break;
  30371. }
  30372. }
  30373. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30374. };
  30375. Animation.prototype.setValue = function (currentValue, blend) {
  30376. if (blend === void 0) { blend = false; }
  30377. // Set value
  30378. var path;
  30379. var destination;
  30380. if (this.targetPropertyPath.length > 1) {
  30381. var property = this._target[this.targetPropertyPath[0]];
  30382. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30383. property = property[this.targetPropertyPath[index]];
  30384. }
  30385. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30386. destination = property;
  30387. }
  30388. else {
  30389. path = this.targetPropertyPath[0];
  30390. destination = this._target;
  30391. }
  30392. // Blending
  30393. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30394. if (!this._originalBlendValue) {
  30395. if (destination[path].clone) {
  30396. this._originalBlendValue = destination[path].clone();
  30397. }
  30398. else {
  30399. this._originalBlendValue = destination[path];
  30400. }
  30401. }
  30402. if (this._originalBlendValue.prototype) {
  30403. if (this._originalBlendValue.prototype.Lerp) {
  30404. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30405. }
  30406. else {
  30407. destination[path] = currentValue;
  30408. }
  30409. }
  30410. else if (this._originalBlendValue.m) {
  30411. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30412. }
  30413. else {
  30414. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30415. }
  30416. this._blendingFactor += this.blendingSpeed;
  30417. }
  30418. else {
  30419. destination[path] = currentValue;
  30420. }
  30421. if (this._target.markAsDirty) {
  30422. this._target.markAsDirty(this.targetProperty);
  30423. }
  30424. };
  30425. Animation.prototype.goToFrame = function (frame) {
  30426. if (frame < this._keys[0].frame) {
  30427. frame = this._keys[0].frame;
  30428. }
  30429. else if (frame > this._keys[this._keys.length - 1].frame) {
  30430. frame = this._keys[this._keys.length - 1].frame;
  30431. }
  30432. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30433. this.setValue(currentValue);
  30434. };
  30435. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30436. if (blend === void 0) { blend = false; }
  30437. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30438. this._stopped = true;
  30439. return false;
  30440. }
  30441. var returnValue = true;
  30442. // Adding a start key at frame 0 if missing
  30443. if (this._keys[0].frame !== 0) {
  30444. var newKey = { frame: 0, value: this._keys[0].value };
  30445. this._keys.splice(0, 0, newKey);
  30446. }
  30447. // Check limits
  30448. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30449. from = this._keys[0].frame;
  30450. }
  30451. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30452. to = this._keys[this._keys.length - 1].frame;
  30453. }
  30454. //to and from cannot be the same key
  30455. if (from === to) {
  30456. from++;
  30457. }
  30458. // Compute ratio
  30459. var range = to - from;
  30460. var offsetValue;
  30461. // ratio represents the frame delta between from and to
  30462. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30463. var highLimitValue = 0;
  30464. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  30465. returnValue = false;
  30466. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30467. }
  30468. else {
  30469. // Get max value if required
  30470. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30471. var keyOffset = to.toString() + from.toString();
  30472. if (!this._offsetsCache[keyOffset]) {
  30473. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30474. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30475. switch (this.dataType) {
  30476. // Float
  30477. case Animation.ANIMATIONTYPE_FLOAT:
  30478. this._offsetsCache[keyOffset] = toValue - fromValue;
  30479. break;
  30480. // Quaternion
  30481. case Animation.ANIMATIONTYPE_QUATERNION:
  30482. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30483. break;
  30484. // Vector3
  30485. case Animation.ANIMATIONTYPE_VECTOR3:
  30486. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30487. // Vector2
  30488. case Animation.ANIMATIONTYPE_VECTOR2:
  30489. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30490. // Size
  30491. case Animation.ANIMATIONTYPE_SIZE:
  30492. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30493. // Color3
  30494. case Animation.ANIMATIONTYPE_COLOR3:
  30495. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30496. default:
  30497. break;
  30498. }
  30499. this._highLimitsCache[keyOffset] = toValue;
  30500. }
  30501. highLimitValue = this._highLimitsCache[keyOffset];
  30502. offsetValue = this._offsetsCache[keyOffset];
  30503. }
  30504. }
  30505. if (offsetValue === undefined) {
  30506. switch (this.dataType) {
  30507. // Float
  30508. case Animation.ANIMATIONTYPE_FLOAT:
  30509. offsetValue = 0;
  30510. break;
  30511. // Quaternion
  30512. case Animation.ANIMATIONTYPE_QUATERNION:
  30513. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30514. break;
  30515. // Vector3
  30516. case Animation.ANIMATIONTYPE_VECTOR3:
  30517. offsetValue = BABYLON.Vector3.Zero();
  30518. break;
  30519. // Vector2
  30520. case Animation.ANIMATIONTYPE_VECTOR2:
  30521. offsetValue = BABYLON.Vector2.Zero();
  30522. break;
  30523. // Size
  30524. case Animation.ANIMATIONTYPE_SIZE:
  30525. offsetValue = BABYLON.Size.Zero();
  30526. break;
  30527. // Color3
  30528. case Animation.ANIMATIONTYPE_COLOR3:
  30529. offsetValue = BABYLON.Color3.Black();
  30530. }
  30531. }
  30532. // Compute value
  30533. var repeatCount = (ratio / range) >> 0;
  30534. var currentFrame = returnValue ? from + ratio % range : to;
  30535. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30536. // Set value
  30537. this.setValue(currentValue);
  30538. // Check events
  30539. for (var index = 0; index < this._events.length; index++) {
  30540. // Make sure current frame has passed event frame and that event frame is within the current range
  30541. // Also, handle both forward and reverse animations
  30542. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  30543. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  30544. var event = this._events[index];
  30545. if (!event.isDone) {
  30546. // If event should be done only once, remove it.
  30547. if (event.onlyOnce) {
  30548. this._events.splice(index, 1);
  30549. index--;
  30550. }
  30551. event.isDone = true;
  30552. event.action();
  30553. } // Don't do anything if the event has already be done.
  30554. }
  30555. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30556. // reset event, the animation is looping
  30557. this._events[index].isDone = false;
  30558. }
  30559. }
  30560. if (!returnValue) {
  30561. this._stopped = true;
  30562. }
  30563. return returnValue;
  30564. };
  30565. Animation.prototype.serialize = function () {
  30566. var serializationObject = {};
  30567. serializationObject.name = this.name;
  30568. serializationObject.property = this.targetProperty;
  30569. serializationObject.framePerSecond = this.framePerSecond;
  30570. serializationObject.dataType = this.dataType;
  30571. serializationObject.loopBehavior = this.loopMode;
  30572. serializationObject.enableBlending = this.enableBlending;
  30573. serializationObject.blendingSpeed = this.blendingSpeed;
  30574. var dataType = this.dataType;
  30575. serializationObject.keys = [];
  30576. var keys = this.getKeys();
  30577. for (var index = 0; index < keys.length; index++) {
  30578. var animationKey = keys[index];
  30579. var key = {};
  30580. key.frame = animationKey.frame;
  30581. switch (dataType) {
  30582. case Animation.ANIMATIONTYPE_FLOAT:
  30583. key.values = [animationKey.value];
  30584. break;
  30585. case Animation.ANIMATIONTYPE_QUATERNION:
  30586. case Animation.ANIMATIONTYPE_MATRIX:
  30587. case Animation.ANIMATIONTYPE_VECTOR3:
  30588. case Animation.ANIMATIONTYPE_COLOR3:
  30589. key.values = animationKey.value.asArray();
  30590. break;
  30591. }
  30592. serializationObject.keys.push(key);
  30593. }
  30594. serializationObject.ranges = [];
  30595. for (var name in this._ranges) {
  30596. var range = {};
  30597. range.name = name;
  30598. range.from = this._ranges[name].from;
  30599. range.to = this._ranges[name].to;
  30600. serializationObject.ranges.push(range);
  30601. }
  30602. return serializationObject;
  30603. };
  30604. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30605. get: function () {
  30606. return Animation._ANIMATIONTYPE_FLOAT;
  30607. },
  30608. enumerable: true,
  30609. configurable: true
  30610. });
  30611. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30612. get: function () {
  30613. return Animation._ANIMATIONTYPE_VECTOR3;
  30614. },
  30615. enumerable: true,
  30616. configurable: true
  30617. });
  30618. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30619. get: function () {
  30620. return Animation._ANIMATIONTYPE_VECTOR2;
  30621. },
  30622. enumerable: true,
  30623. configurable: true
  30624. });
  30625. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30626. get: function () {
  30627. return Animation._ANIMATIONTYPE_SIZE;
  30628. },
  30629. enumerable: true,
  30630. configurable: true
  30631. });
  30632. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30633. get: function () {
  30634. return Animation._ANIMATIONTYPE_QUATERNION;
  30635. },
  30636. enumerable: true,
  30637. configurable: true
  30638. });
  30639. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30640. get: function () {
  30641. return Animation._ANIMATIONTYPE_MATRIX;
  30642. },
  30643. enumerable: true,
  30644. configurable: true
  30645. });
  30646. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30647. get: function () {
  30648. return Animation._ANIMATIONTYPE_COLOR3;
  30649. },
  30650. enumerable: true,
  30651. configurable: true
  30652. });
  30653. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30654. get: function () {
  30655. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30656. },
  30657. enumerable: true,
  30658. configurable: true
  30659. });
  30660. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30661. get: function () {
  30662. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30663. },
  30664. enumerable: true,
  30665. configurable: true
  30666. });
  30667. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30668. get: function () {
  30669. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30670. },
  30671. enumerable: true,
  30672. configurable: true
  30673. });
  30674. Animation.Parse = function (parsedAnimation) {
  30675. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30676. var dataType = parsedAnimation.dataType;
  30677. var keys = [];
  30678. var data;
  30679. var index;
  30680. if (parsedAnimation.enableBlending) {
  30681. animation.enableBlending = parsedAnimation.enableBlending;
  30682. }
  30683. if (parsedAnimation.blendingSpeed) {
  30684. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30685. }
  30686. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30687. var key = parsedAnimation.keys[index];
  30688. switch (dataType) {
  30689. case Animation.ANIMATIONTYPE_FLOAT:
  30690. data = key.values[0];
  30691. break;
  30692. case Animation.ANIMATIONTYPE_QUATERNION:
  30693. data = BABYLON.Quaternion.FromArray(key.values);
  30694. break;
  30695. case Animation.ANIMATIONTYPE_MATRIX:
  30696. data = BABYLON.Matrix.FromArray(key.values);
  30697. break;
  30698. case Animation.ANIMATIONTYPE_COLOR3:
  30699. data = BABYLON.Color3.FromArray(key.values);
  30700. break;
  30701. case Animation.ANIMATIONTYPE_VECTOR3:
  30702. default:
  30703. data = BABYLON.Vector3.FromArray(key.values);
  30704. break;
  30705. }
  30706. keys.push({
  30707. frame: key.frame,
  30708. value: data
  30709. });
  30710. }
  30711. animation.setKeys(keys);
  30712. if (parsedAnimation.ranges) {
  30713. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30714. data = parsedAnimation.ranges[index];
  30715. animation.createRange(data.name, data.from, data.to);
  30716. }
  30717. }
  30718. return animation;
  30719. };
  30720. Animation.AppendSerializedAnimations = function (source, destination) {
  30721. if (source.animations) {
  30722. destination.animations = [];
  30723. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30724. var animation = source.animations[animationIndex];
  30725. destination.animations.push(animation.serialize());
  30726. }
  30727. }
  30728. };
  30729. // Statics
  30730. Animation._ANIMATIONTYPE_FLOAT = 0;
  30731. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30732. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30733. Animation._ANIMATIONTYPE_MATRIX = 3;
  30734. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30735. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30736. Animation._ANIMATIONTYPE_SIZE = 6;
  30737. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30738. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30739. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30740. return Animation;
  30741. }());
  30742. BABYLON.Animation = Animation;
  30743. })(BABYLON || (BABYLON = {}));
  30744. //# sourceMappingURL=babylon.animation.js.map
  30745. var BABYLON;
  30746. (function (BABYLON) {
  30747. var Animatable = (function () {
  30748. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30749. if (fromFrame === void 0) { fromFrame = 0; }
  30750. if (toFrame === void 0) { toFrame = 100; }
  30751. if (loopAnimation === void 0) { loopAnimation = false; }
  30752. if (speedRatio === void 0) { speedRatio = 1.0; }
  30753. this.target = target;
  30754. this.fromFrame = fromFrame;
  30755. this.toFrame = toFrame;
  30756. this.loopAnimation = loopAnimation;
  30757. this.speedRatio = speedRatio;
  30758. this.onAnimationEnd = onAnimationEnd;
  30759. this._localDelayOffset = null;
  30760. this._pausedDelay = null;
  30761. this._animations = new Array();
  30762. this._paused = false;
  30763. this.animationStarted = false;
  30764. if (animations) {
  30765. this.appendAnimations(target, animations);
  30766. }
  30767. this._scene = scene;
  30768. scene._activeAnimatables.push(this);
  30769. }
  30770. // Methods
  30771. Animatable.prototype.getAnimations = function () {
  30772. return this._animations;
  30773. };
  30774. Animatable.prototype.appendAnimations = function (target, animations) {
  30775. for (var index = 0; index < animations.length; index++) {
  30776. var animation = animations[index];
  30777. animation._target = target;
  30778. this._animations.push(animation);
  30779. }
  30780. };
  30781. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30782. var animations = this._animations;
  30783. for (var index = 0; index < animations.length; index++) {
  30784. if (animations[index].targetProperty === property) {
  30785. return animations[index];
  30786. }
  30787. }
  30788. return null;
  30789. };
  30790. Animatable.prototype.reset = function () {
  30791. var animations = this._animations;
  30792. for (var index = 0; index < animations.length; index++) {
  30793. animations[index].reset();
  30794. }
  30795. this._localDelayOffset = null;
  30796. this._pausedDelay = null;
  30797. };
  30798. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30799. var animations = this._animations;
  30800. for (var index = 0; index < animations.length; index++) {
  30801. animations[index].enableBlending = true;
  30802. animations[index].blendingSpeed = blendingSpeed;
  30803. }
  30804. };
  30805. Animatable.prototype.disableBlending = function () {
  30806. var animations = this._animations;
  30807. for (var index = 0; index < animations.length; index++) {
  30808. animations[index].enableBlending = false;
  30809. }
  30810. };
  30811. Animatable.prototype.goToFrame = function (frame) {
  30812. var animations = this._animations;
  30813. if (animations[0]) {
  30814. var fps = animations[0].framePerSecond;
  30815. var currentFrame = animations[0].currentFrame;
  30816. var adjustTime = frame - currentFrame;
  30817. var delay = adjustTime * 1000 / fps;
  30818. this._localDelayOffset -= delay;
  30819. }
  30820. for (var index = 0; index < animations.length; index++) {
  30821. animations[index].goToFrame(frame);
  30822. }
  30823. };
  30824. Animatable.prototype.pause = function () {
  30825. if (this._paused) {
  30826. return;
  30827. }
  30828. this._paused = true;
  30829. };
  30830. Animatable.prototype.restart = function () {
  30831. this._paused = false;
  30832. };
  30833. Animatable.prototype.stop = function (animationName) {
  30834. if (animationName) {
  30835. var idx = this._scene._activeAnimatables.indexOf(this);
  30836. if (idx > -1) {
  30837. var animations = this._animations;
  30838. for (var index = animations.length - 1; index >= 0; index--) {
  30839. if (typeof animationName === "string" && animations[index].name != animationName) {
  30840. continue;
  30841. }
  30842. animations[index].reset();
  30843. animations.splice(index, 1);
  30844. }
  30845. if (animations.length == 0) {
  30846. this._scene._activeAnimatables.splice(idx, 1);
  30847. if (this.onAnimationEnd) {
  30848. this.onAnimationEnd();
  30849. }
  30850. }
  30851. }
  30852. }
  30853. else {
  30854. var index = this._scene._activeAnimatables.indexOf(this);
  30855. if (index > -1) {
  30856. this._scene._activeAnimatables.splice(index, 1);
  30857. var animations = this._animations;
  30858. for (var index = 0; index < animations.length; index++) {
  30859. animations[index].reset();
  30860. }
  30861. if (this.onAnimationEnd) {
  30862. this.onAnimationEnd();
  30863. }
  30864. }
  30865. }
  30866. };
  30867. Animatable.prototype._animate = function (delay) {
  30868. if (this._paused) {
  30869. this.animationStarted = false;
  30870. if (this._pausedDelay === null) {
  30871. this._pausedDelay = delay;
  30872. }
  30873. return true;
  30874. }
  30875. if (this._localDelayOffset === null) {
  30876. this._localDelayOffset = delay;
  30877. }
  30878. else if (this._pausedDelay !== null) {
  30879. this._localDelayOffset += delay - this._pausedDelay;
  30880. this._pausedDelay = null;
  30881. }
  30882. // Animating
  30883. var running = false;
  30884. var animations = this._animations;
  30885. var index;
  30886. for (index = 0; index < animations.length; index++) {
  30887. var animation = animations[index];
  30888. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30889. running = running || isRunning;
  30890. }
  30891. this.animationStarted = running;
  30892. if (!running) {
  30893. // Remove from active animatables
  30894. index = this._scene._activeAnimatables.indexOf(this);
  30895. this._scene._activeAnimatables.splice(index, 1);
  30896. }
  30897. if (!running && this.onAnimationEnd) {
  30898. this.onAnimationEnd();
  30899. this.onAnimationEnd = null;
  30900. }
  30901. return running;
  30902. };
  30903. return Animatable;
  30904. }());
  30905. BABYLON.Animatable = Animatable;
  30906. })(BABYLON || (BABYLON = {}));
  30907. //# sourceMappingURL=babylon.animatable.js.map
  30908. var BABYLON;
  30909. (function (BABYLON) {
  30910. var EasingFunction = (function () {
  30911. function EasingFunction() {
  30912. // Properties
  30913. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  30914. }
  30915. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  30916. get: function () {
  30917. return EasingFunction._EASINGMODE_EASEIN;
  30918. },
  30919. enumerable: true,
  30920. configurable: true
  30921. });
  30922. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  30923. get: function () {
  30924. return EasingFunction._EASINGMODE_EASEOUT;
  30925. },
  30926. enumerable: true,
  30927. configurable: true
  30928. });
  30929. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  30930. get: function () {
  30931. return EasingFunction._EASINGMODE_EASEINOUT;
  30932. },
  30933. enumerable: true,
  30934. configurable: true
  30935. });
  30936. EasingFunction.prototype.setEasingMode = function (easingMode) {
  30937. var n = Math.min(Math.max(easingMode, 0), 2);
  30938. this._easingMode = n;
  30939. };
  30940. EasingFunction.prototype.getEasingMode = function () {
  30941. return this._easingMode;
  30942. };
  30943. EasingFunction.prototype.easeInCore = function (gradient) {
  30944. throw new Error('You must implement this method');
  30945. };
  30946. EasingFunction.prototype.ease = function (gradient) {
  30947. switch (this._easingMode) {
  30948. case EasingFunction.EASINGMODE_EASEIN:
  30949. return this.easeInCore(gradient);
  30950. case EasingFunction.EASINGMODE_EASEOUT:
  30951. return (1 - this.easeInCore(1 - gradient));
  30952. }
  30953. if (gradient >= 0.5) {
  30954. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  30955. }
  30956. return (this.easeInCore(gradient * 2) * 0.5);
  30957. };
  30958. //Statics
  30959. EasingFunction._EASINGMODE_EASEIN = 0;
  30960. EasingFunction._EASINGMODE_EASEOUT = 1;
  30961. EasingFunction._EASINGMODE_EASEINOUT = 2;
  30962. return EasingFunction;
  30963. }());
  30964. BABYLON.EasingFunction = EasingFunction;
  30965. var CircleEase = (function (_super) {
  30966. __extends(CircleEase, _super);
  30967. function CircleEase() {
  30968. return _super !== null && _super.apply(this, arguments) || this;
  30969. }
  30970. CircleEase.prototype.easeInCore = function (gradient) {
  30971. gradient = Math.max(0, Math.min(1, gradient));
  30972. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30973. };
  30974. return CircleEase;
  30975. }(EasingFunction));
  30976. BABYLON.CircleEase = CircleEase;
  30977. var BackEase = (function (_super) {
  30978. __extends(BackEase, _super);
  30979. function BackEase(amplitude) {
  30980. if (amplitude === void 0) { amplitude = 1; }
  30981. var _this = _super.call(this) || this;
  30982. _this.amplitude = amplitude;
  30983. return _this;
  30984. }
  30985. BackEase.prototype.easeInCore = function (gradient) {
  30986. var num = Math.max(0, this.amplitude);
  30987. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30988. };
  30989. return BackEase;
  30990. }(EasingFunction));
  30991. BABYLON.BackEase = BackEase;
  30992. var BounceEase = (function (_super) {
  30993. __extends(BounceEase, _super);
  30994. function BounceEase(bounces, bounciness) {
  30995. if (bounces === void 0) { bounces = 3; }
  30996. if (bounciness === void 0) { bounciness = 2; }
  30997. var _this = _super.call(this) || this;
  30998. _this.bounces = bounces;
  30999. _this.bounciness = bounciness;
  31000. return _this;
  31001. }
  31002. BounceEase.prototype.easeInCore = function (gradient) {
  31003. var y = Math.max(0.0, this.bounces);
  31004. var bounciness = this.bounciness;
  31005. if (bounciness <= 1.0) {
  31006. bounciness = 1.001;
  31007. }
  31008. var num9 = Math.pow(bounciness, y);
  31009. var num5 = 1.0 - bounciness;
  31010. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  31011. var num15 = gradient * num4;
  31012. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  31013. var num3 = Math.floor(num65);
  31014. var num13 = num3 + 1.0;
  31015. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  31016. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  31017. var num7 = (num8 + num12) * 0.5;
  31018. var num6 = gradient - num7;
  31019. var num2 = num7 - num8;
  31020. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  31021. };
  31022. return BounceEase;
  31023. }(EasingFunction));
  31024. BABYLON.BounceEase = BounceEase;
  31025. var CubicEase = (function (_super) {
  31026. __extends(CubicEase, _super);
  31027. function CubicEase() {
  31028. return _super !== null && _super.apply(this, arguments) || this;
  31029. }
  31030. CubicEase.prototype.easeInCore = function (gradient) {
  31031. return (gradient * gradient * gradient);
  31032. };
  31033. return CubicEase;
  31034. }(EasingFunction));
  31035. BABYLON.CubicEase = CubicEase;
  31036. var ElasticEase = (function (_super) {
  31037. __extends(ElasticEase, _super);
  31038. function ElasticEase(oscillations, springiness) {
  31039. if (oscillations === void 0) { oscillations = 3; }
  31040. if (springiness === void 0) { springiness = 3; }
  31041. var _this = _super.call(this) || this;
  31042. _this.oscillations = oscillations;
  31043. _this.springiness = springiness;
  31044. return _this;
  31045. }
  31046. ElasticEase.prototype.easeInCore = function (gradient) {
  31047. var num2;
  31048. var num3 = Math.max(0.0, this.oscillations);
  31049. var num = Math.max(0.0, this.springiness);
  31050. if (num == 0) {
  31051. num2 = gradient;
  31052. }
  31053. else {
  31054. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  31055. }
  31056. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  31057. };
  31058. return ElasticEase;
  31059. }(EasingFunction));
  31060. BABYLON.ElasticEase = ElasticEase;
  31061. var ExponentialEase = (function (_super) {
  31062. __extends(ExponentialEase, _super);
  31063. function ExponentialEase(exponent) {
  31064. if (exponent === void 0) { exponent = 2; }
  31065. var _this = _super.call(this) || this;
  31066. _this.exponent = exponent;
  31067. return _this;
  31068. }
  31069. ExponentialEase.prototype.easeInCore = function (gradient) {
  31070. if (this.exponent <= 0) {
  31071. return gradient;
  31072. }
  31073. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  31074. };
  31075. return ExponentialEase;
  31076. }(EasingFunction));
  31077. BABYLON.ExponentialEase = ExponentialEase;
  31078. var PowerEase = (function (_super) {
  31079. __extends(PowerEase, _super);
  31080. function PowerEase(power) {
  31081. if (power === void 0) { power = 2; }
  31082. var _this = _super.call(this) || this;
  31083. _this.power = power;
  31084. return _this;
  31085. }
  31086. PowerEase.prototype.easeInCore = function (gradient) {
  31087. var y = Math.max(0.0, this.power);
  31088. return Math.pow(gradient, y);
  31089. };
  31090. return PowerEase;
  31091. }(EasingFunction));
  31092. BABYLON.PowerEase = PowerEase;
  31093. var QuadraticEase = (function (_super) {
  31094. __extends(QuadraticEase, _super);
  31095. function QuadraticEase() {
  31096. return _super !== null && _super.apply(this, arguments) || this;
  31097. }
  31098. QuadraticEase.prototype.easeInCore = function (gradient) {
  31099. return (gradient * gradient);
  31100. };
  31101. return QuadraticEase;
  31102. }(EasingFunction));
  31103. BABYLON.QuadraticEase = QuadraticEase;
  31104. var QuarticEase = (function (_super) {
  31105. __extends(QuarticEase, _super);
  31106. function QuarticEase() {
  31107. return _super !== null && _super.apply(this, arguments) || this;
  31108. }
  31109. QuarticEase.prototype.easeInCore = function (gradient) {
  31110. return (gradient * gradient * gradient * gradient);
  31111. };
  31112. return QuarticEase;
  31113. }(EasingFunction));
  31114. BABYLON.QuarticEase = QuarticEase;
  31115. var QuinticEase = (function (_super) {
  31116. __extends(QuinticEase, _super);
  31117. function QuinticEase() {
  31118. return _super !== null && _super.apply(this, arguments) || this;
  31119. }
  31120. QuinticEase.prototype.easeInCore = function (gradient) {
  31121. return (gradient * gradient * gradient * gradient * gradient);
  31122. };
  31123. return QuinticEase;
  31124. }(EasingFunction));
  31125. BABYLON.QuinticEase = QuinticEase;
  31126. var SineEase = (function (_super) {
  31127. __extends(SineEase, _super);
  31128. function SineEase() {
  31129. return _super !== null && _super.apply(this, arguments) || this;
  31130. }
  31131. SineEase.prototype.easeInCore = function (gradient) {
  31132. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  31133. };
  31134. return SineEase;
  31135. }(EasingFunction));
  31136. BABYLON.SineEase = SineEase;
  31137. var BezierCurveEase = (function (_super) {
  31138. __extends(BezierCurveEase, _super);
  31139. function BezierCurveEase(x1, y1, x2, y2) {
  31140. if (x1 === void 0) { x1 = 0; }
  31141. if (y1 === void 0) { y1 = 0; }
  31142. if (x2 === void 0) { x2 = 1; }
  31143. if (y2 === void 0) { y2 = 1; }
  31144. var _this = _super.call(this) || this;
  31145. _this.x1 = x1;
  31146. _this.y1 = y1;
  31147. _this.x2 = x2;
  31148. _this.y2 = y2;
  31149. return _this;
  31150. }
  31151. BezierCurveEase.prototype.easeInCore = function (gradient) {
  31152. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  31153. };
  31154. return BezierCurveEase;
  31155. }(EasingFunction));
  31156. BABYLON.BezierCurveEase = BezierCurveEase;
  31157. })(BABYLON || (BABYLON = {}));
  31158. //# sourceMappingURL=babylon.easing.js.map
  31159. var BABYLON;
  31160. (function (BABYLON) {
  31161. BABYLON.CameraInputTypes = {};
  31162. var CameraInputsManager = (function () {
  31163. function CameraInputsManager(camera) {
  31164. this.attached = {};
  31165. this.camera = camera;
  31166. this.checkInputs = function () { };
  31167. }
  31168. CameraInputsManager.prototype.add = function (input) {
  31169. var type = input.getSimpleName();
  31170. if (this.attached[type]) {
  31171. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31172. return;
  31173. }
  31174. this.attached[type] = input;
  31175. input.camera = this.camera;
  31176. //for checkInputs, we are dynamically creating a function
  31177. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31178. if (input.checkInputs) {
  31179. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31180. }
  31181. if (this.attachedElement) {
  31182. input.attachControl(this.attachedElement);
  31183. }
  31184. };
  31185. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31186. for (var cam in this.attached) {
  31187. var input = this.attached[cam];
  31188. if (input === inputToRemove) {
  31189. input.detachControl(this.attachedElement);
  31190. input.camera = null;
  31191. delete this.attached[cam];
  31192. this.rebuildInputCheck();
  31193. }
  31194. }
  31195. };
  31196. CameraInputsManager.prototype.removeByType = function (inputType) {
  31197. for (var cam in this.attached) {
  31198. var input = this.attached[cam];
  31199. if (input.getClassName() === inputType) {
  31200. input.detachControl(this.attachedElement);
  31201. input.camera = null;
  31202. delete this.attached[cam];
  31203. this.rebuildInputCheck();
  31204. }
  31205. }
  31206. };
  31207. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31208. var current = this.checkInputs;
  31209. return function () {
  31210. current();
  31211. fn();
  31212. };
  31213. };
  31214. CameraInputsManager.prototype.attachInput = function (input) {
  31215. input.attachControl(this.attachedElement, this.noPreventDefault);
  31216. };
  31217. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31218. if (this.attachedElement) {
  31219. return;
  31220. }
  31221. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31222. this.attachedElement = element;
  31223. this.noPreventDefault = noPreventDefault;
  31224. for (var cam in this.attached) {
  31225. var input = this.attached[cam];
  31226. this.attached[cam].attachControl(element, noPreventDefault);
  31227. }
  31228. };
  31229. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  31230. if (disconnect === void 0) { disconnect = false; }
  31231. if (this.attachedElement !== element) {
  31232. return;
  31233. }
  31234. for (var cam in this.attached) {
  31235. var input = this.attached[cam];
  31236. this.attached[cam].detachControl(element);
  31237. if (disconnect) {
  31238. this.attached[cam].camera = null;
  31239. }
  31240. }
  31241. this.attachedElement = null;
  31242. };
  31243. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31244. this.checkInputs = function () { };
  31245. for (var cam in this.attached) {
  31246. var input = this.attached[cam];
  31247. if (input.checkInputs) {
  31248. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31249. }
  31250. }
  31251. };
  31252. CameraInputsManager.prototype.clear = function () {
  31253. if (this.attachedElement) {
  31254. this.detachElement(this.attachedElement, true);
  31255. }
  31256. this.attached = {};
  31257. this.attachedElement = null;
  31258. this.checkInputs = function () { };
  31259. };
  31260. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31261. var inputs = {};
  31262. for (var cam in this.attached) {
  31263. var input = this.attached[cam];
  31264. var res = BABYLON.SerializationHelper.Serialize(input);
  31265. inputs[input.getClassName()] = res;
  31266. }
  31267. serializedCamera.inputsmgr = inputs;
  31268. };
  31269. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31270. var parsedInputs = parsedCamera.inputsmgr;
  31271. if (parsedInputs) {
  31272. this.clear();
  31273. for (var n in parsedInputs) {
  31274. var construct = BABYLON.CameraInputTypes[n];
  31275. if (construct) {
  31276. var parsedinput = parsedInputs[n];
  31277. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31278. this.add(input);
  31279. }
  31280. }
  31281. }
  31282. else {
  31283. //2016-03-08 this part is for managing backward compatibility
  31284. for (var n in this.attached) {
  31285. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  31286. if (construct) {
  31287. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31288. this.remove(this.attached[n]);
  31289. this.add(input);
  31290. }
  31291. }
  31292. }
  31293. };
  31294. return CameraInputsManager;
  31295. }());
  31296. BABYLON.CameraInputsManager = CameraInputsManager;
  31297. })(BABYLON || (BABYLON = {}));
  31298. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31299. /// <reference path="babylon.camera.ts" />
  31300. var BABYLON;
  31301. (function (BABYLON) {
  31302. var TargetCamera = (function (_super) {
  31303. __extends(TargetCamera, _super);
  31304. function TargetCamera(name, position, scene) {
  31305. var _this = _super.call(this, name, position, scene) || this;
  31306. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31307. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31308. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31309. _this.speed = 2.0;
  31310. _this.noRotationConstraint = false;
  31311. _this.lockedTarget = null;
  31312. _this._currentTarget = BABYLON.Vector3.Zero();
  31313. _this._viewMatrix = BABYLON.Matrix.Zero();
  31314. _this._camMatrix = BABYLON.Matrix.Zero();
  31315. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31316. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31317. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31318. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31319. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31320. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31321. _this._tempMatrix = BABYLON.Matrix.Zero();
  31322. return _this;
  31323. }
  31324. TargetCamera.prototype.getFrontPosition = function (distance) {
  31325. var direction = this.getTarget().subtract(this.position);
  31326. direction.normalize();
  31327. direction.scaleInPlace(distance);
  31328. return this.globalPosition.add(direction);
  31329. };
  31330. TargetCamera.prototype._getLockedTargetPosition = function () {
  31331. if (!this.lockedTarget) {
  31332. return null;
  31333. }
  31334. if (this.lockedTarget.absolutePosition) {
  31335. this.lockedTarget.computeWorldMatrix();
  31336. }
  31337. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31338. };
  31339. // Cache
  31340. TargetCamera.prototype._initCache = function () {
  31341. _super.prototype._initCache.call(this);
  31342. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31343. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31344. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31345. };
  31346. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31347. if (!ignoreParentClass) {
  31348. _super.prototype._updateCache.call(this);
  31349. }
  31350. var lockedTargetPosition = this._getLockedTargetPosition();
  31351. if (!lockedTargetPosition) {
  31352. this._cache.lockedTarget = null;
  31353. }
  31354. else {
  31355. if (!this._cache.lockedTarget) {
  31356. this._cache.lockedTarget = lockedTargetPosition.clone();
  31357. }
  31358. else {
  31359. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31360. }
  31361. }
  31362. this._cache.rotation.copyFrom(this.rotation);
  31363. if (this.rotationQuaternion)
  31364. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31365. };
  31366. // Synchronized
  31367. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31368. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31369. return false;
  31370. }
  31371. var lockedTargetPosition = this._getLockedTargetPosition();
  31372. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31373. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31374. };
  31375. // Methods
  31376. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31377. var engine = this.getEngine();
  31378. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31379. };
  31380. // Target
  31381. TargetCamera.prototype.setTarget = function (target) {
  31382. this.upVector.normalize();
  31383. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31384. this._camMatrix.invert();
  31385. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31386. var vDir = target.subtract(this.position);
  31387. if (vDir.x >= 0.0) {
  31388. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31389. }
  31390. else {
  31391. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31392. }
  31393. this.rotation.z = 0;
  31394. if (isNaN(this.rotation.x)) {
  31395. this.rotation.x = 0;
  31396. }
  31397. if (isNaN(this.rotation.y)) {
  31398. this.rotation.y = 0;
  31399. }
  31400. if (isNaN(this.rotation.z)) {
  31401. this.rotation.z = 0;
  31402. }
  31403. if (this.rotationQuaternion) {
  31404. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31405. }
  31406. };
  31407. /**
  31408. * Return the current target position of the camera. This value is expressed in local space.
  31409. */
  31410. TargetCamera.prototype.getTarget = function () {
  31411. return this._currentTarget;
  31412. };
  31413. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31414. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31415. };
  31416. TargetCamera.prototype._updatePosition = function () {
  31417. if (this.parent) {
  31418. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31419. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31420. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31421. return;
  31422. }
  31423. this.position.addInPlace(this.cameraDirection);
  31424. };
  31425. TargetCamera.prototype._checkInputs = function () {
  31426. var needToMove = this._decideIfNeedsToMove();
  31427. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31428. // Move
  31429. if (needToMove) {
  31430. this._updatePosition();
  31431. }
  31432. // Rotate
  31433. if (needToRotate) {
  31434. this.rotation.x += this.cameraRotation.x;
  31435. this.rotation.y += this.cameraRotation.y;
  31436. //rotate, if quaternion is set and rotation was used
  31437. if (this.rotationQuaternion) {
  31438. var len = this.rotation.lengthSquared();
  31439. if (len) {
  31440. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31441. }
  31442. }
  31443. if (!this.noRotationConstraint) {
  31444. var limit = (Math.PI / 2) * 0.95;
  31445. if (this.rotation.x > limit)
  31446. this.rotation.x = limit;
  31447. if (this.rotation.x < -limit)
  31448. this.rotation.x = -limit;
  31449. }
  31450. }
  31451. // Inertia
  31452. if (needToMove) {
  31453. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31454. this.cameraDirection.x = 0;
  31455. }
  31456. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31457. this.cameraDirection.y = 0;
  31458. }
  31459. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31460. this.cameraDirection.z = 0;
  31461. }
  31462. this.cameraDirection.scaleInPlace(this.inertia);
  31463. }
  31464. if (needToRotate) {
  31465. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31466. this.cameraRotation.x = 0;
  31467. }
  31468. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31469. this.cameraRotation.y = 0;
  31470. }
  31471. this.cameraRotation.scaleInPlace(this.inertia);
  31472. }
  31473. _super.prototype._checkInputs.call(this);
  31474. };
  31475. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31476. if (this.rotationQuaternion) {
  31477. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31478. //update the up vector!
  31479. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31480. }
  31481. else {
  31482. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31483. }
  31484. };
  31485. TargetCamera.prototype._getViewMatrix = function () {
  31486. if (!this.lockedTarget) {
  31487. // Compute
  31488. this._updateCameraRotationMatrix();
  31489. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31490. // Computing target and final matrix
  31491. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31492. }
  31493. else {
  31494. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31495. }
  31496. if (this.getScene().useRightHandedSystem) {
  31497. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31498. }
  31499. else {
  31500. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31501. }
  31502. return this._viewMatrix;
  31503. };
  31504. /**
  31505. * @override
  31506. * Override Camera.createRigCamera
  31507. */
  31508. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31509. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31510. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31511. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31512. if (!this.rotationQuaternion) {
  31513. this.rotationQuaternion = new BABYLON.Quaternion();
  31514. }
  31515. rigCamera._cameraRigParams = {};
  31516. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31517. }
  31518. return rigCamera;
  31519. }
  31520. return null;
  31521. };
  31522. /**
  31523. * @override
  31524. * Override Camera._updateRigCameras
  31525. */
  31526. TargetCamera.prototype._updateRigCameras = function () {
  31527. var camLeft = this._rigCameras[0];
  31528. var camRight = this._rigCameras[1];
  31529. switch (this.cameraRigMode) {
  31530. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31531. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31532. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31533. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31534. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31535. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31536. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31537. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31538. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31539. camLeft.setTarget(this.getTarget());
  31540. camRight.setTarget(this.getTarget());
  31541. break;
  31542. case BABYLON.Camera.RIG_MODE_VR:
  31543. if (camLeft.rotationQuaternion) {
  31544. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31545. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31546. }
  31547. else {
  31548. camLeft.rotation.copyFrom(this.rotation);
  31549. camRight.rotation.copyFrom(this.rotation);
  31550. }
  31551. camLeft.position.copyFrom(this.position);
  31552. camRight.position.copyFrom(this.position);
  31553. break;
  31554. }
  31555. _super.prototype._updateRigCameras.call(this);
  31556. };
  31557. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31558. if (!this._rigCamTransformMatrix) {
  31559. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31560. }
  31561. var target = this.getTarget();
  31562. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31563. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31564. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31565. };
  31566. TargetCamera.prototype.getClassName = function () {
  31567. return "TargetCamera";
  31568. };
  31569. __decorate([
  31570. BABYLON.serializeAsVector3()
  31571. ], TargetCamera.prototype, "rotation", void 0);
  31572. __decorate([
  31573. BABYLON.serialize()
  31574. ], TargetCamera.prototype, "speed", void 0);
  31575. __decorate([
  31576. BABYLON.serializeAsMeshReference("lockedTargetId")
  31577. ], TargetCamera.prototype, "lockedTarget", void 0);
  31578. return TargetCamera;
  31579. }(BABYLON.Camera));
  31580. BABYLON.TargetCamera = TargetCamera;
  31581. })(BABYLON || (BABYLON = {}));
  31582. //# sourceMappingURL=babylon.targetCamera.js.map
  31583. var BABYLON;
  31584. (function (BABYLON) {
  31585. var ArcRotateCameraKeyboardMoveInput = (function () {
  31586. function ArcRotateCameraKeyboardMoveInput() {
  31587. this._keys = [];
  31588. this.keysUp = [38];
  31589. this.keysDown = [40];
  31590. this.keysLeft = [37];
  31591. this.keysRight = [39];
  31592. }
  31593. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31594. var _this = this;
  31595. element.tabIndex = 1;
  31596. this._onKeyDown = function (evt) {
  31597. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31598. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31599. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31600. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31601. var index = _this._keys.indexOf(evt.keyCode);
  31602. if (index === -1) {
  31603. _this._keys.push(evt.keyCode);
  31604. }
  31605. if (evt.preventDefault) {
  31606. if (!noPreventDefault) {
  31607. evt.preventDefault();
  31608. }
  31609. }
  31610. }
  31611. };
  31612. this._onKeyUp = function (evt) {
  31613. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31614. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31615. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31616. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31617. var index = _this._keys.indexOf(evt.keyCode);
  31618. if (index >= 0) {
  31619. _this._keys.splice(index, 1);
  31620. }
  31621. if (evt.preventDefault) {
  31622. if (!noPreventDefault) {
  31623. evt.preventDefault();
  31624. }
  31625. }
  31626. }
  31627. };
  31628. this._onLostFocus = function () {
  31629. _this._keys = [];
  31630. };
  31631. this._onFocus = function () {
  31632. element.addEventListener("keydown", _this._onKeyDown, false);
  31633. element.addEventListener("keyup", _this._onKeyUp, false);
  31634. };
  31635. this._onBlur = function () {
  31636. element.removeEventListener("keydown", _this._onKeyDown);
  31637. element.removeEventListener("keyup", _this._onKeyUp);
  31638. };
  31639. element.addEventListener("focus", this._onFocus);
  31640. element.addEventListener("blur", this._onBlur);
  31641. BABYLON.Tools.RegisterTopRootEvents([
  31642. { name: "blur", handler: this._onLostFocus }
  31643. ]);
  31644. };
  31645. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31646. if (element && this._onBlur) {
  31647. this._onBlur();
  31648. element.removeEventListener("focus", this._onFocus);
  31649. element.removeEventListener("blur", this._onBlur);
  31650. }
  31651. BABYLON.Tools.UnregisterTopRootEvents([
  31652. { name: "blur", handler: this._onLostFocus }
  31653. ]);
  31654. this._keys = [];
  31655. this._onKeyDown = null;
  31656. this._onKeyUp = null;
  31657. this._onLostFocus = null;
  31658. this._onBlur = null;
  31659. this._onFocus = null;
  31660. };
  31661. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31662. if (this._onKeyDown) {
  31663. var camera = this.camera;
  31664. for (var index = 0; index < this._keys.length; index++) {
  31665. var keyCode = this._keys[index];
  31666. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31667. camera.inertialAlphaOffset -= 0.01;
  31668. }
  31669. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31670. camera.inertialBetaOffset -= 0.01;
  31671. }
  31672. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31673. camera.inertialAlphaOffset += 0.01;
  31674. }
  31675. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31676. camera.inertialBetaOffset += 0.01;
  31677. }
  31678. }
  31679. }
  31680. };
  31681. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  31682. return "ArcRotateCameraKeyboardMoveInput";
  31683. };
  31684. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31685. return "keyboard";
  31686. };
  31687. __decorate([
  31688. BABYLON.serialize()
  31689. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31690. __decorate([
  31691. BABYLON.serialize()
  31692. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31693. __decorate([
  31694. BABYLON.serialize()
  31695. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31696. __decorate([
  31697. BABYLON.serialize()
  31698. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31699. return ArcRotateCameraKeyboardMoveInput;
  31700. }());
  31701. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  31702. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  31703. })(BABYLON || (BABYLON = {}));
  31704. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  31705. var BABYLON;
  31706. (function (BABYLON) {
  31707. var ArcRotateCameraMouseWheelInput = (function () {
  31708. function ArcRotateCameraMouseWheelInput() {
  31709. this.wheelPrecision = 3.0;
  31710. }
  31711. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  31712. var _this = this;
  31713. this._wheel = function (p, s) {
  31714. //sanity check - this should be a PointerWheel event.
  31715. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  31716. return;
  31717. var event = p.event;
  31718. var delta = 0;
  31719. if (event.wheelDelta) {
  31720. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  31721. }
  31722. else if (event.detail) {
  31723. delta = -event.detail / _this.wheelPrecision;
  31724. }
  31725. if (delta)
  31726. _this.camera.inertialRadiusOffset += delta;
  31727. if (event.preventDefault) {
  31728. if (!noPreventDefault) {
  31729. event.preventDefault();
  31730. }
  31731. }
  31732. };
  31733. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  31734. };
  31735. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  31736. if (this._observer && element) {
  31737. this.camera.getScene().onPointerObservable.remove(this._observer);
  31738. this._observer = null;
  31739. this._wheel = null;
  31740. }
  31741. };
  31742. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  31743. return "ArcRotateCameraMouseWheelInput";
  31744. };
  31745. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  31746. return "mousewheel";
  31747. };
  31748. __decorate([
  31749. BABYLON.serialize()
  31750. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  31751. return ArcRotateCameraMouseWheelInput;
  31752. }());
  31753. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  31754. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  31755. })(BABYLON || (BABYLON = {}));
  31756. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  31757. var BABYLON;
  31758. (function (BABYLON) {
  31759. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  31760. var ArcRotateCameraPointersInput = (function () {
  31761. function ArcRotateCameraPointersInput() {
  31762. this.buttons = [0, 1, 2];
  31763. this.angularSensibilityX = 1000.0;
  31764. this.angularSensibilityY = 1000.0;
  31765. this.pinchPrecision = 6.0;
  31766. this.panningSensibility = 50.0;
  31767. this._isPanClick = false;
  31768. this.pinchInwards = true;
  31769. }
  31770. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  31771. var _this = this;
  31772. var engine = this.camera.getEngine();
  31773. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  31774. var pointA, pointB;
  31775. var previousPinchDistance = 0;
  31776. this._pointerInput = function (p, s) {
  31777. var evt = p.event;
  31778. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31779. return;
  31780. }
  31781. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31782. try {
  31783. evt.srcElement.setPointerCapture(evt.pointerId);
  31784. }
  31785. catch (e) {
  31786. //Nothing to do with the error. Execution will continue.
  31787. }
  31788. // Manage panning with pan button click
  31789. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  31790. // manage pointers
  31791. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  31792. if (pointA === undefined) {
  31793. pointA = cacheSoloPointer;
  31794. }
  31795. else if (pointB === undefined) {
  31796. pointB = cacheSoloPointer;
  31797. }
  31798. if (!noPreventDefault) {
  31799. evt.preventDefault();
  31800. element.focus();
  31801. }
  31802. }
  31803. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31804. try {
  31805. evt.srcElement.releasePointerCapture(evt.pointerId);
  31806. }
  31807. catch (e) {
  31808. //Nothing to do with the error.
  31809. }
  31810. cacheSoloPointer = null;
  31811. previousPinchDistance = 0;
  31812. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  31813. //but emptying completly pointers collection is required to fix a bug on iPhone :
  31814. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  31815. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  31816. pointA = pointB = undefined;
  31817. if (!noPreventDefault) {
  31818. evt.preventDefault();
  31819. }
  31820. }
  31821. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31822. if (!noPreventDefault) {
  31823. evt.preventDefault();
  31824. }
  31825. // One button down
  31826. if (pointA && pointB === undefined) {
  31827. if (_this.panningSensibility !== 0 &&
  31828. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  31829. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  31830. _this.camera
  31831. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  31832. _this.camera
  31833. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  31834. }
  31835. else {
  31836. var offsetX = evt.clientX - cacheSoloPointer.x;
  31837. var offsetY = evt.clientY - cacheSoloPointer.y;
  31838. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31839. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31840. }
  31841. cacheSoloPointer.x = evt.clientX;
  31842. cacheSoloPointer.y = evt.clientY;
  31843. }
  31844. else if (pointA && pointB) {
  31845. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  31846. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  31847. ed.x = evt.clientX;
  31848. ed.y = evt.clientY;
  31849. var direction = _this.pinchInwards ? 1 : -1;
  31850. var distX = pointA.x - pointB.x;
  31851. var distY = pointA.y - pointB.y;
  31852. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  31853. if (previousPinchDistance === 0) {
  31854. previousPinchDistance = pinchSquaredDistance;
  31855. return;
  31856. }
  31857. if (pinchSquaredDistance !== previousPinchDistance) {
  31858. _this.camera
  31859. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  31860. (_this.pinchPrecision *
  31861. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  31862. direction);
  31863. previousPinchDistance = pinchSquaredDistance;
  31864. }
  31865. }
  31866. }
  31867. };
  31868. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31869. this._onContextMenu = function (evt) {
  31870. evt.preventDefault();
  31871. };
  31872. if (!this.camera._useCtrlForPanning) {
  31873. element.addEventListener("contextmenu", this._onContextMenu, false);
  31874. }
  31875. this._onLostFocus = function () {
  31876. //this._keys = [];
  31877. pointA = pointB = undefined;
  31878. previousPinchDistance = 0;
  31879. cacheSoloPointer = null;
  31880. };
  31881. this._onMouseMove = function (evt) {
  31882. if (!engine.isPointerLock) {
  31883. return;
  31884. }
  31885. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31886. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31887. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31888. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31889. if (!noPreventDefault) {
  31890. evt.preventDefault();
  31891. }
  31892. };
  31893. this._onGestureStart = function (e) {
  31894. if (window.MSGesture === undefined) {
  31895. return;
  31896. }
  31897. if (!_this._MSGestureHandler) {
  31898. _this._MSGestureHandler = new MSGesture();
  31899. _this._MSGestureHandler.target = element;
  31900. }
  31901. _this._MSGestureHandler.addPointer(e.pointerId);
  31902. };
  31903. this._onGesture = function (e) {
  31904. _this.camera.radius *= e.scale;
  31905. if (e.preventDefault) {
  31906. if (!noPreventDefault) {
  31907. e.stopPropagation();
  31908. e.preventDefault();
  31909. }
  31910. }
  31911. };
  31912. element.addEventListener("mousemove", this._onMouseMove, false);
  31913. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  31914. element.addEventListener("MSGestureChange", this._onGesture, false);
  31915. BABYLON.Tools.RegisterTopRootEvents([
  31916. { name: "blur", handler: this._onLostFocus }
  31917. ]);
  31918. };
  31919. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  31920. BABYLON.Tools.UnregisterTopRootEvents([
  31921. { name: "blur", handler: this._onLostFocus }
  31922. ]);
  31923. if (element && this._observer) {
  31924. this.camera.getScene().onPointerObservable.remove(this._observer);
  31925. this._observer = null;
  31926. element.removeEventListener("contextmenu", this._onContextMenu);
  31927. element.removeEventListener("mousemove", this._onMouseMove);
  31928. element.removeEventListener("MSPointerDown", this._onGestureStart);
  31929. element.removeEventListener("MSGestureChange", this._onGesture);
  31930. this._isPanClick = false;
  31931. this.pinchInwards = true;
  31932. this._onMouseMove = null;
  31933. this._onGestureStart = null;
  31934. this._onGesture = null;
  31935. this._MSGestureHandler = null;
  31936. this._onLostFocus = null;
  31937. this._onContextMenu = null;
  31938. }
  31939. };
  31940. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  31941. return "ArcRotateCameraPointersInput";
  31942. };
  31943. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  31944. return "pointers";
  31945. };
  31946. __decorate([
  31947. BABYLON.serialize()
  31948. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  31949. __decorate([
  31950. BABYLON.serialize()
  31951. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  31952. __decorate([
  31953. BABYLON.serialize()
  31954. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  31955. __decorate([
  31956. BABYLON.serialize()
  31957. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  31958. __decorate([
  31959. BABYLON.serialize()
  31960. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  31961. return ArcRotateCameraPointersInput;
  31962. }());
  31963. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  31964. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  31965. })(BABYLON || (BABYLON = {}));
  31966. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  31967. /// <reference path="babylon.targetCamera.ts" />
  31968. /// <reference path="..\Tools\babylon.tools.ts" />
  31969. var BABYLON;
  31970. (function (BABYLON) {
  31971. var ArcRotateCamera = (function (_super) {
  31972. __extends(ArcRotateCamera, _super);
  31973. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  31974. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  31975. _this.inertialAlphaOffset = 0;
  31976. _this.inertialBetaOffset = 0;
  31977. _this.inertialRadiusOffset = 0;
  31978. _this.lowerAlphaLimit = null;
  31979. _this.upperAlphaLimit = null;
  31980. _this.lowerBetaLimit = 0.01;
  31981. _this.upperBetaLimit = Math.PI;
  31982. _this.lowerRadiusLimit = null;
  31983. _this.upperRadiusLimit = null;
  31984. _this.inertialPanningX = 0;
  31985. _this.inertialPanningY = 0;
  31986. _this.panningInertia = 0.9;
  31987. //-- end properties for backward compatibility for inputs
  31988. _this.zoomOnFactor = 1;
  31989. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  31990. _this.allowUpsideDown = true;
  31991. _this._viewMatrix = new BABYLON.Matrix();
  31992. // Panning
  31993. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  31994. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  31995. _this.checkCollisions = false;
  31996. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31997. _this._previousPosition = BABYLON.Vector3.Zero();
  31998. _this._collisionVelocity = BABYLON.Vector3.Zero();
  31999. _this._newPosition = BABYLON.Vector3.Zero();
  32000. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32001. if (collidedMesh === void 0) { collidedMesh = null; }
  32002. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  32003. newPosition.multiplyInPlace(_this._collider.radius);
  32004. }
  32005. if (!collidedMesh) {
  32006. _this._previousPosition.copyFrom(_this.position);
  32007. }
  32008. else {
  32009. _this.setPosition(newPosition);
  32010. if (_this.onCollide) {
  32011. _this.onCollide(collidedMesh);
  32012. }
  32013. }
  32014. // Recompute because of constraints
  32015. var cosa = Math.cos(_this.alpha);
  32016. var sina = Math.sin(_this.alpha);
  32017. var cosb = Math.cos(_this.beta);
  32018. var sinb = Math.sin(_this.beta);
  32019. if (sinb === 0) {
  32020. sinb = 0.0001;
  32021. }
  32022. var target = _this._getTargetPosition();
  32023. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  32024. _this.position.copyFrom(_this._newPosition);
  32025. var up = _this.upVector;
  32026. if (_this.allowUpsideDown && _this.beta < 0) {
  32027. up = up.clone();
  32028. up = up.negate();
  32029. }
  32030. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  32031. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  32032. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  32033. _this._collisionTriggered = false;
  32034. };
  32035. _this._target = BABYLON.Vector3.Zero();
  32036. if (target) {
  32037. _this.setTarget(target);
  32038. }
  32039. _this.alpha = alpha;
  32040. _this.beta = beta;
  32041. _this.radius = radius;
  32042. _this.getViewMatrix();
  32043. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  32044. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  32045. return _this;
  32046. }
  32047. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  32048. get: function () {
  32049. return this._target;
  32050. },
  32051. set: function (value) {
  32052. this.setTarget(value);
  32053. },
  32054. enumerable: true,
  32055. configurable: true
  32056. });
  32057. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  32058. //-- begin properties for backward compatibility for inputs
  32059. get: function () {
  32060. var pointers = this.inputs.attached["pointers"];
  32061. if (pointers)
  32062. return pointers.angularSensibilityX;
  32063. },
  32064. set: function (value) {
  32065. var pointers = this.inputs.attached["pointers"];
  32066. if (pointers) {
  32067. pointers.angularSensibilityX = value;
  32068. }
  32069. },
  32070. enumerable: true,
  32071. configurable: true
  32072. });
  32073. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  32074. get: function () {
  32075. var pointers = this.inputs.attached["pointers"];
  32076. if (pointers)
  32077. return pointers.angularSensibilityY;
  32078. },
  32079. set: function (value) {
  32080. var pointers = this.inputs.attached["pointers"];
  32081. if (pointers) {
  32082. pointers.angularSensibilityY = value;
  32083. }
  32084. },
  32085. enumerable: true,
  32086. configurable: true
  32087. });
  32088. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  32089. get: function () {
  32090. var pointers = this.inputs.attached["pointers"];
  32091. if (pointers)
  32092. return pointers.pinchPrecision;
  32093. },
  32094. set: function (value) {
  32095. var pointers = this.inputs.attached["pointers"];
  32096. if (pointers) {
  32097. pointers.pinchPrecision = value;
  32098. }
  32099. },
  32100. enumerable: true,
  32101. configurable: true
  32102. });
  32103. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  32104. get: function () {
  32105. var pointers = this.inputs.attached["pointers"];
  32106. if (pointers)
  32107. return pointers.panningSensibility;
  32108. },
  32109. set: function (value) {
  32110. var pointers = this.inputs.attached["pointers"];
  32111. if (pointers) {
  32112. pointers.panningSensibility = value;
  32113. }
  32114. },
  32115. enumerable: true,
  32116. configurable: true
  32117. });
  32118. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  32119. get: function () {
  32120. var keyboard = this.inputs.attached["keyboard"];
  32121. if (keyboard)
  32122. return keyboard.keysUp;
  32123. },
  32124. set: function (value) {
  32125. var keyboard = this.inputs.attached["keyboard"];
  32126. if (keyboard)
  32127. keyboard.keysUp = value;
  32128. },
  32129. enumerable: true,
  32130. configurable: true
  32131. });
  32132. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  32133. get: function () {
  32134. var keyboard = this.inputs.attached["keyboard"];
  32135. if (keyboard)
  32136. return keyboard.keysDown;
  32137. },
  32138. set: function (value) {
  32139. var keyboard = this.inputs.attached["keyboard"];
  32140. if (keyboard)
  32141. keyboard.keysDown = value;
  32142. },
  32143. enumerable: true,
  32144. configurable: true
  32145. });
  32146. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  32147. get: function () {
  32148. var keyboard = this.inputs.attached["keyboard"];
  32149. if (keyboard)
  32150. return keyboard.keysLeft;
  32151. },
  32152. set: function (value) {
  32153. var keyboard = this.inputs.attached["keyboard"];
  32154. if (keyboard)
  32155. keyboard.keysLeft = value;
  32156. },
  32157. enumerable: true,
  32158. configurable: true
  32159. });
  32160. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  32161. get: function () {
  32162. var keyboard = this.inputs.attached["keyboard"];
  32163. if (keyboard)
  32164. return keyboard.keysRight;
  32165. },
  32166. set: function (value) {
  32167. var keyboard = this.inputs.attached["keyboard"];
  32168. if (keyboard)
  32169. keyboard.keysRight = value;
  32170. },
  32171. enumerable: true,
  32172. configurable: true
  32173. });
  32174. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  32175. get: function () {
  32176. var mousewheel = this.inputs.attached["mousewheel"];
  32177. if (mousewheel)
  32178. return mousewheel.wheelPrecision;
  32179. },
  32180. set: function (value) {
  32181. var mousewheel = this.inputs.attached["mousewheel"];
  32182. if (mousewheel)
  32183. mousewheel.wheelPrecision = value;
  32184. },
  32185. enumerable: true,
  32186. configurable: true
  32187. });
  32188. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  32189. get: function () {
  32190. return this._bouncingBehavior;
  32191. },
  32192. enumerable: true,
  32193. configurable: true
  32194. });
  32195. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  32196. get: function () {
  32197. return this._bouncingBehavior != null;
  32198. },
  32199. set: function (value) {
  32200. if (value === this.useBouncingBehavior) {
  32201. return;
  32202. }
  32203. if (value) {
  32204. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  32205. this.addBehavior(this._bouncingBehavior);
  32206. }
  32207. else {
  32208. this.removeBehavior(this._bouncingBehavior);
  32209. this._bouncingBehavior = null;
  32210. }
  32211. },
  32212. enumerable: true,
  32213. configurable: true
  32214. });
  32215. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  32216. get: function () {
  32217. return this._framingBehavior;
  32218. },
  32219. enumerable: true,
  32220. configurable: true
  32221. });
  32222. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  32223. get: function () {
  32224. return this._framingBehavior != null;
  32225. },
  32226. set: function (value) {
  32227. if (value === this.useFramingBehavior) {
  32228. return;
  32229. }
  32230. if (value) {
  32231. this._framingBehavior = new BABYLON.FramingBehavior();
  32232. this.addBehavior(this._framingBehavior);
  32233. }
  32234. else {
  32235. this.removeBehavior(this._framingBehavior);
  32236. this._framingBehavior = null;
  32237. }
  32238. },
  32239. enumerable: true,
  32240. configurable: true
  32241. });
  32242. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  32243. get: function () {
  32244. return this._autoRotationBehavior;
  32245. },
  32246. enumerable: true,
  32247. configurable: true
  32248. });
  32249. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  32250. get: function () {
  32251. return this._autoRotationBehavior != null;
  32252. },
  32253. set: function (value) {
  32254. if (value === this.useAutoRotationBehavior) {
  32255. return;
  32256. }
  32257. if (value) {
  32258. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  32259. this.addBehavior(this._autoRotationBehavior);
  32260. }
  32261. else {
  32262. this.removeBehavior(this._autoRotationBehavior);
  32263. this._autoRotationBehavior = null;
  32264. }
  32265. },
  32266. enumerable: true,
  32267. configurable: true
  32268. });
  32269. // Cache
  32270. ArcRotateCamera.prototype._initCache = function () {
  32271. _super.prototype._initCache.call(this);
  32272. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32273. this._cache.alpha = undefined;
  32274. this._cache.beta = undefined;
  32275. this._cache.radius = undefined;
  32276. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  32277. };
  32278. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  32279. if (!ignoreParentClass) {
  32280. _super.prototype._updateCache.call(this);
  32281. }
  32282. this._cache._target.copyFrom(this._getTargetPosition());
  32283. this._cache.alpha = this.alpha;
  32284. this._cache.beta = this.beta;
  32285. this._cache.radius = this.radius;
  32286. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32287. };
  32288. ArcRotateCamera.prototype._getTargetPosition = function () {
  32289. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32290. var pos = this._targetHost.getAbsolutePosition();
  32291. if (this._targetBoundingCenter) {
  32292. pos.addToRef(this._targetBoundingCenter, this._target);
  32293. }
  32294. else {
  32295. this._target.copyFrom(pos);
  32296. }
  32297. }
  32298. var lockedTargetPosition = this._getLockedTargetPosition();
  32299. if (lockedTargetPosition) {
  32300. return lockedTargetPosition;
  32301. }
  32302. return this._target;
  32303. };
  32304. // Synchronized
  32305. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32306. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32307. return false;
  32308. return this._cache._target.equals(this._getTargetPosition())
  32309. && this._cache.alpha === this.alpha
  32310. && this._cache.beta === this.beta
  32311. && this._cache.radius === this.radius
  32312. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32313. };
  32314. // Methods
  32315. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32316. var _this = this;
  32317. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32318. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32319. this._useCtrlForPanning = useCtrlForPanning;
  32320. this._panningMouseButton = panningMouseButton;
  32321. this.inputs.attachElement(element, noPreventDefault);
  32322. this._reset = function () {
  32323. _this.inertialAlphaOffset = 0;
  32324. _this.inertialBetaOffset = 0;
  32325. _this.inertialRadiusOffset = 0;
  32326. };
  32327. };
  32328. ArcRotateCamera.prototype.detachControl = function (element) {
  32329. this.inputs.detachElement(element);
  32330. if (this._reset) {
  32331. this._reset();
  32332. }
  32333. };
  32334. ArcRotateCamera.prototype._checkInputs = function () {
  32335. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32336. if (this._collisionTriggered) {
  32337. return;
  32338. }
  32339. this.inputs.checkInputs();
  32340. // Inertia
  32341. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32342. if (this.getScene().useRightHandedSystem) {
  32343. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32344. }
  32345. else {
  32346. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32347. }
  32348. this.beta += this.inertialBetaOffset;
  32349. this.radius -= this.inertialRadiusOffset;
  32350. this.inertialAlphaOffset *= this.inertia;
  32351. this.inertialBetaOffset *= this.inertia;
  32352. this.inertialRadiusOffset *= this.inertia;
  32353. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  32354. this.inertialAlphaOffset = 0;
  32355. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  32356. this.inertialBetaOffset = 0;
  32357. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32358. this.inertialRadiusOffset = 0;
  32359. }
  32360. // Panning inertia
  32361. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32362. if (!this._localDirection) {
  32363. this._localDirection = BABYLON.Vector3.Zero();
  32364. this._transformedDirection = BABYLON.Vector3.Zero();
  32365. }
  32366. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32367. this._localDirection.multiplyInPlace(this.panningAxis);
  32368. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32369. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32370. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32371. if (!this.panningAxis.y) {
  32372. this._transformedDirection.y = 0;
  32373. }
  32374. if (!this._targetHost) {
  32375. this._target.addInPlace(this._transformedDirection);
  32376. }
  32377. this.inertialPanningX *= this.panningInertia;
  32378. this.inertialPanningY *= this.panningInertia;
  32379. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32380. this.inertialPanningX = 0;
  32381. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32382. this.inertialPanningY = 0;
  32383. }
  32384. // Limits
  32385. this._checkLimits();
  32386. _super.prototype._checkInputs.call(this);
  32387. };
  32388. ArcRotateCamera.prototype._checkLimits = function () {
  32389. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32390. if (this.allowUpsideDown && this.beta > Math.PI) {
  32391. this.beta = this.beta - (2 * Math.PI);
  32392. }
  32393. }
  32394. else {
  32395. if (this.beta < this.lowerBetaLimit) {
  32396. this.beta = this.lowerBetaLimit;
  32397. }
  32398. }
  32399. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32400. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32401. this.beta = this.beta + (2 * Math.PI);
  32402. }
  32403. }
  32404. else {
  32405. if (this.beta > this.upperBetaLimit) {
  32406. this.beta = this.upperBetaLimit;
  32407. }
  32408. }
  32409. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32410. this.alpha = this.lowerAlphaLimit;
  32411. }
  32412. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32413. this.alpha = this.upperAlphaLimit;
  32414. }
  32415. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32416. this.radius = this.lowerRadiusLimit;
  32417. }
  32418. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32419. this.radius = this.upperRadiusLimit;
  32420. }
  32421. };
  32422. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32423. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32424. this.radius = radiusv3.length();
  32425. if (this.radius === 0) {
  32426. this.radius = 0.0001; // Just to avoid division by zero
  32427. }
  32428. // Alpha
  32429. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32430. if (radiusv3.z < 0) {
  32431. this.alpha = 2 * Math.PI - this.alpha;
  32432. }
  32433. // Beta
  32434. this.beta = Math.acos(radiusv3.y / this.radius);
  32435. this._checkLimits();
  32436. };
  32437. ArcRotateCamera.prototype.setPosition = function (position) {
  32438. if (this.position.equals(position)) {
  32439. return;
  32440. }
  32441. this.position.copyFrom(position);
  32442. this.rebuildAnglesAndRadius();
  32443. };
  32444. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32445. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32446. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32447. if (target.getBoundingInfo) {
  32448. if (toBoundingCenter) {
  32449. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32450. }
  32451. else {
  32452. this._targetBoundingCenter = null;
  32453. }
  32454. this._targetHost = target;
  32455. this._target = this._getTargetPosition();
  32456. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  32457. }
  32458. else {
  32459. var newTarget = target;
  32460. var currentTarget = this._getTargetPosition();
  32461. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32462. return;
  32463. }
  32464. this._targetHost = null;
  32465. this._target = newTarget;
  32466. this._targetBoundingCenter = null;
  32467. this.onMeshTargetChangedObservable.notifyObservers(null);
  32468. }
  32469. this.rebuildAnglesAndRadius();
  32470. };
  32471. ArcRotateCamera.prototype._getViewMatrix = function () {
  32472. // Compute
  32473. var cosa = Math.cos(this.alpha);
  32474. var sina = Math.sin(this.alpha);
  32475. var cosb = Math.cos(this.beta);
  32476. var sinb = Math.sin(this.beta);
  32477. if (sinb === 0) {
  32478. sinb = 0.0001;
  32479. }
  32480. var target = this._getTargetPosition();
  32481. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32482. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32483. if (!this._collider) {
  32484. this._collider = new BABYLON.Collider();
  32485. }
  32486. this._collider.radius = this.collisionRadius;
  32487. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32488. this._collisionTriggered = true;
  32489. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32490. }
  32491. else {
  32492. this.position.copyFrom(this._newPosition);
  32493. var up = this.upVector;
  32494. if (this.allowUpsideDown && sinb < 0) {
  32495. up = up.clone();
  32496. up = up.negate();
  32497. }
  32498. if (this.getScene().useRightHandedSystem) {
  32499. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32500. }
  32501. else {
  32502. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32503. }
  32504. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32505. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32506. }
  32507. this._currentTarget = target;
  32508. return this._viewMatrix;
  32509. };
  32510. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32511. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32512. meshes = meshes || this.getScene().meshes;
  32513. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32514. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32515. this.radius = distance * this.zoomOnFactor;
  32516. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32517. };
  32518. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32519. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32520. var meshesOrMinMaxVector;
  32521. var distance;
  32522. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32523. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32524. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32525. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32526. }
  32527. else {
  32528. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32529. distance = meshesOrMinMaxVectorAndDistance.distance;
  32530. }
  32531. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32532. if (!doNotUpdateMaxZ) {
  32533. this.maxZ = distance * 2;
  32534. }
  32535. };
  32536. /**
  32537. * @override
  32538. * Override Camera.createRigCamera
  32539. */
  32540. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32541. var alphaShift;
  32542. switch (this.cameraRigMode) {
  32543. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32544. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32545. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32546. case BABYLON.Camera.RIG_MODE_VR:
  32547. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32548. break;
  32549. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32550. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32551. break;
  32552. }
  32553. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32554. rigCam._cameraRigParams = {};
  32555. return rigCam;
  32556. };
  32557. /**
  32558. * @override
  32559. * Override Camera._updateRigCameras
  32560. */
  32561. ArcRotateCamera.prototype._updateRigCameras = function () {
  32562. var camLeft = this._rigCameras[0];
  32563. var camRight = this._rigCameras[1];
  32564. camLeft.beta = camRight.beta = this.beta;
  32565. camLeft.radius = camRight.radius = this.radius;
  32566. switch (this.cameraRigMode) {
  32567. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32568. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32569. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32570. case BABYLON.Camera.RIG_MODE_VR:
  32571. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32572. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32573. break;
  32574. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32575. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32576. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32577. break;
  32578. }
  32579. _super.prototype._updateRigCameras.call(this);
  32580. };
  32581. ArcRotateCamera.prototype.dispose = function () {
  32582. this.inputs.clear();
  32583. _super.prototype.dispose.call(this);
  32584. };
  32585. ArcRotateCamera.prototype.getClassName = function () {
  32586. return "ArcRotateCamera";
  32587. };
  32588. __decorate([
  32589. BABYLON.serialize()
  32590. ], ArcRotateCamera.prototype, "alpha", void 0);
  32591. __decorate([
  32592. BABYLON.serialize()
  32593. ], ArcRotateCamera.prototype, "beta", void 0);
  32594. __decorate([
  32595. BABYLON.serialize()
  32596. ], ArcRotateCamera.prototype, "radius", void 0);
  32597. __decorate([
  32598. BABYLON.serializeAsVector3("target")
  32599. ], ArcRotateCamera.prototype, "_target", void 0);
  32600. __decorate([
  32601. BABYLON.serialize()
  32602. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  32603. __decorate([
  32604. BABYLON.serialize()
  32605. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  32606. __decorate([
  32607. BABYLON.serialize()
  32608. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  32609. __decorate([
  32610. BABYLON.serialize()
  32611. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  32612. __decorate([
  32613. BABYLON.serialize()
  32614. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  32615. __decorate([
  32616. BABYLON.serialize()
  32617. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  32618. __decorate([
  32619. BABYLON.serialize()
  32620. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  32621. __decorate([
  32622. BABYLON.serialize()
  32623. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  32624. __decorate([
  32625. BABYLON.serialize()
  32626. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  32627. __decorate([
  32628. BABYLON.serialize()
  32629. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  32630. __decorate([
  32631. BABYLON.serialize()
  32632. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  32633. __decorate([
  32634. BABYLON.serialize()
  32635. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  32636. __decorate([
  32637. BABYLON.serialize()
  32638. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  32639. __decorate([
  32640. BABYLON.serialize()
  32641. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  32642. return ArcRotateCamera;
  32643. }(BABYLON.TargetCamera));
  32644. BABYLON.ArcRotateCamera = ArcRotateCamera;
  32645. })(BABYLON || (BABYLON = {}));
  32646. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  32647. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  32648. var BABYLON;
  32649. (function (BABYLON) {
  32650. var ArcRotateCameraInputsManager = (function (_super) {
  32651. __extends(ArcRotateCameraInputsManager, _super);
  32652. function ArcRotateCameraInputsManager(camera) {
  32653. return _super.call(this, camera) || this;
  32654. }
  32655. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  32656. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  32657. return this;
  32658. };
  32659. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  32660. this.add(new BABYLON.ArcRotateCameraPointersInput());
  32661. return this;
  32662. };
  32663. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  32664. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  32665. return this;
  32666. };
  32667. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  32668. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  32669. return this;
  32670. };
  32671. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  32672. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  32673. return this;
  32674. };
  32675. return ArcRotateCameraInputsManager;
  32676. }(BABYLON.CameraInputsManager));
  32677. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  32678. })(BABYLON || (BABYLON = {}));
  32679. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  32680. var BABYLON;
  32681. (function (BABYLON) {
  32682. var CubeTexture = (function (_super) {
  32683. __extends(CubeTexture, _super);
  32684. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  32685. if (onLoad === void 0) { onLoad = null; }
  32686. if (onError === void 0) { onError = null; }
  32687. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32688. if (prefiltered === void 0) { prefiltered = false; }
  32689. if (forcedExtension === void 0) { forcedExtension = null; }
  32690. var _this = _super.call(this, scene) || this;
  32691. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  32692. _this.name = rootUrl;
  32693. _this.url = rootUrl;
  32694. _this._noMipmap = noMipmap;
  32695. _this.hasAlpha = false;
  32696. _this._format = format;
  32697. _this._prefiltered = prefiltered;
  32698. _this.isCube = true;
  32699. _this._textureMatrix = BABYLON.Matrix.Identity();
  32700. if (prefiltered) {
  32701. _this.gammaSpace = false;
  32702. }
  32703. if (!rootUrl && !files) {
  32704. return _this;
  32705. }
  32706. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  32707. if (!files) {
  32708. if (!extensions) {
  32709. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  32710. }
  32711. files = [];
  32712. for (var index = 0; index < extensions.length; index++) {
  32713. files.push(rootUrl + extensions[index]);
  32714. }
  32715. _this._extensions = extensions;
  32716. }
  32717. _this._files = files;
  32718. if (!_this._texture) {
  32719. if (!scene.useDelayedTextureLoading) {
  32720. if (prefiltered) {
  32721. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  32722. }
  32723. else {
  32724. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  32725. }
  32726. }
  32727. else {
  32728. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32729. }
  32730. }
  32731. else if (onLoad) {
  32732. if (_this._texture.isReady) {
  32733. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  32734. }
  32735. else {
  32736. _this._texture.onLoadedObservable.add(onLoad);
  32737. }
  32738. }
  32739. return _this;
  32740. }
  32741. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  32742. return new CubeTexture("", scene, null, noMipmap, files);
  32743. };
  32744. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  32745. if (forcedExtension === void 0) { forcedExtension = null; }
  32746. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  32747. };
  32748. // Methods
  32749. CubeTexture.prototype.delayLoad = function () {
  32750. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32751. return;
  32752. }
  32753. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32754. this._texture = this._getFromCache(this.url, this._noMipmap);
  32755. if (!this._texture) {
  32756. if (this._prefiltered) {
  32757. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  32758. }
  32759. else {
  32760. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  32761. }
  32762. }
  32763. };
  32764. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  32765. return this._textureMatrix;
  32766. };
  32767. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  32768. this._textureMatrix = value;
  32769. };
  32770. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32771. var texture = BABYLON.SerializationHelper.Parse(function () {
  32772. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  32773. }, parsedTexture, scene);
  32774. // Animations
  32775. if (parsedTexture.animations) {
  32776. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32777. var parsedAnimation = parsedTexture.animations[animationIndex];
  32778. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32779. }
  32780. }
  32781. return texture;
  32782. };
  32783. CubeTexture.prototype.clone = function () {
  32784. var _this = this;
  32785. return BABYLON.SerializationHelper.Clone(function () {
  32786. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  32787. }, this);
  32788. };
  32789. return CubeTexture;
  32790. }(BABYLON.BaseTexture));
  32791. BABYLON.CubeTexture = CubeTexture;
  32792. })(BABYLON || (BABYLON = {}));
  32793. //# sourceMappingURL=babylon.cubeTexture.js.map
  32794. var BABYLON;
  32795. (function (BABYLON) {
  32796. var RenderTargetTexture = (function (_super) {
  32797. __extends(RenderTargetTexture, _super);
  32798. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  32799. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  32800. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32801. if (isCube === void 0) { isCube = false; }
  32802. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32803. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  32804. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  32805. if (isMulti === void 0) { isMulti = false; }
  32806. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  32807. _this.isCube = isCube;
  32808. /**
  32809. * Use this list to define the list of mesh you want to render.
  32810. */
  32811. _this.renderList = new Array();
  32812. _this.renderParticles = true;
  32813. _this.renderSprites = false;
  32814. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  32815. _this.ignoreCameraViewport = false;
  32816. // Events
  32817. /**
  32818. * An event triggered when the texture is unbind.
  32819. * @type {BABYLON.Observable}
  32820. */
  32821. _this.onBeforeBindObservable = new BABYLON.Observable();
  32822. /**
  32823. * An event triggered when the texture is unbind.
  32824. * @type {BABYLON.Observable}
  32825. */
  32826. _this.onAfterUnbindObservable = new BABYLON.Observable();
  32827. /**
  32828. * An event triggered before rendering the texture
  32829. * @type {BABYLON.Observable}
  32830. */
  32831. _this.onBeforeRenderObservable = new BABYLON.Observable();
  32832. /**
  32833. * An event triggered after rendering the texture
  32834. * @type {BABYLON.Observable}
  32835. */
  32836. _this.onAfterRenderObservable = new BABYLON.Observable();
  32837. /**
  32838. * An event triggered after the texture clear
  32839. * @type {BABYLON.Observable}
  32840. */
  32841. _this.onClearObservable = new BABYLON.Observable();
  32842. _this._currentRefreshId = -1;
  32843. _this._refreshRate = 1;
  32844. _this._samples = 1;
  32845. scene = _this.getScene();
  32846. _this.name = name;
  32847. _this.isRenderTarget = true;
  32848. _this._size = size;
  32849. _this._generateMipMaps = generateMipMaps;
  32850. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  32851. // Rendering groups
  32852. _this._renderingManager = new BABYLON.RenderingManager(scene);
  32853. if (isMulti) {
  32854. return _this;
  32855. }
  32856. _this._renderTargetOptions = {
  32857. generateMipMaps: generateMipMaps,
  32858. type: type,
  32859. samplingMode: samplingMode,
  32860. generateDepthBuffer: generateDepthBuffer,
  32861. generateStencilBuffer: generateStencilBuffer
  32862. };
  32863. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  32864. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32865. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32866. }
  32867. if (isCube) {
  32868. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  32869. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  32870. _this._textureMatrix = BABYLON.Matrix.Identity();
  32871. }
  32872. else {
  32873. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  32874. }
  32875. return _this;
  32876. }
  32877. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  32878. get: function () {
  32879. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  32880. },
  32881. enumerable: true,
  32882. configurable: true
  32883. });
  32884. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  32885. get: function () {
  32886. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  32887. },
  32888. enumerable: true,
  32889. configurable: true
  32890. });
  32891. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  32892. get: function () {
  32893. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  32894. },
  32895. enumerable: true,
  32896. configurable: true
  32897. });
  32898. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  32899. set: function (callback) {
  32900. if (this._onAfterUnbindObserver) {
  32901. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  32902. }
  32903. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  32904. },
  32905. enumerable: true,
  32906. configurable: true
  32907. });
  32908. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  32909. set: function (callback) {
  32910. if (this._onBeforeRenderObserver) {
  32911. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32912. }
  32913. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32914. },
  32915. enumerable: true,
  32916. configurable: true
  32917. });
  32918. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  32919. set: function (callback) {
  32920. if (this._onAfterRenderObserver) {
  32921. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32922. }
  32923. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32924. },
  32925. enumerable: true,
  32926. configurable: true
  32927. });
  32928. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  32929. set: function (callback) {
  32930. if (this._onClearObserver) {
  32931. this.onClearObservable.remove(this._onClearObserver);
  32932. }
  32933. this._onClearObserver = this.onClearObservable.add(callback);
  32934. },
  32935. enumerable: true,
  32936. configurable: true
  32937. });
  32938. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  32939. get: function () {
  32940. return this._renderTargetOptions;
  32941. },
  32942. enumerable: true,
  32943. configurable: true
  32944. });
  32945. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  32946. get: function () {
  32947. return this._samples;
  32948. },
  32949. set: function (value) {
  32950. if (this._samples === value) {
  32951. return;
  32952. }
  32953. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  32954. },
  32955. enumerable: true,
  32956. configurable: true
  32957. });
  32958. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  32959. this._currentRefreshId = -1;
  32960. };
  32961. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  32962. get: function () {
  32963. return this._refreshRate;
  32964. },
  32965. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  32966. set: function (value) {
  32967. this._refreshRate = value;
  32968. this.resetRefreshCounter();
  32969. },
  32970. enumerable: true,
  32971. configurable: true
  32972. });
  32973. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  32974. if (!this._postProcessManager) {
  32975. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  32976. this._postProcesses = new Array();
  32977. }
  32978. this._postProcesses.push(postProcess);
  32979. this._postProcesses[0].autoClear = false;
  32980. };
  32981. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  32982. if (!this._postProcesses) {
  32983. return;
  32984. }
  32985. if (dispose) {
  32986. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  32987. var postProcess = _a[_i];
  32988. postProcess.dispose();
  32989. postProcess = null;
  32990. }
  32991. }
  32992. this._postProcesses = [];
  32993. };
  32994. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  32995. if (!this._postProcesses) {
  32996. return;
  32997. }
  32998. var index = this._postProcesses.indexOf(postProcess);
  32999. if (index === -1) {
  33000. return;
  33001. }
  33002. this._postProcesses.splice(index, 1);
  33003. if (this._postProcesses.length > 0) {
  33004. this._postProcesses[0].autoClear = false;
  33005. }
  33006. };
  33007. RenderTargetTexture.prototype._shouldRender = function () {
  33008. if (this._currentRefreshId === -1) {
  33009. this._currentRefreshId = 1;
  33010. return true;
  33011. }
  33012. if (this.refreshRate === this._currentRefreshId) {
  33013. this._currentRefreshId = 1;
  33014. return true;
  33015. }
  33016. this._currentRefreshId++;
  33017. return false;
  33018. };
  33019. RenderTargetTexture.prototype.getRenderSize = function () {
  33020. return this._size;
  33021. };
  33022. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  33023. get: function () {
  33024. return true;
  33025. },
  33026. enumerable: true,
  33027. configurable: true
  33028. });
  33029. RenderTargetTexture.prototype.scale = function (ratio) {
  33030. var newSize = this._size * ratio;
  33031. this.resize(newSize);
  33032. };
  33033. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  33034. if (this.isCube) {
  33035. return this._textureMatrix;
  33036. }
  33037. return _super.prototype.getReflectionTextureMatrix.call(this);
  33038. };
  33039. RenderTargetTexture.prototype.resize = function (size) {
  33040. this.releaseInternalTexture();
  33041. if (this.isCube) {
  33042. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  33043. }
  33044. else {
  33045. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  33046. }
  33047. };
  33048. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  33049. var scene = this.getScene();
  33050. var engine = scene.getEngine();
  33051. if (this.useCameraPostProcesses !== undefined) {
  33052. useCameraPostProcess = this.useCameraPostProcesses;
  33053. }
  33054. if (this._waitingRenderList) {
  33055. this.renderList = [];
  33056. for (var index = 0; index < this._waitingRenderList.length; index++) {
  33057. var id = this._waitingRenderList[index];
  33058. this.renderList.push(scene.getMeshByID(id));
  33059. }
  33060. delete this._waitingRenderList;
  33061. }
  33062. // Is predicate defined?
  33063. if (this.renderListPredicate) {
  33064. this.renderList.splice(0); // Clear previous renderList
  33065. var sceneMeshes = this.getScene().meshes;
  33066. for (var index = 0; index < sceneMeshes.length; index++) {
  33067. var mesh = sceneMeshes[index];
  33068. if (this.renderListPredicate(mesh)) {
  33069. this.renderList.push(mesh);
  33070. }
  33071. }
  33072. }
  33073. if (this.renderList && this.renderList.length === 0) {
  33074. return;
  33075. }
  33076. this.onBeforeBindObservable.notifyObservers(this);
  33077. // Set custom projection.
  33078. // Needs to be before binding to prevent changing the aspect ratio.
  33079. var camera;
  33080. if (this.activeCamera) {
  33081. camera = this.activeCamera;
  33082. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  33083. if (this.activeCamera !== scene.activeCamera) {
  33084. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  33085. }
  33086. }
  33087. else {
  33088. camera = scene.activeCamera;
  33089. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  33090. }
  33091. // Prepare renderingManager
  33092. this._renderingManager.reset();
  33093. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  33094. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  33095. var sceneRenderId = scene.getRenderId();
  33096. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  33097. var mesh = currentRenderList[meshIndex];
  33098. if (mesh) {
  33099. if (!mesh.isReady()) {
  33100. // Reset _currentRefreshId
  33101. this.resetRefreshCounter();
  33102. continue;
  33103. }
  33104. mesh._preActivateForIntermediateRendering(sceneRenderId);
  33105. var isMasked = void 0;
  33106. if (!this.renderList) {
  33107. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  33108. }
  33109. else {
  33110. isMasked = false;
  33111. }
  33112. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  33113. mesh._activate(sceneRenderId);
  33114. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33115. var subMesh = mesh.subMeshes[subIndex];
  33116. scene._activeIndices.addCount(subMesh.indexCount, false);
  33117. this._renderingManager.dispatch(subMesh);
  33118. }
  33119. }
  33120. }
  33121. }
  33122. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  33123. var particleSystem = scene.particleSystems[particleIndex];
  33124. var emitter = particleSystem.emitter;
  33125. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  33126. continue;
  33127. }
  33128. if (currentRenderList.indexOf(emitter) >= 0) {
  33129. this._renderingManager.dispatchParticles(particleSystem);
  33130. }
  33131. }
  33132. if (this.isCube) {
  33133. for (var face = 0; face < 6; face++) {
  33134. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33135. scene.incrementRenderId();
  33136. scene.resetCachedMaterial();
  33137. }
  33138. }
  33139. else {
  33140. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33141. }
  33142. this.onAfterUnbindObservable.notifyObservers(this);
  33143. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  33144. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  33145. }
  33146. engine.setViewport(scene.activeCamera.viewport);
  33147. scene.resetCachedMaterial();
  33148. };
  33149. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  33150. var _this = this;
  33151. var scene = this.getScene();
  33152. var engine = scene.getEngine();
  33153. // Bind
  33154. if (this._postProcessManager) {
  33155. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  33156. }
  33157. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  33158. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  33159. }
  33160. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  33161. // Clear
  33162. if (this.onClearObservable.hasObservers()) {
  33163. this.onClearObservable.notifyObservers(engine);
  33164. }
  33165. else {
  33166. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  33167. }
  33168. if (!this._doNotChangeAspectRatio) {
  33169. scene.updateTransformMatrix(true);
  33170. }
  33171. // Render
  33172. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  33173. if (this._postProcessManager) {
  33174. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  33175. }
  33176. else if (useCameraPostProcess) {
  33177. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  33178. }
  33179. if (!this._doNotChangeAspectRatio) {
  33180. scene.updateTransformMatrix(true);
  33181. }
  33182. // Dump ?
  33183. if (dumpForDebug) {
  33184. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  33185. }
  33186. // Unbind
  33187. if (!this.isCube || faceIndex === 5) {
  33188. if (this.isCube) {
  33189. if (faceIndex === 5) {
  33190. engine.generateMipMapsForCubemap(this._texture);
  33191. }
  33192. }
  33193. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  33194. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  33195. });
  33196. }
  33197. else {
  33198. this.onAfterRenderObservable.notifyObservers(faceIndex);
  33199. }
  33200. };
  33201. /**
  33202. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  33203. * This allowed control for front to back rendering or reversly depending of the special needs.
  33204. *
  33205. * @param renderingGroupId The rendering group id corresponding to its index
  33206. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  33207. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  33208. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  33209. */
  33210. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  33211. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  33212. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  33213. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  33214. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  33215. };
  33216. /**
  33217. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  33218. *
  33219. * @param renderingGroupId The rendering group id corresponding to its index
  33220. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  33221. */
  33222. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  33223. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  33224. };
  33225. RenderTargetTexture.prototype.clone = function () {
  33226. var textureSize = this.getSize();
  33227. 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);
  33228. // Base texture
  33229. newTexture.hasAlpha = this.hasAlpha;
  33230. newTexture.level = this.level;
  33231. // RenderTarget Texture
  33232. newTexture.coordinatesMode = this.coordinatesMode;
  33233. newTexture.renderList = this.renderList.slice(0);
  33234. return newTexture;
  33235. };
  33236. RenderTargetTexture.prototype.serialize = function () {
  33237. if (!this.name) {
  33238. return null;
  33239. }
  33240. var serializationObject = _super.prototype.serialize.call(this);
  33241. serializationObject.renderTargetSize = this.getRenderSize();
  33242. serializationObject.renderList = [];
  33243. for (var index = 0; index < this.renderList.length; index++) {
  33244. serializationObject.renderList.push(this.renderList[index].id);
  33245. }
  33246. return serializationObject;
  33247. };
  33248. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  33249. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  33250. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  33251. };
  33252. RenderTargetTexture.prototype.dispose = function () {
  33253. if (this._postProcessManager) {
  33254. this._postProcessManager.dispose();
  33255. this._postProcessManager = null;
  33256. }
  33257. this.clearPostProcesses(true);
  33258. this.renderList = null;
  33259. // Remove from custom render targets
  33260. var scene = this.getScene();
  33261. var index = scene.customRenderTargets.indexOf(this);
  33262. if (index >= 0) {
  33263. scene.customRenderTargets.splice(index, 1);
  33264. }
  33265. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  33266. var camera = _a[_i];
  33267. index = camera.customRenderTargets.indexOf(this);
  33268. if (index >= 0) {
  33269. camera.customRenderTargets.splice(index, 1);
  33270. }
  33271. }
  33272. _super.prototype.dispose.call(this);
  33273. };
  33274. RenderTargetTexture.prototype._rebuild = function () {
  33275. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  33276. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  33277. }
  33278. };
  33279. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  33280. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  33281. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  33282. return RenderTargetTexture;
  33283. }(BABYLON.Texture));
  33284. BABYLON.RenderTargetTexture = RenderTargetTexture;
  33285. })(BABYLON || (BABYLON = {}));
  33286. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  33287. var BABYLON;
  33288. (function (BABYLON) {
  33289. ;
  33290. var MultiRenderTarget = (function (_super) {
  33291. __extends(MultiRenderTarget, _super);
  33292. function MultiRenderTarget(name, size, count, scene, options) {
  33293. var _this = this;
  33294. options = options || {};
  33295. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  33296. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  33297. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  33298. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  33299. if (!_this.isSupported) {
  33300. _this.dispose();
  33301. return;
  33302. }
  33303. var types = [];
  33304. var samplingModes = [];
  33305. for (var i = 0; i < count; i++) {
  33306. if (options.types && options.types[i]) {
  33307. types.push(options.types[i]);
  33308. }
  33309. else {
  33310. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  33311. }
  33312. if (options.samplingModes && options.samplingModes[i]) {
  33313. samplingModes.push(options.samplingModes[i]);
  33314. }
  33315. else {
  33316. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33317. }
  33318. }
  33319. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  33320. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  33321. _this._count = count;
  33322. _this._size = size;
  33323. _this._multiRenderTargetOptions = {
  33324. samplingModes: samplingModes,
  33325. generateMipMaps: generateMipMaps,
  33326. generateDepthBuffer: generateDepthBuffer,
  33327. generateStencilBuffer: generateStencilBuffer,
  33328. generateDepthTexture: generateDepthTexture,
  33329. types: types,
  33330. textureCount: count
  33331. };
  33332. _this._internalTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  33333. _this._createInternalTextures();
  33334. return _this;
  33335. }
  33336. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  33337. get: function () {
  33338. var engine = this.getScene().getEngine();
  33339. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  33340. },
  33341. enumerable: true,
  33342. configurable: true
  33343. });
  33344. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  33345. get: function () {
  33346. return this._textures;
  33347. },
  33348. enumerable: true,
  33349. configurable: true
  33350. });
  33351. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  33352. get: function () {
  33353. return this._textures[this._textures.length - 1];
  33354. },
  33355. enumerable: true,
  33356. configurable: true
  33357. });
  33358. MultiRenderTarget.prototype._createInternalTextures = function () {
  33359. this._textures = [];
  33360. for (var i = 0; i < this._internalTextures.length; i++) {
  33361. var texture = new BABYLON.Texture(null, this.getScene());
  33362. texture._texture = this._internalTextures[i];
  33363. this._textures.push(texture);
  33364. }
  33365. // Keeps references to frame buffer and stencil/depth buffer
  33366. this._texture = this._internalTextures[0];
  33367. };
  33368. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  33369. get: function () {
  33370. return this._samples;
  33371. },
  33372. set: function (value) {
  33373. if (this._samples === value) {
  33374. return;
  33375. }
  33376. for (var i = 0; i < this._internalTextures.length; i++) {
  33377. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  33378. }
  33379. },
  33380. enumerable: true,
  33381. configurable: true
  33382. });
  33383. MultiRenderTarget.prototype.resize = function (size) {
  33384. this.releaseInternalTextures();
  33385. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  33386. this._createInternalTextures();
  33387. };
  33388. MultiRenderTarget.prototype.dispose = function () {
  33389. this.releaseInternalTextures();
  33390. _super.prototype.dispose.call(this);
  33391. };
  33392. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  33393. if (!this._internalTextures) {
  33394. return;
  33395. }
  33396. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  33397. if (this._internalTextures[i] !== undefined) {
  33398. this._internalTextures[i].dispose();
  33399. this._internalTextures.splice(i, 1);
  33400. }
  33401. }
  33402. };
  33403. return MultiRenderTarget;
  33404. }(BABYLON.RenderTargetTexture));
  33405. BABYLON.MultiRenderTarget = MultiRenderTarget;
  33406. })(BABYLON || (BABYLON = {}));
  33407. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  33408. /// <reference path="babylon.renderTargetTexture.ts" />
  33409. var BABYLON;
  33410. (function (BABYLON) {
  33411. var MirrorTexture = (function (_super) {
  33412. __extends(MirrorTexture, _super);
  33413. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  33414. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33415. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33416. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33417. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  33418. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  33419. _this._transformMatrix = BABYLON.Matrix.Zero();
  33420. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  33421. _this._blurKernelX = 0;
  33422. _this._blurKernelY = 0;
  33423. _this._blurRatio = 1.0;
  33424. _this.onBeforeRenderObservable.add(function () {
  33425. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  33426. _this._savedViewMatrix = scene.getViewMatrix();
  33427. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  33428. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  33429. scene.clipPlane = _this.mirrorPlane;
  33430. scene.getEngine().cullBackFaces = false;
  33431. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  33432. });
  33433. _this.onAfterRenderObservable.add(function () {
  33434. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  33435. scene.getEngine().cullBackFaces = true;
  33436. scene._mirroredCameraPosition = null;
  33437. delete scene.clipPlane;
  33438. });
  33439. return _this;
  33440. }
  33441. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  33442. get: function () {
  33443. return this._blurRatio;
  33444. },
  33445. set: function (value) {
  33446. if (this._blurRatio === value) {
  33447. return;
  33448. }
  33449. this._blurRatio = value;
  33450. this._preparePostProcesses();
  33451. },
  33452. enumerable: true,
  33453. configurable: true
  33454. });
  33455. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  33456. set: function (value) {
  33457. this.blurKernelX = value;
  33458. this.blurKernelY = value;
  33459. },
  33460. enumerable: true,
  33461. configurable: true
  33462. });
  33463. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  33464. get: function () {
  33465. return this._blurKernelX;
  33466. },
  33467. set: function (value) {
  33468. if (this._blurKernelX === value) {
  33469. return;
  33470. }
  33471. this._blurKernelX = value;
  33472. this._preparePostProcesses();
  33473. },
  33474. enumerable: true,
  33475. configurable: true
  33476. });
  33477. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  33478. get: function () {
  33479. return this._blurKernelY;
  33480. },
  33481. set: function (value) {
  33482. if (this._blurKernelY === value) {
  33483. return;
  33484. }
  33485. this._blurKernelY = value;
  33486. this._preparePostProcesses();
  33487. },
  33488. enumerable: true,
  33489. configurable: true
  33490. });
  33491. MirrorTexture.prototype._preparePostProcesses = function () {
  33492. this.clearPostProcesses(true);
  33493. if (this._blurKernelX && this._blurKernelY) {
  33494. var engine = this.getScene().getEngine();
  33495. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33496. 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);
  33497. this._blurX.autoClear = false;
  33498. if (this._blurRatio === 1 && this.samples < 2) {
  33499. this._blurX.outputTexture = this._texture;
  33500. }
  33501. else {
  33502. this._blurX.alwaysForcePOT = true;
  33503. }
  33504. 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);
  33505. this._blurY.autoClear = false;
  33506. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  33507. this.addPostProcess(this._blurX);
  33508. this.addPostProcess(this._blurY);
  33509. }
  33510. };
  33511. MirrorTexture.prototype.clone = function () {
  33512. var textureSize = this.getSize();
  33513. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  33514. // Base texture
  33515. newTexture.hasAlpha = this.hasAlpha;
  33516. newTexture.level = this.level;
  33517. // Mirror Texture
  33518. newTexture.mirrorPlane = this.mirrorPlane.clone();
  33519. newTexture.renderList = this.renderList.slice(0);
  33520. return newTexture;
  33521. };
  33522. MirrorTexture.prototype.serialize = function () {
  33523. if (!this.name) {
  33524. return null;
  33525. }
  33526. var serializationObject = _super.prototype.serialize.call(this);
  33527. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  33528. return serializationObject;
  33529. };
  33530. return MirrorTexture;
  33531. }(BABYLON.RenderTargetTexture));
  33532. BABYLON.MirrorTexture = MirrorTexture;
  33533. })(BABYLON || (BABYLON = {}));
  33534. //# sourceMappingURL=babylon.mirrorTexture.js.map
  33535. /// <reference path="babylon.renderTargetTexture.ts" />
  33536. var BABYLON;
  33537. (function (BABYLON) {
  33538. /**
  33539. * Creates a refraction texture used by refraction channel of the standard material.
  33540. * @param name the texture name
  33541. * @param size size of the underlying texture
  33542. * @param scene root scene
  33543. */
  33544. var RefractionTexture = (function (_super) {
  33545. __extends(RefractionTexture, _super);
  33546. function RefractionTexture(name, size, scene, generateMipMaps) {
  33547. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  33548. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  33549. _this.depth = 2.0;
  33550. _this.onBeforeRenderObservable.add(function () {
  33551. scene.clipPlane = _this.refractionPlane;
  33552. });
  33553. _this.onAfterRenderObservable.add(function () {
  33554. delete scene.clipPlane;
  33555. });
  33556. return _this;
  33557. }
  33558. RefractionTexture.prototype.clone = function () {
  33559. var textureSize = this.getSize();
  33560. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  33561. // Base texture
  33562. newTexture.hasAlpha = this.hasAlpha;
  33563. newTexture.level = this.level;
  33564. // Refraction Texture
  33565. newTexture.refractionPlane = this.refractionPlane.clone();
  33566. newTexture.renderList = this.renderList.slice(0);
  33567. newTexture.depth = this.depth;
  33568. return newTexture;
  33569. };
  33570. RefractionTexture.prototype.serialize = function () {
  33571. if (!this.name) {
  33572. return null;
  33573. }
  33574. var serializationObject = _super.prototype.serialize.call(this);
  33575. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  33576. serializationObject.depth = this.depth;
  33577. return serializationObject;
  33578. };
  33579. return RefractionTexture;
  33580. }(BABYLON.RenderTargetTexture));
  33581. BABYLON.RefractionTexture = RefractionTexture;
  33582. })(BABYLON || (BABYLON = {}));
  33583. //# sourceMappingURL=babylon.refractionTexture.js.map
  33584. /// <reference path="babylon.texture.ts" />
  33585. var BABYLON;
  33586. (function (BABYLON) {
  33587. var DynamicTexture = (function (_super) {
  33588. __extends(DynamicTexture, _super);
  33589. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  33590. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33591. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33592. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  33593. _this.name = name;
  33594. var engine = _this.getScene().getEngine();
  33595. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33596. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33597. _this._generateMipMaps = generateMipMaps;
  33598. if (options.getContext) {
  33599. _this._canvas = options;
  33600. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33601. }
  33602. else {
  33603. _this._canvas = document.createElement("canvas");
  33604. if (options.width) {
  33605. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33606. }
  33607. else {
  33608. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  33609. }
  33610. }
  33611. var textureSize = _this.getSize();
  33612. _this._canvas.width = textureSize.width;
  33613. _this._canvas.height = textureSize.height;
  33614. _this._context = _this._canvas.getContext("2d");
  33615. return _this;
  33616. }
  33617. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  33618. get: function () {
  33619. return true;
  33620. },
  33621. enumerable: true,
  33622. configurable: true
  33623. });
  33624. DynamicTexture.prototype._recreate = function (textureSize) {
  33625. this._canvas.width = textureSize.width;
  33626. this._canvas.height = textureSize.height;
  33627. this.releaseInternalTexture();
  33628. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  33629. };
  33630. DynamicTexture.prototype.scale = function (ratio) {
  33631. var textureSize = this.getSize();
  33632. textureSize.width *= ratio;
  33633. textureSize.height *= ratio;
  33634. this._recreate(textureSize);
  33635. };
  33636. DynamicTexture.prototype.scaleTo = function (width, height) {
  33637. var textureSize = this.getSize();
  33638. textureSize.width = width;
  33639. textureSize.height = height;
  33640. this._recreate(textureSize);
  33641. };
  33642. DynamicTexture.prototype.getContext = function () {
  33643. return this._context;
  33644. };
  33645. DynamicTexture.prototype.clear = function () {
  33646. var size = this.getSize();
  33647. this._context.fillRect(0, 0, size.width, size.height);
  33648. };
  33649. DynamicTexture.prototype.update = function (invertY) {
  33650. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  33651. };
  33652. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  33653. if (update === void 0) { update = true; }
  33654. var size = this.getSize();
  33655. if (clearColor) {
  33656. this._context.fillStyle = clearColor;
  33657. this._context.fillRect(0, 0, size.width, size.height);
  33658. }
  33659. this._context.font = font;
  33660. if (x === null || x === undefined) {
  33661. var textSize = this._context.measureText(text);
  33662. x = (size.width - textSize.width) / 2;
  33663. }
  33664. if (y === null || y === undefined) {
  33665. var fontSize = parseInt((font.replace(/\D/g, '')));
  33666. ;
  33667. y = (size.height / 2) + (fontSize / 3.65);
  33668. }
  33669. this._context.fillStyle = color;
  33670. this._context.fillText(text, x, y);
  33671. if (update) {
  33672. this.update(invertY);
  33673. }
  33674. };
  33675. DynamicTexture.prototype.clone = function () {
  33676. var textureSize = this.getSize();
  33677. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  33678. // Base texture
  33679. newTexture.hasAlpha = this.hasAlpha;
  33680. newTexture.level = this.level;
  33681. // Dynamic Texture
  33682. newTexture.wrapU = this.wrapU;
  33683. newTexture.wrapV = this.wrapV;
  33684. return newTexture;
  33685. };
  33686. DynamicTexture.prototype._rebuild = function () {
  33687. this.update();
  33688. };
  33689. return DynamicTexture;
  33690. }(BABYLON.Texture));
  33691. BABYLON.DynamicTexture = DynamicTexture;
  33692. })(BABYLON || (BABYLON = {}));
  33693. //# sourceMappingURL=babylon.dynamicTexture.js.map
  33694. var BABYLON;
  33695. (function (BABYLON) {
  33696. var VideoTexture = (function (_super) {
  33697. __extends(VideoTexture, _super);
  33698. /**
  33699. * Creates a video texture.
  33700. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  33701. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  33702. * @param {BABYLON.Scene} scene is obviously the current scene.
  33703. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  33704. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  33705. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  33706. */
  33707. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  33708. if (generateMipMaps === void 0) { generateMipMaps = false; }
  33709. if (invertY === void 0) { invertY = false; }
  33710. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33711. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33712. _this._autoLaunch = true;
  33713. var urls;
  33714. _this.name = name;
  33715. if (urlsOrVideo instanceof HTMLVideoElement) {
  33716. _this.video = urlsOrVideo;
  33717. }
  33718. else {
  33719. urls = urlsOrVideo;
  33720. _this.video = document.createElement("video");
  33721. _this.video.autoplay = false;
  33722. _this.video.loop = true;
  33723. }
  33724. _this._generateMipMaps = generateMipMaps;
  33725. _this._samplingMode = samplingMode;
  33726. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  33727. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33728. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33729. }
  33730. else {
  33731. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33732. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33733. _this._generateMipMaps = false;
  33734. }
  33735. if (urls) {
  33736. _this.video.addEventListener("canplay", function () {
  33737. _this._createTexture();
  33738. });
  33739. urls.forEach(function (url) {
  33740. var source = document.createElement("source");
  33741. source.src = url;
  33742. _this.video.appendChild(source);
  33743. });
  33744. }
  33745. else {
  33746. _this._createTexture();
  33747. }
  33748. _this._lastUpdate = BABYLON.Tools.Now;
  33749. return _this;
  33750. }
  33751. VideoTexture.prototype.__setTextureReady = function () {
  33752. this._texture.isReady = true;
  33753. };
  33754. VideoTexture.prototype._createTexture = function () {
  33755. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  33756. if (this._autoLaunch) {
  33757. this._autoLaunch = false;
  33758. this.video.play();
  33759. }
  33760. this._setTextureReady = this.__setTextureReady.bind(this);
  33761. this.video.addEventListener("playing", this._setTextureReady);
  33762. };
  33763. VideoTexture.prototype.update = function () {
  33764. var now = BABYLON.Tools.Now;
  33765. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  33766. return false;
  33767. }
  33768. this._lastUpdate = now;
  33769. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  33770. return true;
  33771. };
  33772. VideoTexture.prototype.dispose = function () {
  33773. _super.prototype.dispose.call(this);
  33774. this.video.removeEventListener("playing", this._setTextureReady);
  33775. };
  33776. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  33777. var video = document.createElement("video");
  33778. var constraintsDeviceId;
  33779. if (constraints && constraints.deviceId) {
  33780. constraintsDeviceId = {
  33781. exact: constraints.deviceId
  33782. };
  33783. }
  33784. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  33785. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  33786. if (navigator.getUserMedia) {
  33787. navigator.getUserMedia({
  33788. video: {
  33789. deviceId: constraintsDeviceId,
  33790. width: {
  33791. min: (constraints && constraints.minWidth) || 256,
  33792. max: (constraints && constraints.maxWidth) || 640
  33793. },
  33794. height: {
  33795. min: (constraints && constraints.minHeight) || 256,
  33796. max: (constraints && constraints.maxHeight) || 480
  33797. }
  33798. }
  33799. }, function (stream) {
  33800. if (video.mozSrcObject !== undefined) {
  33801. video.mozSrcObject = stream;
  33802. }
  33803. else {
  33804. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  33805. }
  33806. video.play();
  33807. if (onReady) {
  33808. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  33809. }
  33810. }, function (e) {
  33811. BABYLON.Tools.Error(e.name);
  33812. });
  33813. }
  33814. };
  33815. return VideoTexture;
  33816. }(BABYLON.Texture));
  33817. BABYLON.VideoTexture = VideoTexture;
  33818. })(BABYLON || (BABYLON = {}));
  33819. //# sourceMappingURL=babylon.videoTexture.js.map
  33820. var BABYLON;
  33821. (function (BABYLON) {
  33822. var RawTexture = (function (_super) {
  33823. __extends(RawTexture, _super);
  33824. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33825. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33826. if (invertY === void 0) { invertY = false; }
  33827. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33828. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33829. _this.format = format;
  33830. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33831. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33832. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33833. return _this;
  33834. }
  33835. RawTexture.prototype.update = function (data) {
  33836. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33837. };
  33838. // Statics
  33839. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33840. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33841. if (invertY === void 0) { invertY = false; }
  33842. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33843. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33844. };
  33845. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33846. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33847. if (invertY === void 0) { invertY = false; }
  33848. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33849. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33850. };
  33851. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33852. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33853. if (invertY === void 0) { invertY = false; }
  33854. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33855. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33856. };
  33857. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33858. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33859. if (invertY === void 0) { invertY = false; }
  33860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33861. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33862. };
  33863. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33864. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33865. if (invertY === void 0) { invertY = false; }
  33866. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33867. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33868. };
  33869. return RawTexture;
  33870. }(BABYLON.Texture));
  33871. BABYLON.RawTexture = RawTexture;
  33872. })(BABYLON || (BABYLON = {}));
  33873. //# sourceMappingURL=babylon.rawTexture.js.map
  33874. var BABYLON;
  33875. (function (BABYLON) {
  33876. var Internals;
  33877. (function (Internals) {
  33878. /*
  33879. * Based on jsTGALoader - Javascript loader for TGA file
  33880. * By Vincent Thibault
  33881. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  33882. */
  33883. var TGATools = (function () {
  33884. function TGATools() {
  33885. }
  33886. TGATools.GetTGAHeader = function (data) {
  33887. var offset = 0;
  33888. var header = {
  33889. id_length: data[offset++],
  33890. colormap_type: data[offset++],
  33891. image_type: data[offset++],
  33892. colormap_index: data[offset++] | data[offset++] << 8,
  33893. colormap_length: data[offset++] | data[offset++] << 8,
  33894. colormap_size: data[offset++],
  33895. origin: [
  33896. data[offset++] | data[offset++] << 8,
  33897. data[offset++] | data[offset++] << 8
  33898. ],
  33899. width: data[offset++] | data[offset++] << 8,
  33900. height: data[offset++] | data[offset++] << 8,
  33901. pixel_size: data[offset++],
  33902. flags: data[offset++]
  33903. };
  33904. return header;
  33905. };
  33906. TGATools.UploadContent = function (gl, data) {
  33907. // Not enough data to contain header ?
  33908. if (data.length < 19) {
  33909. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  33910. return;
  33911. }
  33912. // Read Header
  33913. var offset = 18;
  33914. var header = TGATools.GetTGAHeader(data);
  33915. // Assume it's a valid Targa file.
  33916. if (header.id_length + offset > data.length) {
  33917. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  33918. return;
  33919. }
  33920. // Skip not needed data
  33921. offset += header.id_length;
  33922. var use_rle = false;
  33923. var use_pal = false;
  33924. var use_rgb = false;
  33925. var use_grey = false;
  33926. // Get some informations.
  33927. switch (header.image_type) {
  33928. case TGATools._TYPE_RLE_INDEXED:
  33929. use_rle = true;
  33930. case TGATools._TYPE_INDEXED:
  33931. use_pal = true;
  33932. break;
  33933. case TGATools._TYPE_RLE_RGB:
  33934. use_rle = true;
  33935. case TGATools._TYPE_RGB:
  33936. use_rgb = true;
  33937. break;
  33938. case TGATools._TYPE_RLE_GREY:
  33939. use_rle = true;
  33940. case TGATools._TYPE_GREY:
  33941. use_grey = true;
  33942. break;
  33943. }
  33944. var pixel_data;
  33945. var numAlphaBits = header.flags & 0xf;
  33946. var pixel_size = header.pixel_size >> 3;
  33947. var pixel_total = header.width * header.height * pixel_size;
  33948. // Read palettes
  33949. var palettes;
  33950. if (use_pal) {
  33951. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  33952. }
  33953. // Read LRE
  33954. if (use_rle) {
  33955. pixel_data = new Uint8Array(pixel_total);
  33956. var c, count, i;
  33957. var localOffset = 0;
  33958. var pixels = new Uint8Array(pixel_size);
  33959. while (offset < pixel_total && localOffset < pixel_total) {
  33960. c = data[offset++];
  33961. count = (c & 0x7f) + 1;
  33962. // RLE pixels
  33963. if (c & 0x80) {
  33964. // Bind pixel tmp array
  33965. for (i = 0; i < pixel_size; ++i) {
  33966. pixels[i] = data[offset++];
  33967. }
  33968. // Copy pixel array
  33969. for (i = 0; i < count; ++i) {
  33970. pixel_data.set(pixels, localOffset + i * pixel_size);
  33971. }
  33972. localOffset += pixel_size * count;
  33973. }
  33974. else {
  33975. count *= pixel_size;
  33976. for (i = 0; i < count; ++i) {
  33977. pixel_data[localOffset + i] = data[offset++];
  33978. }
  33979. localOffset += count;
  33980. }
  33981. }
  33982. }
  33983. else {
  33984. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  33985. }
  33986. // Load to texture
  33987. var x_start, y_start, x_step, y_step, y_end, x_end;
  33988. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  33989. default:
  33990. case TGATools._ORIGIN_UL:
  33991. x_start = 0;
  33992. x_step = 1;
  33993. x_end = header.width;
  33994. y_start = 0;
  33995. y_step = 1;
  33996. y_end = header.height;
  33997. break;
  33998. case TGATools._ORIGIN_BL:
  33999. x_start = 0;
  34000. x_step = 1;
  34001. x_end = header.width;
  34002. y_start = header.height - 1;
  34003. y_step = -1;
  34004. y_end = -1;
  34005. break;
  34006. case TGATools._ORIGIN_UR:
  34007. x_start = header.width - 1;
  34008. x_step = -1;
  34009. x_end = -1;
  34010. y_start = 0;
  34011. y_step = 1;
  34012. y_end = header.height;
  34013. break;
  34014. case TGATools._ORIGIN_BR:
  34015. x_start = header.width - 1;
  34016. x_step = -1;
  34017. x_end = -1;
  34018. y_start = header.height - 1;
  34019. y_step = -1;
  34020. y_end = -1;
  34021. break;
  34022. }
  34023. // Load the specify method
  34024. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  34025. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  34026. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  34027. };
  34028. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34029. var image = pixel_data, colormap = palettes;
  34030. var width = header.width, height = header.height;
  34031. var color, i = 0, x, y;
  34032. var imageData = new Uint8Array(width * height * 4);
  34033. for (y = y_start; y !== y_end; y += y_step) {
  34034. for (x = x_start; x !== x_end; x += x_step, i++) {
  34035. color = image[i];
  34036. imageData[(x + width * y) * 4 + 3] = 255;
  34037. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  34038. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  34039. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  34040. }
  34041. }
  34042. return imageData;
  34043. };
  34044. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34045. var image = pixel_data;
  34046. var width = header.width, height = header.height;
  34047. var color, i = 0, x, y;
  34048. var imageData = new Uint8Array(width * height * 4);
  34049. for (y = y_start; y !== y_end; y += y_step) {
  34050. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34051. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  34052. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  34053. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  34054. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  34055. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  34056. }
  34057. }
  34058. return imageData;
  34059. };
  34060. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34061. var image = pixel_data;
  34062. var width = header.width, height = header.height;
  34063. var i = 0, x, y;
  34064. var imageData = new Uint8Array(width * height * 4);
  34065. for (y = y_start; y !== y_end; y += y_step) {
  34066. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  34067. imageData[(x + width * y) * 4 + 3] = 255;
  34068. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34069. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34070. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34071. }
  34072. }
  34073. return imageData;
  34074. };
  34075. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34076. var image = pixel_data;
  34077. var width = header.width, height = header.height;
  34078. var i = 0, x, y;
  34079. var imageData = new Uint8Array(width * height * 4);
  34080. for (y = y_start; y !== y_end; y += y_step) {
  34081. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  34082. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34083. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34084. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34085. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  34086. }
  34087. }
  34088. return imageData;
  34089. };
  34090. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34091. var image = pixel_data;
  34092. var width = header.width, height = header.height;
  34093. var color, i = 0, x, y;
  34094. var imageData = new Uint8Array(width * height * 4);
  34095. for (y = y_start; y !== y_end; y += y_step) {
  34096. for (x = x_start; x !== x_end; x += x_step, i++) {
  34097. color = image[i];
  34098. imageData[(x + width * y) * 4 + 0] = color;
  34099. imageData[(x + width * y) * 4 + 1] = color;
  34100. imageData[(x + width * y) * 4 + 2] = color;
  34101. imageData[(x + width * y) * 4 + 3] = 255;
  34102. }
  34103. }
  34104. return imageData;
  34105. };
  34106. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34107. var image = pixel_data;
  34108. var width = header.width, height = header.height;
  34109. var i = 0, x, y;
  34110. var imageData = new Uint8Array(width * height * 4);
  34111. for (y = y_start; y !== y_end; y += y_step) {
  34112. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34113. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  34114. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  34115. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34116. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  34117. }
  34118. }
  34119. return imageData;
  34120. };
  34121. TGATools._TYPE_NO_DATA = 0;
  34122. TGATools._TYPE_INDEXED = 1;
  34123. TGATools._TYPE_RGB = 2;
  34124. TGATools._TYPE_GREY = 3;
  34125. TGATools._TYPE_RLE_INDEXED = 9;
  34126. TGATools._TYPE_RLE_RGB = 10;
  34127. TGATools._TYPE_RLE_GREY = 11;
  34128. TGATools._ORIGIN_MASK = 0x30;
  34129. TGATools._ORIGIN_SHIFT = 0x04;
  34130. TGATools._ORIGIN_BL = 0x00;
  34131. TGATools._ORIGIN_BR = 0x01;
  34132. TGATools._ORIGIN_UL = 0x02;
  34133. TGATools._ORIGIN_UR = 0x03;
  34134. return TGATools;
  34135. }());
  34136. Internals.TGATools = TGATools;
  34137. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34138. })(BABYLON || (BABYLON = {}));
  34139. //# sourceMappingURL=babylon.tga.js.map
  34140. var BABYLON;
  34141. (function (BABYLON) {
  34142. var Internals;
  34143. (function (Internals) {
  34144. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34145. // All values and structures referenced from:
  34146. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34147. var DDS_MAGIC = 0x20534444;
  34148. 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;
  34149. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34150. 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;
  34151. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34152. function FourCCToInt32(value) {
  34153. return value.charCodeAt(0) +
  34154. (value.charCodeAt(1) << 8) +
  34155. (value.charCodeAt(2) << 16) +
  34156. (value.charCodeAt(3) << 24);
  34157. }
  34158. function Int32ToFourCC(value) {
  34159. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34160. }
  34161. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34162. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34163. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34164. var FOURCC_DX10 = FourCCToInt32("DX10");
  34165. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  34166. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  34167. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  34168. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  34169. var headerLengthInt = 31; // The header length in 32 bit ints
  34170. // Offsets into the header array
  34171. var off_magic = 0;
  34172. var off_size = 1;
  34173. var off_flags = 2;
  34174. var off_height = 3;
  34175. var off_width = 4;
  34176. var off_mipmapCount = 7;
  34177. var off_pfFlags = 20;
  34178. var off_pfFourCC = 21;
  34179. var off_RGBbpp = 22;
  34180. var off_RMask = 23;
  34181. var off_GMask = 24;
  34182. var off_BMask = 25;
  34183. var off_AMask = 26;
  34184. var off_caps1 = 27;
  34185. var off_caps2 = 28;
  34186. var off_caps3 = 29;
  34187. var off_caps4 = 30;
  34188. var off_dxgiFormat = 32;
  34189. ;
  34190. var DDSTools = (function () {
  34191. function DDSTools() {
  34192. }
  34193. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34194. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34195. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  34196. var mipmapCount = 1;
  34197. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34198. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34199. }
  34200. var fourCC = header[off_pfFourCC];
  34201. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  34202. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34203. switch (fourCC) {
  34204. case FOURCC_D3DFMT_R16G16B16A16F:
  34205. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34206. break;
  34207. case FOURCC_D3DFMT_R32G32B32A32F:
  34208. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34209. break;
  34210. case FOURCC_DX10:
  34211. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  34212. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34213. break;
  34214. }
  34215. }
  34216. return {
  34217. width: header[off_width],
  34218. height: header[off_height],
  34219. mipmapCount: mipmapCount,
  34220. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34221. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34222. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34223. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  34224. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  34225. dxgiFormat: dxgiFormat,
  34226. textureType: textureType
  34227. };
  34228. };
  34229. DDSTools._ToHalfFloat = function (value) {
  34230. if (!DDSTools._FloatView) {
  34231. DDSTools._FloatView = new Float32Array(1);
  34232. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  34233. }
  34234. DDSTools._FloatView[0] = value;
  34235. var x = DDSTools._Int32View[0];
  34236. var bits = (x >> 16) & 0x8000; /* Get the sign */
  34237. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  34238. var e = (x >> 23) & 0xff; /* Using int is faster here */
  34239. /* If zero, or denormal, or exponent underflows too much for a denormal
  34240. * half, return signed zero. */
  34241. if (e < 103) {
  34242. return bits;
  34243. }
  34244. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  34245. if (e > 142) {
  34246. bits |= 0x7c00;
  34247. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  34248. * not Inf, so make sure we set one mantissa bit too. */
  34249. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  34250. return bits;
  34251. }
  34252. /* If exponent underflows but not too much, return a denormal */
  34253. if (e < 113) {
  34254. m |= 0x0800;
  34255. /* Extra rounding may overflow and set mantissa to 0 and exponent
  34256. * to 1, which is OK. */
  34257. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  34258. return bits;
  34259. }
  34260. bits |= ((e - 112) << 10) | (m >> 1);
  34261. bits += m & 1;
  34262. return bits;
  34263. };
  34264. DDSTools._FromHalfFloat = function (value) {
  34265. var s = (value & 0x8000) >> 15;
  34266. var e = (value & 0x7C00) >> 10;
  34267. var f = value & 0x03FF;
  34268. if (e === 0) {
  34269. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  34270. }
  34271. else if (e == 0x1F) {
  34272. return f ? NaN : ((s ? -1 : 1) * Infinity);
  34273. }
  34274. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  34275. };
  34276. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34277. var destArray = new Float32Array(dataLength);
  34278. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34279. var index = 0;
  34280. for (var y = 0; y < height; y++) {
  34281. for (var x = 0; x < width; x++) {
  34282. var srcPos = (x + y * width) * 4;
  34283. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  34284. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  34285. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  34286. if (DDSTools.StoreLODInAlphaChannel) {
  34287. destArray[index + 3] = lod;
  34288. }
  34289. else {
  34290. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  34291. }
  34292. index += 4;
  34293. }
  34294. }
  34295. return destArray;
  34296. };
  34297. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34298. if (DDSTools.StoreLODInAlphaChannel) {
  34299. var destArray = new Uint16Array(dataLength);
  34300. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34301. var index = 0;
  34302. for (var y = 0; y < height; y++) {
  34303. for (var x = 0; x < width; x++) {
  34304. var srcPos = (x + y * width) * 4;
  34305. destArray[index] = srcData[srcPos];
  34306. destArray[index + 1] = srcData[srcPos + 1];
  34307. destArray[index + 2] = srcData[srcPos + 2];
  34308. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  34309. index += 4;
  34310. }
  34311. }
  34312. return destArray;
  34313. }
  34314. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  34315. };
  34316. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34317. if (DDSTools.StoreLODInAlphaChannel) {
  34318. var destArray = new Float32Array(dataLength);
  34319. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34320. var index = 0;
  34321. for (var y = 0; y < height; y++) {
  34322. for (var x = 0; x < width; x++) {
  34323. var srcPos = (x + y * width) * 4;
  34324. destArray[index] = srcData[srcPos];
  34325. destArray[index + 1] = srcData[srcPos + 1];
  34326. destArray[index + 2] = srcData[srcPos + 2];
  34327. destArray[index + 3] = lod;
  34328. index += 4;
  34329. }
  34330. }
  34331. return destArray;
  34332. }
  34333. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  34334. };
  34335. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34336. var destArray = new Uint8Array(dataLength);
  34337. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34338. var index = 0;
  34339. for (var y = 0; y < height; y++) {
  34340. for (var x = 0; x < width; x++) {
  34341. var srcPos = (x + y * width) * 4;
  34342. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  34343. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  34344. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  34345. if (DDSTools.StoreLODInAlphaChannel) {
  34346. destArray[index + 3] = lod;
  34347. }
  34348. else {
  34349. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  34350. }
  34351. index += 4;
  34352. }
  34353. }
  34354. return destArray;
  34355. };
  34356. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34357. var destArray = new Uint8Array(dataLength);
  34358. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34359. var index = 0;
  34360. for (var y = 0; y < height; y++) {
  34361. for (var x = 0; x < width; x++) {
  34362. var srcPos = (x + y * width) * 4;
  34363. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  34364. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  34365. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  34366. if (DDSTools.StoreLODInAlphaChannel) {
  34367. destArray[index + 3] = lod;
  34368. }
  34369. else {
  34370. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  34371. }
  34372. index += 4;
  34373. }
  34374. }
  34375. return destArray;
  34376. };
  34377. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34378. var byteArray = new Uint8Array(dataLength);
  34379. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34380. var index = 0;
  34381. for (var y = 0; y < height; y++) {
  34382. for (var x = 0; x < width; x++) {
  34383. var srcPos = (x + y * width) * 4;
  34384. byteArray[index] = srcData[srcPos + 2];
  34385. byteArray[index + 1] = srcData[srcPos + 1];
  34386. byteArray[index + 2] = srcData[srcPos];
  34387. byteArray[index + 3] = srcData[srcPos + 3];
  34388. index += 4;
  34389. }
  34390. }
  34391. return byteArray;
  34392. };
  34393. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34394. var byteArray = new Uint8Array(dataLength);
  34395. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34396. var index = 0;
  34397. for (var y = 0; y < height; y++) {
  34398. for (var x = 0; x < width; x++) {
  34399. var srcPos = (x + y * width) * 3;
  34400. byteArray[index] = srcData[srcPos + 2];
  34401. byteArray[index + 1] = srcData[srcPos + 1];
  34402. byteArray[index + 2] = srcData[srcPos];
  34403. index += 3;
  34404. }
  34405. }
  34406. return byteArray;
  34407. };
  34408. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34409. var byteArray = new Uint8Array(dataLength);
  34410. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34411. var index = 0;
  34412. for (var y = 0; y < height; y++) {
  34413. for (var x = 0; x < width; x++) {
  34414. var srcPos = (x + y * width);
  34415. byteArray[index] = srcData[srcPos];
  34416. index++;
  34417. }
  34418. }
  34419. return byteArray;
  34420. };
  34421. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  34422. if (lodIndex === void 0) { lodIndex = -1; }
  34423. var ext = engine.getCaps().s3tc;
  34424. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  34425. if (header[off_magic] != DDS_MAGIC) {
  34426. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34427. return;
  34428. }
  34429. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34430. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34431. return;
  34432. }
  34433. if (info.isCompressed && !ext) {
  34434. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  34435. return;
  34436. }
  34437. var bpp = header[off_RGBbpp];
  34438. dataOffset = header[off_size] + 4;
  34439. var computeFormats = false;
  34440. if (info.isFourCC) {
  34441. fourCC = header[off_pfFourCC];
  34442. switch (fourCC) {
  34443. case FOURCC_DXT1:
  34444. blockBytes = 8;
  34445. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34446. break;
  34447. case FOURCC_DXT3:
  34448. blockBytes = 16;
  34449. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34450. break;
  34451. case FOURCC_DXT5:
  34452. blockBytes = 16;
  34453. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34454. break;
  34455. case FOURCC_D3DFMT_R16G16B16A16F:
  34456. computeFormats = true;
  34457. break;
  34458. case FOURCC_D3DFMT_R32G32B32A32F:
  34459. computeFormats = true;
  34460. break;
  34461. case FOURCC_DX10:
  34462. // There is an additionnal header so dataOffset need to be changed
  34463. dataOffset += 5 * 4; // 5 uints
  34464. var supported = false;
  34465. switch (info.dxgiFormat) {
  34466. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  34467. computeFormats = true;
  34468. supported = true;
  34469. break;
  34470. case DXGI_FORMAT_B8G8R8X8_UNORM:
  34471. info.isRGB = true;
  34472. info.isFourCC = false;
  34473. bpp = 32;
  34474. supported = true;
  34475. break;
  34476. }
  34477. if (supported) {
  34478. break;
  34479. }
  34480. default:
  34481. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34482. return;
  34483. }
  34484. }
  34485. if (computeFormats) {
  34486. format = engine._getWebGLTextureType(info.textureType);
  34487. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34488. }
  34489. mipmapCount = 1;
  34490. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34491. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34492. }
  34493. for (var face = 0; face < faces; face++) {
  34494. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34495. width = header[off_width];
  34496. height = header[off_height];
  34497. for (mip = 0; mip < mipmapCount; ++mip) {
  34498. if (lodIndex === -1 || lodIndex === mip) {
  34499. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  34500. var i = (lodIndex === -1) ? mip : 0;
  34501. if (!info.isCompressed && info.isFourCC) {
  34502. dataLength = width * height * 4;
  34503. var floatArray;
  34504. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  34505. if (bpp === 128) {
  34506. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34507. }
  34508. else if (bpp === 64) {
  34509. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34510. }
  34511. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34512. format = engine._getWebGLTextureType(info.textureType);
  34513. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34514. }
  34515. else {
  34516. if (bpp === 128) {
  34517. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34518. }
  34519. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  34520. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34521. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34522. format = engine._getWebGLTextureType(info.textureType);
  34523. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34524. }
  34525. else {
  34526. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34527. }
  34528. }
  34529. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  34530. }
  34531. else if (info.isRGB) {
  34532. if (bpp === 24) {
  34533. dataLength = width * height * 3;
  34534. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34535. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34536. }
  34537. else {
  34538. dataLength = width * height * 4;
  34539. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34540. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34541. }
  34542. }
  34543. else if (info.isLuminance) {
  34544. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34545. var unpaddedRowSize = width;
  34546. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34547. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34548. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34549. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34550. }
  34551. else {
  34552. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34553. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34554. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  34555. }
  34556. }
  34557. dataOffset += width * height * (bpp / 8);
  34558. width *= 0.5;
  34559. height *= 0.5;
  34560. width = Math.max(1.0, width);
  34561. height = Math.max(1.0, height);
  34562. }
  34563. }
  34564. };
  34565. DDSTools.StoreLODInAlphaChannel = false;
  34566. return DDSTools;
  34567. }());
  34568. Internals.DDSTools = DDSTools;
  34569. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34570. })(BABYLON || (BABYLON = {}));
  34571. //# sourceMappingURL=babylon.dds.js.map
  34572. var BABYLON;
  34573. (function (BABYLON) {
  34574. var Internals;
  34575. (function (Internals) {
  34576. /**
  34577. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  34578. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  34579. */
  34580. var KhronosTextureContainer = (function () {
  34581. /**
  34582. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  34583. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  34584. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  34585. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  34586. */
  34587. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  34588. this.arrayBuffer = arrayBuffer;
  34589. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  34590. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  34591. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  34592. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  34593. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  34594. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  34595. BABYLON.Tools.Error("texture missing KTX identifier");
  34596. return;
  34597. }
  34598. // load the reset of the header in native 32 bit int
  34599. var header = new Int32Array(this.arrayBuffer, 12, 13);
  34600. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  34601. var oppositeEndianess = header[0] === 0x01020304;
  34602. // read all the header elements in order they exist in the file, without modification (sans endainness)
  34603. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  34604. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  34605. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  34606. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  34607. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  34608. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  34609. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  34610. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  34611. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  34612. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  34613. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  34614. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  34615. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  34616. if (this.glType !== 0) {
  34617. BABYLON.Tools.Error("only compressed formats currently supported");
  34618. return;
  34619. }
  34620. else {
  34621. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  34622. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  34623. }
  34624. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  34625. BABYLON.Tools.Error("only 2D textures currently supported");
  34626. return;
  34627. }
  34628. if (this.numberOfArrayElements !== 0) {
  34629. BABYLON.Tools.Error("texture arrays not currently supported");
  34630. return;
  34631. }
  34632. if (this.numberOfFaces !== facesExpected) {
  34633. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  34634. return;
  34635. }
  34636. // we now have a completely validated file, so could use existence of loadType as success
  34637. // would need to make this more elaborate & adjust checks above to support more than one load type
  34638. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  34639. }
  34640. // not as fast hardware based, but will probably never need to use
  34641. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  34642. return ((val & 0xFF) << 24)
  34643. | ((val & 0xFF00) << 8)
  34644. | ((val >> 8) & 0xFF00)
  34645. | ((val >> 24) & 0xFF);
  34646. };
  34647. /**
  34648. * It is assumed that the texture has already been created & is currently bound
  34649. */
  34650. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  34651. switch (this.loadType) {
  34652. case KhronosTextureContainer.COMPRESSED_2D:
  34653. this._upload2DCompressedLevels(gl, loadMipmaps);
  34654. break;
  34655. case KhronosTextureContainer.TEX_2D:
  34656. case KhronosTextureContainer.COMPRESSED_3D:
  34657. case KhronosTextureContainer.TEX_3D:
  34658. }
  34659. };
  34660. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  34661. // initialize width & height for level 1
  34662. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  34663. var width = this.pixelWidth;
  34664. var height = this.pixelHeight;
  34665. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  34666. for (var level = 0; level < mipmapCount; level++) {
  34667. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  34668. for (var face = 0; face < this.numberOfFaces; face++) {
  34669. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34670. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  34671. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  34672. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  34673. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  34674. }
  34675. width = Math.max(1.0, width * 0.5);
  34676. height = Math.max(1.0, height * 0.5);
  34677. }
  34678. };
  34679. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  34680. // load types
  34681. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  34682. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  34683. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  34684. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  34685. return KhronosTextureContainer;
  34686. }());
  34687. Internals.KhronosTextureContainer = KhronosTextureContainer;
  34688. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34689. })(BABYLON || (BABYLON = {}));
  34690. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  34691. var BABYLON;
  34692. (function (BABYLON) {
  34693. var PostProcess = (function () {
  34694. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  34695. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  34696. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34697. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  34698. if (blockCompilation === void 0) { blockCompilation = false; }
  34699. this.name = name;
  34700. this.width = -1;
  34701. this.height = -1;
  34702. this.autoClear = true;
  34703. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  34704. /*
  34705. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  34706. Can only be used on a single postprocess or on the last one of a chain.
  34707. */
  34708. this.enablePixelPerfectMode = false;
  34709. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  34710. this.alwaysForcePOT = false;
  34711. this.samples = 1;
  34712. this._reusable = false;
  34713. this._textures = new BABYLON.SmartArray(2);
  34714. this._currentRenderTextureInd = 0;
  34715. this._scaleRatio = new BABYLON.Vector2(1, 1);
  34716. this._texelSize = BABYLON.Vector2.Zero();
  34717. // Events
  34718. /**
  34719. * An event triggered when the postprocess is activated.
  34720. * @type {BABYLON.Observable}
  34721. */
  34722. this.onActivateObservable = new BABYLON.Observable();
  34723. /**
  34724. * An event triggered when the postprocess changes its size.
  34725. * @type {BABYLON.Observable}
  34726. */
  34727. this.onSizeChangedObservable = new BABYLON.Observable();
  34728. /**
  34729. * An event triggered when the postprocess applies its effect.
  34730. * @type {BABYLON.Observable}
  34731. */
  34732. this.onApplyObservable = new BABYLON.Observable();
  34733. /**
  34734. * An event triggered before rendering the postprocess
  34735. * @type {BABYLON.Observable}
  34736. */
  34737. this.onBeforeRenderObservable = new BABYLON.Observable();
  34738. /**
  34739. * An event triggered after rendering the postprocess
  34740. * @type {BABYLON.Observable}
  34741. */
  34742. this.onAfterRenderObservable = new BABYLON.Observable();
  34743. if (camera != null) {
  34744. this._camera = camera;
  34745. this._scene = camera.getScene();
  34746. camera.attachPostProcess(this);
  34747. this._engine = this._scene.getEngine();
  34748. }
  34749. else {
  34750. this._engine = engine;
  34751. }
  34752. this._options = options;
  34753. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  34754. this._reusable = reusable || false;
  34755. this._textureType = textureType;
  34756. this._samplers = samplers || [];
  34757. this._samplers.push("textureSampler");
  34758. this._fragmentUrl = fragmentUrl;
  34759. this._vertexUrl = vertexUrl;
  34760. this._parameters = parameters || [];
  34761. this._parameters.push("scale");
  34762. this._indexParameters = indexParameters;
  34763. if (!blockCompilation) {
  34764. this.updateEffect(defines);
  34765. }
  34766. }
  34767. Object.defineProperty(PostProcess.prototype, "onActivate", {
  34768. set: function (callback) {
  34769. if (this._onActivateObserver) {
  34770. this.onActivateObservable.remove(this._onActivateObserver);
  34771. }
  34772. this._onActivateObserver = this.onActivateObservable.add(callback);
  34773. },
  34774. enumerable: true,
  34775. configurable: true
  34776. });
  34777. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  34778. set: function (callback) {
  34779. if (this._onSizeChangedObserver) {
  34780. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  34781. }
  34782. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  34783. },
  34784. enumerable: true,
  34785. configurable: true
  34786. });
  34787. Object.defineProperty(PostProcess.prototype, "onApply", {
  34788. set: function (callback) {
  34789. if (this._onApplyObserver) {
  34790. this.onApplyObservable.remove(this._onApplyObserver);
  34791. }
  34792. this._onApplyObserver = this.onApplyObservable.add(callback);
  34793. },
  34794. enumerable: true,
  34795. configurable: true
  34796. });
  34797. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  34798. set: function (callback) {
  34799. if (this._onBeforeRenderObserver) {
  34800. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  34801. }
  34802. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  34803. },
  34804. enumerable: true,
  34805. configurable: true
  34806. });
  34807. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  34808. set: function (callback) {
  34809. if (this._onAfterRenderObserver) {
  34810. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  34811. }
  34812. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  34813. },
  34814. enumerable: true,
  34815. configurable: true
  34816. });
  34817. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  34818. get: function () {
  34819. return this._textures.data[this._currentRenderTextureInd];
  34820. },
  34821. set: function (value) {
  34822. this._forcedOutputTexture = value;
  34823. },
  34824. enumerable: true,
  34825. configurable: true
  34826. });
  34827. PostProcess.prototype.getCamera = function () {
  34828. return this._camera;
  34829. };
  34830. Object.defineProperty(PostProcess.prototype, "texelSize", {
  34831. get: function () {
  34832. if (this._shareOutputWithPostProcess) {
  34833. return this._shareOutputWithPostProcess.texelSize;
  34834. }
  34835. if (this._forcedOutputTexture) {
  34836. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  34837. }
  34838. return this._texelSize;
  34839. },
  34840. enumerable: true,
  34841. configurable: true
  34842. });
  34843. PostProcess.prototype.getEngine = function () {
  34844. return this._engine;
  34845. };
  34846. PostProcess.prototype.getEffect = function () {
  34847. return this._effect;
  34848. };
  34849. PostProcess.prototype.shareOutputWith = function (postProcess) {
  34850. this._disposeTextures();
  34851. this._shareOutputWithPostProcess = postProcess;
  34852. return this;
  34853. };
  34854. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  34855. 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);
  34856. };
  34857. PostProcess.prototype.isReusable = function () {
  34858. return this._reusable;
  34859. };
  34860. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  34861. PostProcess.prototype.markTextureDirty = function () {
  34862. this.width = -1;
  34863. };
  34864. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  34865. var _this = this;
  34866. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  34867. camera = camera || this._camera;
  34868. var scene = camera.getScene();
  34869. var engine = scene.getEngine();
  34870. var maxSize = engine.getCaps().maxTextureSize;
  34871. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  34872. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  34873. var desiredWidth = this._options.width || requiredWidth;
  34874. var desiredHeight = this._options.height || requiredHeight;
  34875. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  34876. if (!this._options.width) {
  34877. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  34878. }
  34879. if (!this._options.height) {
  34880. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  34881. }
  34882. }
  34883. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  34884. if (this._textures.length > 0) {
  34885. for (var i = 0; i < this._textures.length; i++) {
  34886. this._engine._releaseTexture(this._textures.data[i]);
  34887. }
  34888. this._textures.reset();
  34889. }
  34890. this.width = desiredWidth;
  34891. this.height = desiredHeight;
  34892. var textureSize = { width: this.width, height: this.height };
  34893. var textureOptions = {
  34894. generateMipMaps: false,
  34895. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  34896. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  34897. samplingMode: this.renderTargetSamplingMode,
  34898. type: this._textureType
  34899. };
  34900. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  34901. if (this._reusable) {
  34902. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  34903. }
  34904. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  34905. this.onSizeChangedObservable.notifyObservers(this);
  34906. }
  34907. this._textures.forEach(function (texture) {
  34908. if (texture.samples !== _this.samples) {
  34909. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  34910. }
  34911. });
  34912. }
  34913. var target;
  34914. if (this._shareOutputWithPostProcess) {
  34915. target = this._shareOutputWithPostProcess.outputTexture;
  34916. }
  34917. else if (this._forcedOutputTexture) {
  34918. target = this._forcedOutputTexture;
  34919. this.width = this._forcedOutputTexture.width;
  34920. this.height = this._forcedOutputTexture.height;
  34921. }
  34922. else {
  34923. target = this.outputTexture;
  34924. }
  34925. if (this.enablePixelPerfectMode) {
  34926. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  34927. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  34928. }
  34929. else {
  34930. this._scaleRatio.copyFromFloats(1, 1);
  34931. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  34932. }
  34933. this.onActivateObservable.notifyObservers(camera);
  34934. // Clear
  34935. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  34936. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  34937. }
  34938. if (this._reusable) {
  34939. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  34940. }
  34941. };
  34942. Object.defineProperty(PostProcess.prototype, "isSupported", {
  34943. get: function () {
  34944. return this._effect.isSupported;
  34945. },
  34946. enumerable: true,
  34947. configurable: true
  34948. });
  34949. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  34950. get: function () {
  34951. if (this._shareOutputWithPostProcess) {
  34952. return this._shareOutputWithPostProcess.aspectRatio;
  34953. }
  34954. if (this._forcedOutputTexture) {
  34955. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  34956. }
  34957. return this.width / this.height;
  34958. },
  34959. enumerable: true,
  34960. configurable: true
  34961. });
  34962. PostProcess.prototype.apply = function () {
  34963. // Check
  34964. if (!this._effect || !this._effect.isReady())
  34965. return null;
  34966. // States
  34967. this._engine.enableEffect(this._effect);
  34968. this._engine.setState(false);
  34969. this._engine.setDepthBuffer(false);
  34970. this._engine.setDepthWrite(false);
  34971. // Alpha
  34972. this._engine.setAlphaMode(this.alphaMode);
  34973. if (this.alphaConstants) {
  34974. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  34975. }
  34976. // Texture
  34977. var source;
  34978. if (this._shareOutputWithPostProcess) {
  34979. source = this._shareOutputWithPostProcess.outputTexture;
  34980. }
  34981. else if (this._forcedOutputTexture) {
  34982. source = this._forcedOutputTexture;
  34983. }
  34984. else {
  34985. source = this.outputTexture;
  34986. }
  34987. this._effect._bindTexture("textureSampler", source);
  34988. // Parameters
  34989. this._effect.setVector2("scale", this._scaleRatio);
  34990. this.onApplyObservable.notifyObservers(this._effect);
  34991. return this._effect;
  34992. };
  34993. PostProcess.prototype._disposeTextures = function () {
  34994. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  34995. return;
  34996. }
  34997. if (this._textures.length > 0) {
  34998. for (var i = 0; i < this._textures.length; i++) {
  34999. this._engine._releaseTexture(this._textures.data[i]);
  35000. }
  35001. }
  35002. this._textures.dispose();
  35003. };
  35004. PostProcess.prototype.dispose = function (camera) {
  35005. camera = camera || this._camera;
  35006. this._disposeTextures();
  35007. if (!camera) {
  35008. return;
  35009. }
  35010. camera.detachPostProcess(this);
  35011. var index = camera._postProcesses.indexOf(this);
  35012. if (index === 0 && camera._postProcesses.length > 0) {
  35013. this._camera._postProcesses[0].markTextureDirty();
  35014. }
  35015. this.onActivateObservable.clear();
  35016. this.onAfterRenderObservable.clear();
  35017. this.onApplyObservable.clear();
  35018. this.onBeforeRenderObservable.clear();
  35019. this.onSizeChangedObservable.clear();
  35020. };
  35021. return PostProcess;
  35022. }());
  35023. BABYLON.PostProcess = PostProcess;
  35024. })(BABYLON || (BABYLON = {}));
  35025. //# sourceMappingURL=babylon.postProcess.js.map
  35026. var BABYLON;
  35027. (function (BABYLON) {
  35028. var PassPostProcess = (function (_super) {
  35029. __extends(PassPostProcess, _super);
  35030. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  35031. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35032. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  35033. }
  35034. return PassPostProcess;
  35035. }(BABYLON.PostProcess));
  35036. BABYLON.PassPostProcess = PassPostProcess;
  35037. })(BABYLON || (BABYLON = {}));
  35038. //# sourceMappingURL=babylon.passPostProcess.js.map
  35039. var BABYLON;
  35040. (function (BABYLON) {
  35041. var ShadowGenerator = (function () {
  35042. /**
  35043. * Creates a ShadowGenerator object.
  35044. * A ShadowGenerator is the required tool to use the shadows.
  35045. * Each light casting shadows needs to use its own ShadowGenerator.
  35046. * Required parameters :
  35047. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  35048. * - `light`: the light object generating the shadows.
  35049. * - `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.
  35050. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  35051. */
  35052. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  35053. // Members
  35054. this._bias = 0.00005;
  35055. this._blurBoxOffset = 1;
  35056. this._blurScale = 2;
  35057. this._blurKernel = 1;
  35058. this._useKernelBlur = false;
  35059. this._filter = ShadowGenerator.FILTER_NONE;
  35060. this._darkness = 0;
  35061. this._transparencyShadow = false;
  35062. /**
  35063. * Controls the extent to which the shadows fade out at the edge of the frustum
  35064. * Used only by directionals and spots
  35065. */
  35066. this.frustumEdgeFalloff = 0;
  35067. this.forceBackFacesOnly = false;
  35068. this._lightDirection = BABYLON.Vector3.Zero();
  35069. this._viewMatrix = BABYLON.Matrix.Zero();
  35070. this._projectionMatrix = BABYLON.Matrix.Zero();
  35071. this._transformMatrix = BABYLON.Matrix.Zero();
  35072. this._worldViewProjection = BABYLON.Matrix.Zero();
  35073. this._currentFaceIndex = 0;
  35074. this._currentFaceIndexCache = 0;
  35075. this._isCube = false;
  35076. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  35077. this._mapSize = mapSize;
  35078. this._light = light;
  35079. this._scene = light.getScene();
  35080. light._shadowGenerator = this;
  35081. // Texture type fallback from float to int if not supported.
  35082. var caps = this._scene.getEngine().getCaps();
  35083. if (!useFullFloatFirst) {
  35084. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35085. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35086. }
  35087. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35088. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35089. }
  35090. else {
  35091. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35092. }
  35093. }
  35094. else {
  35095. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35096. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35097. }
  35098. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35099. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35100. }
  35101. else {
  35102. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35103. }
  35104. }
  35105. this._initializeGenerator();
  35106. }
  35107. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  35108. // Static
  35109. get: function () {
  35110. return ShadowGenerator._FILTER_NONE;
  35111. },
  35112. enumerable: true,
  35113. configurable: true
  35114. });
  35115. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  35116. get: function () {
  35117. return ShadowGenerator._FILTER_POISSONSAMPLING;
  35118. },
  35119. enumerable: true,
  35120. configurable: true
  35121. });
  35122. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  35123. get: function () {
  35124. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  35125. },
  35126. enumerable: true,
  35127. configurable: true
  35128. });
  35129. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  35130. get: function () {
  35131. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  35132. },
  35133. enumerable: true,
  35134. configurable: true
  35135. });
  35136. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  35137. get: function () {
  35138. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35139. },
  35140. enumerable: true,
  35141. configurable: true
  35142. });
  35143. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  35144. get: function () {
  35145. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35146. },
  35147. enumerable: true,
  35148. configurable: true
  35149. });
  35150. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  35151. get: function () {
  35152. return this._bias;
  35153. },
  35154. set: function (bias) {
  35155. this._bias = bias;
  35156. },
  35157. enumerable: true,
  35158. configurable: true
  35159. });
  35160. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  35161. get: function () {
  35162. return this._blurBoxOffset;
  35163. },
  35164. set: function (value) {
  35165. if (this._blurBoxOffset === value) {
  35166. return;
  35167. }
  35168. this._blurBoxOffset = value;
  35169. this._disposeBlurPostProcesses();
  35170. },
  35171. enumerable: true,
  35172. configurable: true
  35173. });
  35174. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  35175. get: function () {
  35176. return this._blurScale;
  35177. },
  35178. set: function (value) {
  35179. if (this._blurScale === value) {
  35180. return;
  35181. }
  35182. this._blurScale = value;
  35183. this._disposeBlurPostProcesses();
  35184. },
  35185. enumerable: true,
  35186. configurable: true
  35187. });
  35188. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  35189. get: function () {
  35190. return this._blurKernel;
  35191. },
  35192. set: function (value) {
  35193. if (this._blurKernel === value) {
  35194. return;
  35195. }
  35196. this._blurKernel = value;
  35197. this._disposeBlurPostProcesses();
  35198. },
  35199. enumerable: true,
  35200. configurable: true
  35201. });
  35202. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  35203. get: function () {
  35204. return this._useKernelBlur;
  35205. },
  35206. set: function (value) {
  35207. if (this._useKernelBlur === value) {
  35208. return;
  35209. }
  35210. this._useKernelBlur = value;
  35211. this._disposeBlurPostProcesses();
  35212. },
  35213. enumerable: true,
  35214. configurable: true
  35215. });
  35216. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  35217. get: function () {
  35218. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  35219. },
  35220. set: function (value) {
  35221. this._depthScale = value;
  35222. },
  35223. enumerable: true,
  35224. configurable: true
  35225. });
  35226. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  35227. get: function () {
  35228. return this._filter;
  35229. },
  35230. set: function (value) {
  35231. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  35232. if (this._light.needCube()) {
  35233. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35234. this.useExponentialShadowMap = true;
  35235. return;
  35236. }
  35237. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35238. this.useCloseExponentialShadowMap = true;
  35239. return;
  35240. }
  35241. }
  35242. if (this._filter === value) {
  35243. return;
  35244. }
  35245. this._filter = value;
  35246. this._disposeBlurPostProcesses();
  35247. this._applyFilterValues();
  35248. this._light._markMeshesAsLightDirty();
  35249. },
  35250. enumerable: true,
  35251. configurable: true
  35252. });
  35253. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  35254. get: function () {
  35255. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  35256. },
  35257. set: function (value) {
  35258. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  35259. },
  35260. enumerable: true,
  35261. configurable: true
  35262. });
  35263. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  35264. get: function () {
  35265. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35266. return this.useExponentialShadowMap;
  35267. },
  35268. set: function (value) {
  35269. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35270. this.useExponentialShadowMap = value;
  35271. },
  35272. enumerable: true,
  35273. configurable: true
  35274. });
  35275. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  35276. get: function () {
  35277. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35278. return this.useBlurExponentialShadowMap;
  35279. },
  35280. set: function (value) {
  35281. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35282. this.useBlurExponentialShadowMap = value;
  35283. },
  35284. enumerable: true,
  35285. configurable: true
  35286. });
  35287. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  35288. get: function () {
  35289. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  35290. },
  35291. set: function (value) {
  35292. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35293. },
  35294. enumerable: true,
  35295. configurable: true
  35296. });
  35297. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  35298. get: function () {
  35299. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  35300. },
  35301. set: function (value) {
  35302. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35303. },
  35304. enumerable: true,
  35305. configurable: true
  35306. });
  35307. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  35308. get: function () {
  35309. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35310. },
  35311. set: function (value) {
  35312. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35313. },
  35314. enumerable: true,
  35315. configurable: true
  35316. });
  35317. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  35318. get: function () {
  35319. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35320. },
  35321. set: function (value) {
  35322. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35323. },
  35324. enumerable: true,
  35325. configurable: true
  35326. });
  35327. /**
  35328. * Returns the darkness value (float).
  35329. */
  35330. ShadowGenerator.prototype.getDarkness = function () {
  35331. return this._darkness;
  35332. };
  35333. /**
  35334. * Sets the ShadowGenerator darkness value (float <= 1.0).
  35335. * Returns the ShadowGenerator.
  35336. */
  35337. ShadowGenerator.prototype.setDarkness = function (darkness) {
  35338. if (darkness >= 1.0)
  35339. this._darkness = 1.0;
  35340. else if (darkness <= 0.0)
  35341. this._darkness = 0.0;
  35342. else
  35343. this._darkness = darkness;
  35344. return this;
  35345. };
  35346. /**
  35347. * Sets the ability to have transparent shadow (boolean).
  35348. * Returns the ShadowGenerator.
  35349. */
  35350. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  35351. this._transparencyShadow = hasShadow;
  35352. return this;
  35353. };
  35354. /**
  35355. * Returns a RenderTargetTexture object : the shadow map texture.
  35356. */
  35357. ShadowGenerator.prototype.getShadowMap = function () {
  35358. return this._shadowMap;
  35359. };
  35360. /**
  35361. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  35362. */
  35363. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  35364. if (this._shadowMap2) {
  35365. return this._shadowMap2;
  35366. }
  35367. return this._shadowMap;
  35368. };
  35369. /**
  35370. * Returns the associated light object.
  35371. */
  35372. ShadowGenerator.prototype.getLight = function () {
  35373. return this._light;
  35374. };
  35375. ShadowGenerator.prototype._initializeGenerator = function () {
  35376. this._light._markMeshesAsLightDirty();
  35377. this._initializeShadowMap();
  35378. };
  35379. ShadowGenerator.prototype._initializeShadowMap = function () {
  35380. var _this = this;
  35381. // Render target
  35382. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  35383. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35384. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35385. this._shadowMap.anisotropicFilteringLevel = 1;
  35386. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35387. this._shadowMap.renderParticles = false;
  35388. // Record Face Index before render.
  35389. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  35390. _this._currentFaceIndex = faceIndex;
  35391. });
  35392. // Custom render function.
  35393. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  35394. // Blur if required afer render.
  35395. this._shadowMap.onAfterUnbindObservable.add(function () {
  35396. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  35397. return;
  35398. }
  35399. if (!_this._blurPostProcesses) {
  35400. _this._initializeBlurRTTAndPostProcesses();
  35401. }
  35402. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  35403. });
  35404. // Clear according to the chosen filter.
  35405. this._shadowMap.onClearObservable.add(function (engine) {
  35406. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  35407. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  35408. }
  35409. else {
  35410. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  35411. }
  35412. });
  35413. };
  35414. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  35415. var _this = this;
  35416. var engine = this._scene.getEngine();
  35417. var targetSize = this._mapSize / this.blurScale;
  35418. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  35419. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  35420. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35421. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35422. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35423. }
  35424. if (this.useKernelBlur) {
  35425. 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);
  35426. this._kernelBlurXPostprocess.width = targetSize;
  35427. this._kernelBlurXPostprocess.height = targetSize;
  35428. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  35429. effect.setTexture("textureSampler", _this._shadowMap);
  35430. });
  35431. 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);
  35432. this._kernelBlurXPostprocess.autoClear = false;
  35433. this._kernelBlurYPostprocess.autoClear = false;
  35434. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35435. this._kernelBlurXPostprocess.packedFloat = true;
  35436. this._kernelBlurYPostprocess.packedFloat = true;
  35437. }
  35438. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  35439. }
  35440. else {
  35441. 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);
  35442. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  35443. effect.setFloat2("screenSize", targetSize, targetSize);
  35444. effect.setTexture("textureSampler", _this._shadowMap);
  35445. });
  35446. this._boxBlurPostprocess.autoClear = false;
  35447. this._blurPostProcesses = [this._boxBlurPostprocess];
  35448. }
  35449. };
  35450. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35451. var index;
  35452. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35453. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  35454. }
  35455. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35456. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  35457. }
  35458. if (this._transparencyShadow) {
  35459. for (index = 0; index < transparentSubMeshes.length; index++) {
  35460. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  35461. }
  35462. }
  35463. };
  35464. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  35465. var _this = this;
  35466. var mesh = subMesh.getRenderingMesh();
  35467. var scene = this._scene;
  35468. var engine = scene.getEngine();
  35469. // Culling
  35470. engine.setState(subMesh.getMaterial().backFaceCulling);
  35471. // Managing instances
  35472. var batch = mesh._getInstancesRenderList(subMesh._id);
  35473. if (batch.mustReturn) {
  35474. return;
  35475. }
  35476. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  35477. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  35478. engine.enableEffect(this._effect);
  35479. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  35480. var material = subMesh.getMaterial();
  35481. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  35482. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  35483. this._effect.setVector3("lightPosition", this.getLight().position);
  35484. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  35485. // Alpha test
  35486. if (material && material.needAlphaTesting()) {
  35487. var alphaTexture = material.getAlphaTestTexture();
  35488. if (alphaTexture) {
  35489. this._effect.setTexture("diffuseSampler", alphaTexture);
  35490. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  35491. }
  35492. }
  35493. // Bones
  35494. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35495. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35496. }
  35497. if (this.forceBackFacesOnly) {
  35498. engine.setState(true, 0, false, true);
  35499. }
  35500. // Draw
  35501. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35502. if (this.forceBackFacesOnly) {
  35503. engine.setState(true, 0, false, false);
  35504. }
  35505. }
  35506. else {
  35507. // Need to reset refresh rate of the shadowMap
  35508. this._shadowMap.resetRefreshCounter();
  35509. }
  35510. };
  35511. ShadowGenerator.prototype._applyFilterValues = function () {
  35512. if (this.filter === ShadowGenerator.FILTER_NONE) {
  35513. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  35514. }
  35515. else {
  35516. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35517. }
  35518. };
  35519. /**
  35520. * Force shader compilation including textures ready check
  35521. */
  35522. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  35523. var _this = this;
  35524. var scene = this._scene;
  35525. var engine = scene.getEngine();
  35526. var subMeshes = new Array();
  35527. var currentIndex = 0;
  35528. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  35529. var mesh = _a[_i];
  35530. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  35531. }
  35532. var checkReady = function () {
  35533. if (!_this._scene || !_this._scene.getEngine()) {
  35534. return;
  35535. }
  35536. var subMesh = subMeshes[currentIndex];
  35537. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  35538. currentIndex++;
  35539. if (currentIndex >= subMeshes.length) {
  35540. if (onCompiled) {
  35541. onCompiled(_this);
  35542. }
  35543. return;
  35544. }
  35545. }
  35546. setTimeout(checkReady, 16);
  35547. };
  35548. if (subMeshes.length > 0) {
  35549. checkReady();
  35550. }
  35551. };
  35552. /**
  35553. * Boolean : true when the ShadowGenerator is finally computed.
  35554. */
  35555. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  35556. var defines = [];
  35557. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35558. defines.push("#define FLOAT");
  35559. }
  35560. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35561. defines.push("#define ESM");
  35562. }
  35563. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35564. var mesh = subMesh.getMesh();
  35565. var material = subMesh.getMaterial();
  35566. // Alpha test
  35567. if (material && material.needAlphaTesting()) {
  35568. var alphaTexture = material.getAlphaTestTexture();
  35569. if (alphaTexture) {
  35570. defines.push("#define ALPHATEST");
  35571. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35572. attribs.push(BABYLON.VertexBuffer.UVKind);
  35573. defines.push("#define UV1");
  35574. }
  35575. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35576. if (alphaTexture.coordinatesIndex === 1) {
  35577. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35578. defines.push("#define UV2");
  35579. }
  35580. }
  35581. }
  35582. }
  35583. // Bones
  35584. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35585. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35586. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35587. if (mesh.numBoneInfluencers > 4) {
  35588. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35589. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35590. }
  35591. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35592. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35593. }
  35594. else {
  35595. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35596. }
  35597. // Instances
  35598. if (useInstances) {
  35599. defines.push("#define INSTANCES");
  35600. attribs.push("world0");
  35601. attribs.push("world1");
  35602. attribs.push("world2");
  35603. attribs.push("world3");
  35604. }
  35605. // Get correct effect
  35606. var join = defines.join("\n");
  35607. if (this._cachedDefines !== join) {
  35608. this._cachedDefines = join;
  35609. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  35610. }
  35611. return this._effect.isReady();
  35612. };
  35613. /**
  35614. * This creates the defines related to the standard BJS materials.
  35615. */
  35616. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  35617. var scene = this._scene;
  35618. var light = this._light;
  35619. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  35620. return;
  35621. }
  35622. defines["SHADOW" + lightIndex] = true;
  35623. if (this.usePoissonSampling) {
  35624. defines["SHADOWPCF" + lightIndex] = true;
  35625. }
  35626. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35627. defines["SHADOWESM" + lightIndex] = true;
  35628. }
  35629. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  35630. defines["SHADOWCLOSEESM" + lightIndex] = true;
  35631. }
  35632. if (light.needCube()) {
  35633. defines["SHADOWCUBE" + lightIndex] = true;
  35634. }
  35635. };
  35636. /**
  35637. * This binds shadow lights related to the standard BJS materials.
  35638. * It implies the unifroms available on the materials are the standard BJS ones.
  35639. */
  35640. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  35641. var light = this._light;
  35642. var scene = this._scene;
  35643. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  35644. return;
  35645. }
  35646. if (!light.needCube()) {
  35647. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  35648. }
  35649. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  35650. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  35651. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  35652. };
  35653. // Methods
  35654. /**
  35655. * Returns a Matrix object : the updated transformation matrix.
  35656. */
  35657. ShadowGenerator.prototype.getTransformMatrix = function () {
  35658. var scene = this._scene;
  35659. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  35660. return this._transformMatrix;
  35661. }
  35662. this._currentRenderID = scene.getRenderId();
  35663. this._currentFaceIndexCache = this._currentFaceIndex;
  35664. var lightPosition = this._light.position;
  35665. if (this._light.computeTransformedInformation()) {
  35666. lightPosition = this._light.transformedPosition;
  35667. }
  35668. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  35669. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  35670. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  35671. }
  35672. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  35673. this._cachedPosition = lightPosition.clone();
  35674. this._cachedDirection = this._lightDirection.clone();
  35675. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  35676. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  35677. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  35678. }
  35679. return this._transformMatrix;
  35680. };
  35681. ShadowGenerator.prototype.recreateShadowMap = function () {
  35682. // Track render list.
  35683. var renderList = this._shadowMap.renderList;
  35684. // Clean up existing data.
  35685. this._disposeRTTandPostProcesses();
  35686. // Reinitializes.
  35687. this._initializeGenerator();
  35688. // Reaffect the filter to ensure a correct fallback if necessary.
  35689. this.filter = this.filter;
  35690. // Reaffect the filter.
  35691. this._applyFilterValues();
  35692. // Reaffect Render List.
  35693. this._shadowMap.renderList = renderList;
  35694. };
  35695. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  35696. if (this._shadowMap2) {
  35697. this._shadowMap2.dispose();
  35698. this._shadowMap2 = null;
  35699. }
  35700. if (this._downSamplePostprocess) {
  35701. this._downSamplePostprocess.dispose();
  35702. this._downSamplePostprocess = null;
  35703. }
  35704. if (this._boxBlurPostprocess) {
  35705. this._boxBlurPostprocess.dispose();
  35706. this._boxBlurPostprocess = null;
  35707. }
  35708. if (this._kernelBlurXPostprocess) {
  35709. this._kernelBlurXPostprocess.dispose();
  35710. this._kernelBlurXPostprocess = null;
  35711. }
  35712. if (this._kernelBlurYPostprocess) {
  35713. this._kernelBlurYPostprocess.dispose();
  35714. this._kernelBlurYPostprocess = null;
  35715. }
  35716. this._blurPostProcesses = null;
  35717. };
  35718. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  35719. if (this._shadowMap) {
  35720. this._shadowMap.dispose();
  35721. this._shadowMap = null;
  35722. }
  35723. this._disposeBlurPostProcesses();
  35724. };
  35725. /**
  35726. * Disposes the ShadowGenerator.
  35727. * Returns nothing.
  35728. */
  35729. ShadowGenerator.prototype.dispose = function () {
  35730. this._disposeRTTandPostProcesses();
  35731. this._light._shadowGenerator = null;
  35732. this._light._markMeshesAsLightDirty();
  35733. };
  35734. /**
  35735. * Serializes the ShadowGenerator and returns a serializationObject.
  35736. */
  35737. ShadowGenerator.prototype.serialize = function () {
  35738. var serializationObject = {};
  35739. var shadowMap = this.getShadowMap();
  35740. serializationObject.lightId = this._light.id;
  35741. serializationObject.mapSize = shadowMap.getRenderSize();
  35742. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  35743. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  35744. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  35745. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  35746. serializationObject.usePoissonSampling = this.usePoissonSampling;
  35747. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  35748. serializationObject.depthScale = this.depthScale;
  35749. serializationObject.darkness = this.getDarkness();
  35750. serializationObject.blurBoxOffset = this.blurBoxOffset;
  35751. serializationObject.blurKernel = this.blurKernel;
  35752. serializationObject.blurScale = this.blurScale;
  35753. serializationObject.useKernelBlur = this.useKernelBlur;
  35754. serializationObject.transparencyShadow = this._transparencyShadow;
  35755. serializationObject.renderList = [];
  35756. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  35757. var mesh = shadowMap.renderList[meshIndex];
  35758. serializationObject.renderList.push(mesh.id);
  35759. }
  35760. return serializationObject;
  35761. };
  35762. /**
  35763. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  35764. */
  35765. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  35766. //casting to point light, as light is missing the position attr and typescript complains.
  35767. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  35768. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  35769. var shadowMap = shadowGenerator.getShadowMap();
  35770. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  35771. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  35772. meshes.forEach(function (mesh) {
  35773. shadowMap.renderList.push(mesh);
  35774. });
  35775. }
  35776. if (parsedShadowGenerator.usePoissonSampling) {
  35777. shadowGenerator.usePoissonSampling = true;
  35778. }
  35779. else if (parsedShadowGenerator.useExponentialShadowMap) {
  35780. shadowGenerator.useExponentialShadowMap = true;
  35781. }
  35782. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  35783. shadowGenerator.useBlurExponentialShadowMap = true;
  35784. }
  35785. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  35786. shadowGenerator.useCloseExponentialShadowMap = true;
  35787. }
  35788. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  35789. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  35790. }
  35791. else if (parsedShadowGenerator.useVarianceShadowMap) {
  35792. shadowGenerator.useExponentialShadowMap = true;
  35793. }
  35794. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  35795. shadowGenerator.useBlurExponentialShadowMap = true;
  35796. }
  35797. if (parsedShadowGenerator.depthScale) {
  35798. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  35799. }
  35800. if (parsedShadowGenerator.blurScale) {
  35801. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  35802. }
  35803. if (parsedShadowGenerator.blurBoxOffset) {
  35804. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  35805. }
  35806. if (parsedShadowGenerator.useKernelBlur) {
  35807. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  35808. }
  35809. if (parsedShadowGenerator.blurKernel) {
  35810. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  35811. }
  35812. if (parsedShadowGenerator.bias !== undefined) {
  35813. shadowGenerator.bias = parsedShadowGenerator.bias;
  35814. }
  35815. if (parsedShadowGenerator.darkness) {
  35816. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  35817. }
  35818. if (parsedShadowGenerator.transparencyShadow) {
  35819. shadowGenerator.setTransparencyShadow(true);
  35820. }
  35821. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  35822. return shadowGenerator;
  35823. };
  35824. ShadowGenerator._FILTER_NONE = 0;
  35825. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  35826. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  35827. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  35828. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  35829. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  35830. return ShadowGenerator;
  35831. }());
  35832. BABYLON.ShadowGenerator = ShadowGenerator;
  35833. })(BABYLON || (BABYLON = {}));
  35834. //# sourceMappingURL=babylon.shadowGenerator.js.map
  35835. var BABYLON;
  35836. (function (BABYLON) {
  35837. var ShadowLight = (function (_super) {
  35838. __extends(ShadowLight, _super);
  35839. function ShadowLight() {
  35840. var _this = _super !== null && _super.apply(this, arguments) || this;
  35841. _this._needProjectionMatrixCompute = true;
  35842. return _this;
  35843. }
  35844. Object.defineProperty(ShadowLight.prototype, "direction", {
  35845. get: function () {
  35846. return this._direction;
  35847. },
  35848. set: function (value) {
  35849. this._direction = value;
  35850. },
  35851. enumerable: true,
  35852. configurable: true
  35853. });
  35854. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  35855. get: function () {
  35856. return this._shadowMinZ;
  35857. },
  35858. set: function (value) {
  35859. this._shadowMinZ = value;
  35860. this.forceProjectionMatrixCompute();
  35861. },
  35862. enumerable: true,
  35863. configurable: true
  35864. });
  35865. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  35866. get: function () {
  35867. return this._shadowMaxZ;
  35868. },
  35869. set: function (value) {
  35870. this._shadowMaxZ = value;
  35871. this.forceProjectionMatrixCompute();
  35872. },
  35873. enumerable: true,
  35874. configurable: true
  35875. });
  35876. /**
  35877. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  35878. */
  35879. ShadowLight.prototype.computeTransformedInformation = function () {
  35880. if (this.parent && this.parent.getWorldMatrix) {
  35881. if (!this.transformedPosition) {
  35882. this.transformedPosition = BABYLON.Vector3.Zero();
  35883. }
  35884. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  35885. // In case the direction is present.
  35886. if (this.direction) {
  35887. if (!this.transformedDirection) {
  35888. this.transformedDirection = BABYLON.Vector3.Zero();
  35889. }
  35890. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  35891. }
  35892. return true;
  35893. }
  35894. return false;
  35895. };
  35896. /**
  35897. * Return the depth scale used for the shadow map.
  35898. */
  35899. ShadowLight.prototype.getDepthScale = function () {
  35900. return 50.0;
  35901. };
  35902. /**
  35903. * Returns the light direction (Vector3) for any passed face index.
  35904. */
  35905. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  35906. return this.transformedDirection ? this.transformedDirection : this.direction;
  35907. };
  35908. /**
  35909. * Returns the DirectionalLight absolute position in the World.
  35910. */
  35911. ShadowLight.prototype.getAbsolutePosition = function () {
  35912. return this.transformedPosition ? this.transformedPosition : this.position;
  35913. };
  35914. /**
  35915. * Sets the DirectionalLight direction toward the passed target (Vector3).
  35916. * Returns the updated DirectionalLight direction (Vector3).
  35917. */
  35918. ShadowLight.prototype.setDirectionToTarget = function (target) {
  35919. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  35920. return this.direction;
  35921. };
  35922. /**
  35923. * Returns the light rotation (Vector3).
  35924. */
  35925. ShadowLight.prototype.getRotation = function () {
  35926. this.direction.normalize();
  35927. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  35928. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  35929. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  35930. };
  35931. /**
  35932. * Boolean : false by default.
  35933. */
  35934. ShadowLight.prototype.needCube = function () {
  35935. return false;
  35936. };
  35937. /**
  35938. * Specifies wether or not the projection matrix should be recomputed this frame.
  35939. */
  35940. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  35941. return this._needProjectionMatrixCompute;
  35942. };
  35943. /**
  35944. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  35945. */
  35946. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  35947. this._needProjectionMatrixCompute = true;
  35948. };
  35949. /**
  35950. * Get the world matrix of the sahdow lights.
  35951. */
  35952. ShadowLight.prototype._getWorldMatrix = function () {
  35953. if (!this._worldMatrix) {
  35954. this._worldMatrix = BABYLON.Matrix.Identity();
  35955. }
  35956. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  35957. return this._worldMatrix;
  35958. };
  35959. /**
  35960. * Gets the minZ used for shadow according to both the scene and the light.
  35961. * @param activeCamera
  35962. */
  35963. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  35964. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  35965. };
  35966. /**
  35967. * Gets the maxZ used for shadow according to both the scene and the light.
  35968. * @param activeCamera
  35969. */
  35970. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  35971. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  35972. };
  35973. /**
  35974. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  35975. * Returns the light.
  35976. */
  35977. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35978. if (this.customProjectionMatrixBuilder) {
  35979. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  35980. }
  35981. else {
  35982. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  35983. }
  35984. return this;
  35985. };
  35986. __decorate([
  35987. BABYLON.serializeAsVector3()
  35988. ], ShadowLight.prototype, "position", void 0);
  35989. __decorate([
  35990. BABYLON.serializeAsVector3()
  35991. ], ShadowLight.prototype, "direction", null);
  35992. __decorate([
  35993. BABYLON.serialize()
  35994. ], ShadowLight.prototype, "shadowMinZ", null);
  35995. __decorate([
  35996. BABYLON.serialize()
  35997. ], ShadowLight.prototype, "shadowMaxZ", null);
  35998. return ShadowLight;
  35999. }(BABYLON.Light));
  36000. BABYLON.ShadowLight = ShadowLight;
  36001. })(BABYLON || (BABYLON = {}));
  36002. //# sourceMappingURL=babylon.shadowLight.js.map
  36003. var BABYLON;
  36004. (function (BABYLON) {
  36005. var PointLight = (function (_super) {
  36006. __extends(PointLight, _super);
  36007. /**
  36008. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36009. * A PointLight emits the light in every direction.
  36010. * It can cast shadows.
  36011. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36012. * ```javascript
  36013. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36014. * ```
  36015. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36016. */
  36017. function PointLight(name, position, scene) {
  36018. var _this = _super.call(this, name, scene) || this;
  36019. _this._shadowAngle = Math.PI / 2;
  36020. _this.position = position;
  36021. return _this;
  36022. }
  36023. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36024. /**
  36025. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36026. * This specifies what angle the shadow will use to be created.
  36027. *
  36028. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36029. */
  36030. get: function () {
  36031. return this._shadowAngle;
  36032. },
  36033. /**
  36034. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36035. * This specifies what angle the shadow will use to be created.
  36036. *
  36037. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36038. */
  36039. set: function (value) {
  36040. this._shadowAngle = value;
  36041. this.forceProjectionMatrixCompute();
  36042. },
  36043. enumerable: true,
  36044. configurable: true
  36045. });
  36046. Object.defineProperty(PointLight.prototype, "direction", {
  36047. get: function () {
  36048. return this._direction;
  36049. },
  36050. /**
  36051. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36052. */
  36053. set: function (value) {
  36054. var previousNeedCube = this.needCube();
  36055. this._direction = value;
  36056. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36057. this._shadowGenerator.recreateShadowMap();
  36058. }
  36059. },
  36060. enumerable: true,
  36061. configurable: true
  36062. });
  36063. /**
  36064. * Returns the string "PointLight"
  36065. */
  36066. PointLight.prototype.getClassName = function () {
  36067. return "PointLight";
  36068. };
  36069. /**
  36070. * Returns the integer 0.
  36071. */
  36072. PointLight.prototype.getTypeID = function () {
  36073. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36074. };
  36075. /**
  36076. * Specifies wether or not the shadowmap should be a cube texture.
  36077. */
  36078. PointLight.prototype.needCube = function () {
  36079. return !this.direction;
  36080. };
  36081. /**
  36082. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36083. */
  36084. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36085. if (this.direction) {
  36086. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36087. }
  36088. else {
  36089. switch (faceIndex) {
  36090. case 0:
  36091. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36092. case 1:
  36093. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36094. case 2:
  36095. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36096. case 3:
  36097. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36098. case 4:
  36099. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36100. case 5:
  36101. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36102. }
  36103. }
  36104. return BABYLON.Vector3.Zero();
  36105. };
  36106. /**
  36107. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36108. * - fov = PI / 2
  36109. * - aspect ratio : 1.0
  36110. * - z-near and far equal to the active camera minZ and maxZ.
  36111. * Returns the PointLight.
  36112. */
  36113. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36114. var activeCamera = this.getScene().activeCamera;
  36115. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36116. };
  36117. PointLight.prototype._buildUniformLayout = function () {
  36118. this._uniformBuffer.addUniform("vLightData", 4);
  36119. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36120. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36121. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36122. this._uniformBuffer.addUniform("depthValues", 2);
  36123. this._uniformBuffer.create();
  36124. };
  36125. /**
  36126. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36127. * Returns the PointLight.
  36128. */
  36129. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36130. if (this.computeTransformedInformation()) {
  36131. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36132. return this;
  36133. }
  36134. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36135. return this;
  36136. };
  36137. __decorate([
  36138. BABYLON.serialize()
  36139. ], PointLight.prototype, "shadowAngle", null);
  36140. return PointLight;
  36141. }(BABYLON.ShadowLight));
  36142. BABYLON.PointLight = PointLight;
  36143. })(BABYLON || (BABYLON = {}));
  36144. //# sourceMappingURL=babylon.pointLight.js.map
  36145. /// <reference path="babylon.light.ts" />
  36146. var BABYLON;
  36147. (function (BABYLON) {
  36148. var DirectionalLight = (function (_super) {
  36149. __extends(DirectionalLight, _super);
  36150. /**
  36151. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36152. * The directional light is emitted from everywhere in the given direction.
  36153. * It can cast shawdows.
  36154. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36155. */
  36156. function DirectionalLight(name, direction, scene) {
  36157. var _this = _super.call(this, name, scene) || this;
  36158. _this._shadowFrustumSize = 0;
  36159. _this._shadowOrthoScale = 0.5;
  36160. _this.autoUpdateExtends = true;
  36161. // Cache
  36162. _this._orthoLeft = Number.MAX_VALUE;
  36163. _this._orthoRight = Number.MIN_VALUE;
  36164. _this._orthoTop = Number.MIN_VALUE;
  36165. _this._orthoBottom = Number.MAX_VALUE;
  36166. _this.position = direction.scale(-1.0);
  36167. _this.direction = direction;
  36168. return _this;
  36169. }
  36170. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36171. /**
  36172. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36173. */
  36174. get: function () {
  36175. return this._shadowFrustumSize;
  36176. },
  36177. /**
  36178. * Specifies a fix frustum size for the shadow generation.
  36179. */
  36180. set: function (value) {
  36181. this._shadowFrustumSize = value;
  36182. this.forceProjectionMatrixCompute();
  36183. },
  36184. enumerable: true,
  36185. configurable: true
  36186. });
  36187. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36188. get: function () {
  36189. return this._shadowOrthoScale;
  36190. },
  36191. set: function (value) {
  36192. this._shadowOrthoScale = value;
  36193. this.forceProjectionMatrixCompute();
  36194. },
  36195. enumerable: true,
  36196. configurable: true
  36197. });
  36198. /**
  36199. * Returns the string "DirectionalLight".
  36200. */
  36201. DirectionalLight.prototype.getClassName = function () {
  36202. return "DirectionalLight";
  36203. };
  36204. /**
  36205. * Returns the integer 1.
  36206. */
  36207. DirectionalLight.prototype.getTypeID = function () {
  36208. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36209. };
  36210. /**
  36211. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36212. * Returns the DirectionalLight Shadow projection matrix.
  36213. */
  36214. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36215. if (this.shadowFrustumSize > 0) {
  36216. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36217. }
  36218. else {
  36219. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36220. }
  36221. };
  36222. /**
  36223. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36224. * Returns the DirectionalLight Shadow projection matrix.
  36225. */
  36226. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36227. var activeCamera = this.getScene().activeCamera;
  36228. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36229. };
  36230. /**
  36231. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36232. * Returns the DirectionalLight Shadow projection matrix.
  36233. */
  36234. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36235. var activeCamera = this.getScene().activeCamera;
  36236. // Check extends
  36237. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36238. var tempVector3 = BABYLON.Vector3.Zero();
  36239. this._orthoLeft = Number.MAX_VALUE;
  36240. this._orthoRight = Number.MIN_VALUE;
  36241. this._orthoTop = Number.MIN_VALUE;
  36242. this._orthoBottom = Number.MAX_VALUE;
  36243. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36244. var mesh = renderList[meshIndex];
  36245. if (!mesh) {
  36246. continue;
  36247. }
  36248. var boundingInfo = mesh.getBoundingInfo();
  36249. if (!boundingInfo) {
  36250. continue;
  36251. }
  36252. var boundingBox = boundingInfo.boundingBox;
  36253. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36254. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36255. if (tempVector3.x < this._orthoLeft)
  36256. this._orthoLeft = tempVector3.x;
  36257. if (tempVector3.y < this._orthoBottom)
  36258. this._orthoBottom = tempVector3.y;
  36259. if (tempVector3.x > this._orthoRight)
  36260. this._orthoRight = tempVector3.x;
  36261. if (tempVector3.y > this._orthoTop)
  36262. this._orthoTop = tempVector3.y;
  36263. }
  36264. }
  36265. }
  36266. var xOffset = this._orthoRight - this._orthoLeft;
  36267. var yOffset = this._orthoTop - this._orthoBottom;
  36268. 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);
  36269. };
  36270. DirectionalLight.prototype._buildUniformLayout = function () {
  36271. this._uniformBuffer.addUniform("vLightData", 4);
  36272. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36273. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36274. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36275. this._uniformBuffer.addUniform("depthValues", 2);
  36276. this._uniformBuffer.create();
  36277. };
  36278. /**
  36279. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36280. * Returns the DirectionalLight.
  36281. */
  36282. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36283. if (this.computeTransformedInformation()) {
  36284. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36285. return this;
  36286. }
  36287. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36288. return this;
  36289. };
  36290. /**
  36291. * Gets the minZ used for shadow according to both the scene and the light.
  36292. *
  36293. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36294. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36295. * @param activeCamera
  36296. */
  36297. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36298. return 1;
  36299. };
  36300. /**
  36301. * Gets the maxZ used for shadow according to both the scene and the light.
  36302. *
  36303. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36304. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36305. * @param activeCamera
  36306. */
  36307. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36308. return 1;
  36309. };
  36310. __decorate([
  36311. BABYLON.serialize()
  36312. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36313. __decorate([
  36314. BABYLON.serialize()
  36315. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36316. __decorate([
  36317. BABYLON.serialize()
  36318. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36319. return DirectionalLight;
  36320. }(BABYLON.ShadowLight));
  36321. BABYLON.DirectionalLight = DirectionalLight;
  36322. })(BABYLON || (BABYLON = {}));
  36323. //# sourceMappingURL=babylon.directionalLight.js.map
  36324. var BABYLON;
  36325. (function (BABYLON) {
  36326. var SpotLight = (function (_super) {
  36327. __extends(SpotLight, _super);
  36328. /**
  36329. * Creates a SpotLight object in the scene with the passed parameters :
  36330. * - `position` (Vector3) is the initial SpotLight position,
  36331. * - `direction` (Vector3) is the initial SpotLight direction,
  36332. * - `angle` (float, in radians) is the spot light cone angle,
  36333. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36334. * A spot light is a simply light oriented cone.
  36335. * It can cast shadows.
  36336. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36337. */
  36338. function SpotLight(name, position, direction, angle, exponent, scene) {
  36339. var _this = _super.call(this, name, scene) || this;
  36340. _this.position = position;
  36341. _this.direction = direction;
  36342. _this.angle = angle;
  36343. _this.exponent = exponent;
  36344. return _this;
  36345. }
  36346. Object.defineProperty(SpotLight.prototype, "angle", {
  36347. get: function () {
  36348. return this._angle;
  36349. },
  36350. set: function (value) {
  36351. this._angle = value;
  36352. this.forceProjectionMatrixCompute();
  36353. },
  36354. enumerable: true,
  36355. configurable: true
  36356. });
  36357. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36358. get: function () {
  36359. return this._shadowAngleScale;
  36360. },
  36361. /**
  36362. * Allows scaling the angle of the light for shadow generation only.
  36363. */
  36364. set: function (value) {
  36365. this._shadowAngleScale = value;
  36366. this.forceProjectionMatrixCompute();
  36367. },
  36368. enumerable: true,
  36369. configurable: true
  36370. });
  36371. /**
  36372. * Returns the string "SpotLight".
  36373. */
  36374. SpotLight.prototype.getClassName = function () {
  36375. return "SpotLight";
  36376. };
  36377. /**
  36378. * Returns the integer 2.
  36379. */
  36380. SpotLight.prototype.getTypeID = function () {
  36381. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36382. };
  36383. /**
  36384. * 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.
  36385. * Returns the SpotLight.
  36386. */
  36387. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36388. var activeCamera = this.getScene().activeCamera;
  36389. this._shadowAngleScale = this._shadowAngleScale || 1;
  36390. var angle = this._shadowAngleScale * this._angle;
  36391. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36392. };
  36393. SpotLight.prototype._buildUniformLayout = function () {
  36394. this._uniformBuffer.addUniform("vLightData", 4);
  36395. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36396. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36397. this._uniformBuffer.addUniform("vLightDirection", 3);
  36398. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36399. this._uniformBuffer.addUniform("depthValues", 2);
  36400. this._uniformBuffer.create();
  36401. };
  36402. /**
  36403. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36404. * Return the SpotLight.
  36405. */
  36406. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36407. var normalizeDirection;
  36408. if (this.computeTransformedInformation()) {
  36409. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36410. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36411. }
  36412. else {
  36413. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36414. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36415. }
  36416. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36417. return this;
  36418. };
  36419. __decorate([
  36420. BABYLON.serialize()
  36421. ], SpotLight.prototype, "angle", null);
  36422. __decorate([
  36423. BABYLON.serialize()
  36424. /**
  36425. * Allows scaling the angle of the light for shadow generation only.
  36426. */
  36427. ], SpotLight.prototype, "shadowAngleScale", null);
  36428. __decorate([
  36429. BABYLON.serialize()
  36430. ], SpotLight.prototype, "exponent", void 0);
  36431. return SpotLight;
  36432. }(BABYLON.ShadowLight));
  36433. BABYLON.SpotLight = SpotLight;
  36434. })(BABYLON || (BABYLON = {}));
  36435. //# sourceMappingURL=babylon.spotLight.js.map
  36436. var BABYLON;
  36437. (function (BABYLON) {
  36438. var MultiMaterial = (function (_super) {
  36439. __extends(MultiMaterial, _super);
  36440. function MultiMaterial(name, scene) {
  36441. var _this = _super.call(this, name, scene, true) || this;
  36442. scene.multiMaterials.push(_this);
  36443. _this.subMaterials = new Array();
  36444. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  36445. return _this;
  36446. }
  36447. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  36448. get: function () {
  36449. return this._subMaterials;
  36450. },
  36451. set: function (value) {
  36452. this._subMaterials = value;
  36453. this._hookArray(value);
  36454. },
  36455. enumerable: true,
  36456. configurable: true
  36457. });
  36458. MultiMaterial.prototype._hookArray = function (array) {
  36459. var _this = this;
  36460. var oldPush = array.push;
  36461. array.push = function () {
  36462. var items = [];
  36463. for (var _i = 0; _i < arguments.length; _i++) {
  36464. items[_i] = arguments[_i];
  36465. }
  36466. var result = oldPush.apply(array, items);
  36467. _this._markAllSubMeshesAsTexturesDirty();
  36468. return result;
  36469. };
  36470. var oldSplice = array.splice;
  36471. array.splice = function (index, deleteCount) {
  36472. var deleted = oldSplice.apply(array, [index, deleteCount]);
  36473. _this._markAllSubMeshesAsTexturesDirty();
  36474. return deleted;
  36475. };
  36476. };
  36477. // Properties
  36478. MultiMaterial.prototype.getSubMaterial = function (index) {
  36479. if (index < 0 || index >= this.subMaterials.length) {
  36480. return this.getScene().defaultMaterial;
  36481. }
  36482. return this.subMaterials[index];
  36483. };
  36484. MultiMaterial.prototype.getActiveTextures = function () {
  36485. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  36486. var _a;
  36487. };
  36488. // Methods
  36489. MultiMaterial.prototype.getClassName = function () {
  36490. return "MultiMaterial";
  36491. };
  36492. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36493. for (var index = 0; index < this.subMaterials.length; index++) {
  36494. var subMaterial = this.subMaterials[index];
  36495. if (subMaterial) {
  36496. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  36497. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  36498. return false;
  36499. }
  36500. continue;
  36501. }
  36502. if (!this.subMaterials[index].isReady(mesh)) {
  36503. return false;
  36504. }
  36505. }
  36506. }
  36507. return true;
  36508. };
  36509. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  36510. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  36511. for (var index = 0; index < this.subMaterials.length; index++) {
  36512. var subMaterial = null;
  36513. if (cloneChildren) {
  36514. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  36515. }
  36516. else {
  36517. subMaterial = this.subMaterials[index];
  36518. }
  36519. newMultiMaterial.subMaterials.push(subMaterial);
  36520. }
  36521. return newMultiMaterial;
  36522. };
  36523. MultiMaterial.prototype.serialize = function () {
  36524. var serializationObject = {};
  36525. serializationObject.name = this.name;
  36526. serializationObject.id = this.id;
  36527. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36528. serializationObject.materials = [];
  36529. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  36530. var subMat = this.subMaterials[matIndex];
  36531. if (subMat) {
  36532. serializationObject.materials.push(subMat.id);
  36533. }
  36534. else {
  36535. serializationObject.materials.push(null);
  36536. }
  36537. }
  36538. return serializationObject;
  36539. };
  36540. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36541. var scene = this.getScene();
  36542. if (!scene) {
  36543. return;
  36544. }
  36545. var index = scene.multiMaterials.indexOf(this);
  36546. if (index >= 0) {
  36547. scene.multiMaterials.splice(index, 1);
  36548. }
  36549. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36550. };
  36551. return MultiMaterial;
  36552. }(BABYLON.Material));
  36553. BABYLON.MultiMaterial = MultiMaterial;
  36554. })(BABYLON || (BABYLON = {}));
  36555. //# sourceMappingURL=babylon.multiMaterial.js.map
  36556. var BABYLON;
  36557. (function (BABYLON) {
  36558. var PBRMaterialDefines = (function (_super) {
  36559. __extends(PBRMaterialDefines, _super);
  36560. function PBRMaterialDefines() {
  36561. var _this = _super.call(this) || this;
  36562. _this.PBR = true;
  36563. _this.MAINUV1 = false;
  36564. _this.MAINUV2 = false;
  36565. _this.UV1 = false;
  36566. _this.UV2 = false;
  36567. _this.ALBEDO = false;
  36568. _this.ALBEDODIRECTUV = 0;
  36569. _this.VERTEXCOLOR = false;
  36570. _this.AMBIENT = false;
  36571. _this.AMBIENTDIRECTUV = 0;
  36572. _this.AMBIENTINGRAYSCALE = false;
  36573. _this.OPACITY = false;
  36574. _this.VERTEXALPHA = false;
  36575. _this.OPACITYDIRECTUV = 0;
  36576. _this.OPACITYRGB = false;
  36577. _this.ALPHATEST = false;
  36578. _this.ALPHABLEND = false;
  36579. _this.ALPHAFROMALBEDO = false;
  36580. _this.ALPHATESTVALUE = 0.5;
  36581. _this.SPECULAROVERALPHA = false;
  36582. _this.RADIANCEOVERALPHA = false;
  36583. _this.ALPHAFRESNEL = false;
  36584. _this.PREMULTIPLYALPHA = false;
  36585. _this.EMISSIVE = false;
  36586. _this.EMISSIVEDIRECTUV = 0;
  36587. _this.REFLECTIVITY = false;
  36588. _this.REFLECTIVITYDIRECTUV = 0;
  36589. _this.SPECULARTERM = false;
  36590. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36591. _this.MICROSURFACEAUTOMATIC = false;
  36592. _this.LODBASEDMICROSFURACE = false;
  36593. _this.MICROSURFACEMAP = false;
  36594. _this.MICROSURFACEMAPDIRECTUV = 0;
  36595. _this.METALLICWORKFLOW = false;
  36596. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36597. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36598. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36599. _this.AOSTOREINMETALMAPRED = false;
  36600. _this.ENVIRONMENTBRDF = false;
  36601. _this.NORMAL = false;
  36602. _this.TANGENT = false;
  36603. _this.BUMP = false;
  36604. _this.BUMPDIRECTUV = 0;
  36605. _this.PARALLAX = false;
  36606. _this.PARALLAXOCCLUSION = false;
  36607. _this.NORMALXYSCALE = true;
  36608. _this.LIGHTMAP = false;
  36609. _this.LIGHTMAPDIRECTUV = 0;
  36610. _this.USELIGHTMAPASSHADOWMAP = false;
  36611. _this.REFLECTION = false;
  36612. _this.REFLECTIONMAP_3D = false;
  36613. _this.REFLECTIONMAP_SPHERICAL = false;
  36614. _this.REFLECTIONMAP_PLANAR = false;
  36615. _this.REFLECTIONMAP_CUBIC = false;
  36616. _this.REFLECTIONMAP_PROJECTION = false;
  36617. _this.REFLECTIONMAP_SKYBOX = false;
  36618. _this.REFLECTIONMAP_EXPLICIT = false;
  36619. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36620. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36621. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36622. _this.INVERTCUBICMAP = false;
  36623. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36624. _this.USESPHERICALINFRAGMENT = false;
  36625. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36626. _this.LODINREFLECTIONALPHA = false;
  36627. _this.GAMMAREFLECTION = false;
  36628. _this.REFRACTION = false;
  36629. _this.REFRACTIONMAP_3D = false;
  36630. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36631. _this.LODINREFRACTIONALPHA = false;
  36632. _this.GAMMAREFRACTION = false;
  36633. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36634. _this.INSTANCES = false;
  36635. _this.NUM_BONE_INFLUENCERS = 0;
  36636. _this.BonesPerMesh = 0;
  36637. _this.MORPHTARGETS = false;
  36638. _this.MORPHTARGETS_NORMAL = false;
  36639. _this.MORPHTARGETS_TANGENT = false;
  36640. _this.NUM_MORPH_INFLUENCERS = 0;
  36641. _this.IMAGEPROCESSING = false;
  36642. _this.VIGNETTE = false;
  36643. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36644. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36645. _this.TONEMAPPING = false;
  36646. _this.CONTRAST = false;
  36647. _this.COLORCURVES = false;
  36648. _this.COLORGRADING = false;
  36649. _this.SAMPLER3DGREENDEPTH = false;
  36650. _this.SAMPLER3DBGRMAP = false;
  36651. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36652. _this.EXPOSURE = false;
  36653. _this.USEPHYSICALLIGHTFALLOFF = false;
  36654. _this.TWOSIDEDLIGHTING = false;
  36655. _this.SHADOWFLOAT = false;
  36656. _this.USERIGHTHANDEDSYSTEM = false;
  36657. _this.CLIPPLANE = false;
  36658. _this.POINTSIZE = false;
  36659. _this.FOG = false;
  36660. _this.LOGARITHMICDEPTH = false;
  36661. _this.FORCENORMALFORWARD = false;
  36662. _this.rebuild();
  36663. return _this;
  36664. }
  36665. PBRMaterialDefines.prototype.reset = function () {
  36666. _super.prototype.reset.call(this);
  36667. this.ALPHATESTVALUE = 0.5;
  36668. this.PBR = true;
  36669. };
  36670. return PBRMaterialDefines;
  36671. }(BABYLON.MaterialDefines));
  36672. /**
  36673. * The Physically based material base class of BJS.
  36674. *
  36675. * This offers the main features of a standard PBR material.
  36676. * For more information, please refer to the documentation :
  36677. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36678. */
  36679. var PBRBaseMaterial = (function (_super) {
  36680. __extends(PBRBaseMaterial, _super);
  36681. /**
  36682. * Instantiates a new PBRMaterial instance.
  36683. *
  36684. * @param name The material name
  36685. * @param scene The scene the material will be use in.
  36686. */
  36687. function PBRBaseMaterial(name, scene) {
  36688. var _this = _super.call(this, name, scene) || this;
  36689. /**
  36690. * Intensity of the direct lights e.g. the four lights available in your scene.
  36691. * This impacts both the direct diffuse and specular highlights.
  36692. */
  36693. _this._directIntensity = 1.0;
  36694. /**
  36695. * Intensity of the emissive part of the material.
  36696. * This helps controlling the emissive effect without modifying the emissive color.
  36697. */
  36698. _this._emissiveIntensity = 1.0;
  36699. /**
  36700. * Intensity of the environment e.g. how much the environment will light the object
  36701. * either through harmonics for rough material or through the refelction for shiny ones.
  36702. */
  36703. _this._environmentIntensity = 1.0;
  36704. /**
  36705. * This is a special control allowing the reduction of the specular highlights coming from the
  36706. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36707. */
  36708. _this._specularIntensity = 1.0;
  36709. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36710. /**
  36711. * Debug Control allowing disabling the bump map on this material.
  36712. */
  36713. _this._disableBumpMap = false;
  36714. /**
  36715. * AKA Occlusion Texture Intensity in other nomenclature.
  36716. */
  36717. _this._ambientTextureStrength = 1.0;
  36718. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36719. /**
  36720. * AKA Diffuse Color in other nomenclature.
  36721. */
  36722. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36723. /**
  36724. * AKA Specular Color in other nomenclature.
  36725. */
  36726. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36727. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36728. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36729. /**
  36730. * AKA Glossiness in other nomenclature.
  36731. */
  36732. _this._microSurface = 0.9;
  36733. /**
  36734. * source material index of refraction (IOR)' / 'destination material IOR.
  36735. */
  36736. _this._indexOfRefraction = 0.66;
  36737. /**
  36738. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36739. */
  36740. _this._invertRefractionY = false;
  36741. /**
  36742. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36743. * Materials half opaque for instance using refraction could benefit from this control.
  36744. */
  36745. _this._linkRefractionWithTransparency = false;
  36746. _this._useLightmapAsShadowmap = false;
  36747. /**
  36748. * Specifies that the alpha is coming form the albedo channel alpha channel.
  36749. */
  36750. _this._useAlphaFromAlbedoTexture = false;
  36751. /**
  36752. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36753. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36754. */
  36755. _this._useSpecularOverAlpha = true;
  36756. /**
  36757. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36758. */
  36759. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36760. /**
  36761. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36762. */
  36763. _this._useRoughnessFromMetallicTextureAlpha = true;
  36764. /**
  36765. * Specifies if the metallic texture contains the roughness information in its green channel.
  36766. */
  36767. _this._useRoughnessFromMetallicTextureGreen = false;
  36768. /**
  36769. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36770. */
  36771. _this._useMetallnessFromMetallicTextureBlue = false;
  36772. /**
  36773. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36774. */
  36775. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36776. /**
  36777. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36778. */
  36779. _this._useAmbientInGrayScale = false;
  36780. /**
  36781. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36782. * The material will try to infer what glossiness each pixel should be.
  36783. */
  36784. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36785. /**
  36786. * BJS is using an harcoded light falloff based on a manually sets up range.
  36787. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36788. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36789. */
  36790. _this._usePhysicalLightFalloff = true;
  36791. /**
  36792. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36793. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36794. */
  36795. _this._useRadianceOverAlpha = true;
  36796. /**
  36797. * Allows using the bump map in parallax mode.
  36798. */
  36799. _this._useParallax = false;
  36800. /**
  36801. * Allows using the bump map in parallax occlusion mode.
  36802. */
  36803. _this._useParallaxOcclusion = false;
  36804. /**
  36805. * Controls the scale bias of the parallax mode.
  36806. */
  36807. _this._parallaxScaleBias = 0.05;
  36808. /**
  36809. * If sets to true, disables all the lights affecting the material.
  36810. */
  36811. _this._disableLighting = false;
  36812. /**
  36813. * Number of Simultaneous lights allowed on the material.
  36814. */
  36815. _this._maxSimultaneousLights = 4;
  36816. /**
  36817. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36818. */
  36819. _this._invertNormalMapX = false;
  36820. /**
  36821. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36822. */
  36823. _this._invertNormalMapY = false;
  36824. /**
  36825. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36826. */
  36827. _this._twoSidedLighting = false;
  36828. /**
  36829. * Defines the alpha limits in alpha test mode.
  36830. */
  36831. _this._alphaCutOff = 0.4;
  36832. /**
  36833. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36834. */
  36835. _this._forceAlphaTest = false;
  36836. /**
  36837. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  36838. * in your scene composition.
  36839. */
  36840. _this._preMultiplyAlpha = false;
  36841. /**
  36842. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36843. * And/Or occlude the blended part.
  36844. */
  36845. _this._useAlphaFresnel = false;
  36846. /**
  36847. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36848. * from cos thetav and roughness:
  36849. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36850. */
  36851. _this._environmentBRDFTexture = null;
  36852. /**
  36853. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36854. */
  36855. _this._forceIrradianceInFragment = false;
  36856. /**
  36857. * Force normal to face away from face.
  36858. * (Temporary internal fix to remove before 3.1)
  36859. */
  36860. _this._forceNormalForward = false;
  36861. _this._renderTargets = new BABYLON.SmartArray(16);
  36862. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36863. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36864. _this._tempColor = new BABYLON.Color3();
  36865. // Setup the default processing configuration to the scene.
  36866. _this._attachImageProcessingConfiguration(null);
  36867. _this.getRenderTargetTextures = function () {
  36868. _this._renderTargets.reset();
  36869. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36870. _this._renderTargets.push(_this._reflectionTexture);
  36871. }
  36872. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36873. _this._renderTargets.push(_this._refractionTexture);
  36874. }
  36875. return _this._renderTargets;
  36876. };
  36877. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36878. return _this;
  36879. }
  36880. /**
  36881. * Attaches a new image processing configuration to the PBR Material.
  36882. * @param configuration
  36883. */
  36884. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36885. var _this = this;
  36886. if (configuration === this._imageProcessingConfiguration) {
  36887. return;
  36888. }
  36889. // Detaches observer.
  36890. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36891. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36892. }
  36893. // Pick the scene configuration if needed.
  36894. if (!configuration) {
  36895. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36896. }
  36897. else {
  36898. this._imageProcessingConfiguration = configuration;
  36899. }
  36900. // Attaches observer.
  36901. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36902. _this._markAllSubMeshesAsImageProcessingDirty();
  36903. });
  36904. };
  36905. PBRBaseMaterial.prototype.getClassName = function () {
  36906. return "PBRBaseMaterial";
  36907. };
  36908. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36909. get: function () {
  36910. return this._useLogarithmicDepth;
  36911. },
  36912. set: function (value) {
  36913. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36914. },
  36915. enumerable: true,
  36916. configurable: true
  36917. });
  36918. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36919. if (this._linkRefractionWithTransparency) {
  36920. return false;
  36921. }
  36922. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36923. };
  36924. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36925. if (this._forceAlphaTest) {
  36926. return true;
  36927. }
  36928. if (this._linkRefractionWithTransparency) {
  36929. return false;
  36930. }
  36931. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  36932. };
  36933. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36934. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  36935. };
  36936. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36937. return this._albedoTexture;
  36938. };
  36939. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36940. if (this.isFrozen) {
  36941. if (this._wasPreviouslyReady) {
  36942. return true;
  36943. }
  36944. }
  36945. if (!subMesh._materialDefines) {
  36946. subMesh._materialDefines = new PBRMaterialDefines();
  36947. }
  36948. var scene = this.getScene();
  36949. var defines = subMesh._materialDefines;
  36950. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36951. if (defines._renderId === scene.getRenderId()) {
  36952. return true;
  36953. }
  36954. }
  36955. var engine = scene.getEngine();
  36956. // Lights
  36957. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36958. defines._needNormals = true;
  36959. // Textures
  36960. if (defines._areTexturesDirty) {
  36961. defines._needUVs = false;
  36962. if (scene.texturesEnabled) {
  36963. if (scene.getEngine().getCaps().textureLOD) {
  36964. defines.LODBASEDMICROSFURACE = true;
  36965. }
  36966. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36967. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36968. return false;
  36969. }
  36970. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36971. }
  36972. else {
  36973. defines.ALBEDO = false;
  36974. }
  36975. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36976. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36977. return false;
  36978. }
  36979. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36980. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36981. }
  36982. else {
  36983. defines.AMBIENT = false;
  36984. }
  36985. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36986. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36987. return false;
  36988. }
  36989. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36990. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36991. }
  36992. else {
  36993. defines.OPACITY = false;
  36994. }
  36995. var reflectionTexture = this._getReflectionTexture();
  36996. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36997. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36998. return false;
  36999. }
  37000. defines.REFLECTION = true;
  37001. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  37002. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  37003. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37004. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  37005. defines.INVERTCUBICMAP = true;
  37006. }
  37007. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  37008. switch (reflectionTexture.coordinatesMode) {
  37009. case BABYLON.Texture.CUBIC_MODE:
  37010. case BABYLON.Texture.INVCUBIC_MODE:
  37011. defines.REFLECTIONMAP_CUBIC = true;
  37012. break;
  37013. case BABYLON.Texture.EXPLICIT_MODE:
  37014. defines.REFLECTIONMAP_EXPLICIT = true;
  37015. break;
  37016. case BABYLON.Texture.PLANAR_MODE:
  37017. defines.REFLECTIONMAP_PLANAR = true;
  37018. break;
  37019. case BABYLON.Texture.PROJECTION_MODE:
  37020. defines.REFLECTIONMAP_PROJECTION = true;
  37021. break;
  37022. case BABYLON.Texture.SKYBOX_MODE:
  37023. defines.REFLECTIONMAP_SKYBOX = true;
  37024. break;
  37025. case BABYLON.Texture.SPHERICAL_MODE:
  37026. defines.REFLECTIONMAP_SPHERICAL = true;
  37027. break;
  37028. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37029. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37030. break;
  37031. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37032. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37033. break;
  37034. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37035. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37036. break;
  37037. }
  37038. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37039. if (reflectionTexture.sphericalPolynomial) {
  37040. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37041. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37042. defines.USESPHERICALINFRAGMENT = true;
  37043. }
  37044. }
  37045. }
  37046. }
  37047. else {
  37048. defines.REFLECTION = false;
  37049. defines.REFLECTIONMAP_3D = false;
  37050. defines.REFLECTIONMAP_SPHERICAL = false;
  37051. defines.REFLECTIONMAP_PLANAR = false;
  37052. defines.REFLECTIONMAP_CUBIC = false;
  37053. defines.REFLECTIONMAP_PROJECTION = false;
  37054. defines.REFLECTIONMAP_SKYBOX = false;
  37055. defines.REFLECTIONMAP_EXPLICIT = false;
  37056. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37057. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37058. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37059. defines.INVERTCUBICMAP = false;
  37060. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37061. defines.USESPHERICALINFRAGMENT = false;
  37062. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37063. defines.LODINREFLECTIONALPHA = false;
  37064. defines.GAMMAREFLECTION = false;
  37065. }
  37066. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37067. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37068. return false;
  37069. }
  37070. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37071. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37072. }
  37073. else {
  37074. defines.LIGHTMAP = false;
  37075. }
  37076. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37077. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37078. return false;
  37079. }
  37080. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37081. }
  37082. else {
  37083. defines.EMISSIVE = false;
  37084. }
  37085. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37086. if (this._metallicTexture) {
  37087. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37088. return false;
  37089. }
  37090. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37091. defines.METALLICWORKFLOW = true;
  37092. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37093. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37094. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37095. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37096. }
  37097. else if (this._reflectivityTexture) {
  37098. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37099. return false;
  37100. }
  37101. defines.METALLICWORKFLOW = false;
  37102. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37103. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37104. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37105. }
  37106. else {
  37107. defines.METALLICWORKFLOW = false;
  37108. defines.REFLECTIVITY = false;
  37109. }
  37110. if (this._microSurfaceTexture) {
  37111. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37112. return false;
  37113. }
  37114. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37115. }
  37116. else {
  37117. defines.MICROSURFACEMAP = false;
  37118. }
  37119. }
  37120. else {
  37121. defines.REFLECTIVITY = false;
  37122. defines.MICROSURFACEMAP = false;
  37123. }
  37124. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37125. // Bump texure can not be none blocking.
  37126. if (!this._bumpTexture.isReady()) {
  37127. return false;
  37128. }
  37129. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37130. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37131. defines.PARALLAX = true;
  37132. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37133. }
  37134. else {
  37135. defines.PARALLAX = false;
  37136. }
  37137. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  37138. }
  37139. else {
  37140. defines.BUMP = false;
  37141. }
  37142. var refractionTexture = this._getRefractionTexture();
  37143. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37144. if (!refractionTexture.isReadyOrNotBlocking()) {
  37145. return false;
  37146. }
  37147. defines.REFRACTION = true;
  37148. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37149. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37150. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  37151. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37152. if (this._linkRefractionWithTransparency) {
  37153. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37154. }
  37155. }
  37156. else {
  37157. defines.REFRACTION = false;
  37158. }
  37159. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37160. // This is blocking.
  37161. if (!this._environmentBRDFTexture.isReady()) {
  37162. return false;
  37163. }
  37164. defines.ENVIRONMENTBRDF = true;
  37165. }
  37166. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37167. defines.ALPHAFROMALBEDO = true;
  37168. }
  37169. }
  37170. if (this._useSpecularOverAlpha) {
  37171. defines.SPECULAROVERALPHA = true;
  37172. }
  37173. if (this._usePhysicalLightFalloff) {
  37174. defines.USEPHYSICALLIGHTFALLOFF = true;
  37175. }
  37176. if (this._useRadianceOverAlpha) {
  37177. defines.RADIANCEOVERALPHA = true;
  37178. }
  37179. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37180. defines.METALLICWORKFLOW = true;
  37181. }
  37182. if (!this.backFaceCulling && this._twoSidedLighting) {
  37183. defines.TWOSIDEDLIGHTING = true;
  37184. }
  37185. defines.ALPHATESTVALUE = this._alphaCutOff;
  37186. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  37187. defines.ALPHABLEND = this.needAlphaBlending();
  37188. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  37189. }
  37190. if (defines._areImageProcessingDirty) {
  37191. if (!this._imageProcessingConfiguration.isReady()) {
  37192. return false;
  37193. }
  37194. this._imageProcessingConfiguration.prepareDefines(defines);
  37195. }
  37196. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37197. // Misc.
  37198. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37199. // Values that need to be evaluated on every frame
  37200. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  37201. // Attribs
  37202. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  37203. if (mesh) {
  37204. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37205. mesh.createNormals(true);
  37206. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  37207. }
  37208. }
  37209. }
  37210. // Get correct effect
  37211. if (defines.isDirty) {
  37212. defines.markAsProcessed();
  37213. scene.resetCachedMaterial();
  37214. // Fallbacks
  37215. var fallbacks = new BABYLON.EffectFallbacks();
  37216. if (defines.ENVIRONMENTBRDF) {
  37217. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  37218. }
  37219. if (defines.REFLECTION) {
  37220. fallbacks.addFallback(0, "REFLECTION");
  37221. }
  37222. if (defines.REFRACTION) {
  37223. fallbacks.addFallback(0, "REFRACTION");
  37224. }
  37225. if (defines.REFLECTIVITY) {
  37226. fallbacks.addFallback(0, "REFLECTIVITY");
  37227. }
  37228. if (defines.BUMP) {
  37229. fallbacks.addFallback(0, "BUMP");
  37230. }
  37231. if (defines.PARALLAX) {
  37232. fallbacks.addFallback(1, "PARALLAX");
  37233. }
  37234. if (defines.PARALLAXOCCLUSION) {
  37235. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37236. }
  37237. if (defines.SPECULAROVERALPHA) {
  37238. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37239. }
  37240. if (defines.FOG) {
  37241. fallbacks.addFallback(1, "FOG");
  37242. }
  37243. if (defines.POINTSIZE) {
  37244. fallbacks.addFallback(0, "POINTSIZE");
  37245. }
  37246. if (defines.LOGARITHMICDEPTH) {
  37247. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37248. }
  37249. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37250. if (defines.SPECULARTERM) {
  37251. fallbacks.addFallback(0, "SPECULARTERM");
  37252. }
  37253. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37254. fallbacks.addCPUSkinningFallback(0, mesh);
  37255. }
  37256. //Attributes
  37257. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37258. if (defines.NORMAL) {
  37259. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37260. }
  37261. if (defines.TANGENT) {
  37262. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37263. }
  37264. if (defines.UV1) {
  37265. attribs.push(BABYLON.VertexBuffer.UVKind);
  37266. }
  37267. if (defines.UV2) {
  37268. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37269. }
  37270. if (defines.VERTEXCOLOR) {
  37271. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37272. }
  37273. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37274. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37275. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37276. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37277. "vFogInfos", "vFogColor", "pointSize",
  37278. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37279. "mBones",
  37280. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37281. "vLightingIntensity",
  37282. "logarithmicDepthConstant",
  37283. "vSphericalX", "vSphericalY", "vSphericalZ",
  37284. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37285. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37286. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37287. "vNormalReoderParams"
  37288. ];
  37289. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37290. "bumpSampler", "lightmapSampler", "opacitySampler",
  37291. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37292. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37293. "microSurfaceSampler", "environmentBrdfSampler"];
  37294. var uniformBuffers = ["Material", "Scene"];
  37295. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37296. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37297. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37298. uniformsNames: uniforms,
  37299. uniformBuffersNames: uniformBuffers,
  37300. samplers: samplers,
  37301. defines: defines,
  37302. maxSimultaneousLights: this._maxSimultaneousLights
  37303. });
  37304. var onCompiled = function (effect) {
  37305. if (this.onCompiled) {
  37306. this.onCompiled(effect);
  37307. }
  37308. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37309. }.bind(this);
  37310. var join = defines.toString();
  37311. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37312. attributes: attribs,
  37313. uniformsNames: uniforms,
  37314. uniformBuffersNames: uniformBuffers,
  37315. samplers: samplers,
  37316. defines: join,
  37317. fallbacks: fallbacks,
  37318. onCompiled: onCompiled,
  37319. onError: this.onError,
  37320. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37321. }, engine), defines);
  37322. this.buildUniformLayout();
  37323. }
  37324. if (!subMesh.effect.isReady()) {
  37325. return false;
  37326. }
  37327. defines._renderId = scene.getRenderId();
  37328. this._wasPreviouslyReady = true;
  37329. return true;
  37330. };
  37331. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37332. // Order is important !
  37333. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37334. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37335. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37336. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37337. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37338. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37339. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37340. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37341. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37342. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37343. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37344. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37345. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37346. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37347. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37348. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37349. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37350. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37351. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  37352. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37353. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37354. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37355. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37356. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37357. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37358. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37359. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37360. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37361. this._uniformBuffer.addUniform("pointSize", 1);
  37362. this._uniformBuffer.create();
  37363. };
  37364. PBRBaseMaterial.prototype.unbind = function () {
  37365. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37366. this._uniformBuffer.setTexture("reflectionSampler", null);
  37367. }
  37368. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37369. this._uniformBuffer.setTexture("refractionSampler", null);
  37370. }
  37371. _super.prototype.unbind.call(this);
  37372. };
  37373. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37374. this._activeEffect.setMatrix("world", world);
  37375. };
  37376. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37377. var scene = this.getScene();
  37378. var defines = subMesh._materialDefines;
  37379. if (!defines) {
  37380. return;
  37381. }
  37382. var effect = subMesh.effect;
  37383. this._activeEffect = effect;
  37384. // Matrices
  37385. this.bindOnlyWorldMatrix(world);
  37386. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37387. // Bones
  37388. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37389. if (mustRebind) {
  37390. this._uniformBuffer.bindToEffect(effect, "Material");
  37391. this.bindViewProjection(effect);
  37392. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37393. // Texture uniforms
  37394. if (scene.texturesEnabled) {
  37395. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37396. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37397. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37398. }
  37399. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37400. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37401. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37402. }
  37403. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37404. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37405. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37406. }
  37407. var reflectionTexture = this._getReflectionTexture();
  37408. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37409. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37410. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37411. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37412. var polynomials = reflectionTexture.sphericalPolynomial;
  37413. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37414. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37415. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37416. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37417. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37418. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37419. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37420. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37421. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37422. }
  37423. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37424. }
  37425. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37426. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37427. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37428. }
  37429. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37430. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37431. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37432. }
  37433. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37434. if (this._metallicTexture) {
  37435. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37436. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37437. }
  37438. else if (this._reflectivityTexture) {
  37439. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37440. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37441. }
  37442. if (this._microSurfaceTexture) {
  37443. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37444. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37445. }
  37446. }
  37447. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37448. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37449. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37450. if (scene._mirroredCameraPosition) {
  37451. 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);
  37452. }
  37453. else {
  37454. 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);
  37455. }
  37456. }
  37457. var refractionTexture = this._getRefractionTexture();
  37458. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37459. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37460. var depth = 1.0;
  37461. if (!refractionTexture.isCube) {
  37462. if (refractionTexture.depth) {
  37463. depth = refractionTexture.depth;
  37464. }
  37465. }
  37466. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37467. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37468. }
  37469. }
  37470. // Point size
  37471. if (this.pointsCloud) {
  37472. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37473. }
  37474. // Colors
  37475. if (defines.METALLICWORKFLOW) {
  37476. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37477. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37478. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37479. }
  37480. else {
  37481. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37482. }
  37483. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37484. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37485. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37486. // Misc
  37487. this._lightingInfos.x = this._directIntensity;
  37488. this._lightingInfos.y = this._emissiveIntensity;
  37489. this._lightingInfos.z = this._environmentIntensity;
  37490. this._lightingInfos.w = this._specularIntensity;
  37491. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37492. }
  37493. // Textures
  37494. if (scene.texturesEnabled) {
  37495. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37496. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37497. }
  37498. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37499. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37500. }
  37501. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37502. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37503. }
  37504. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37505. if (defines.LODBASEDMICROSFURACE) {
  37506. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37507. }
  37508. else {
  37509. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37510. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37511. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37512. }
  37513. }
  37514. if (defines.ENVIRONMENTBRDF) {
  37515. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37516. }
  37517. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37518. if (defines.LODBASEDMICROSFURACE) {
  37519. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37520. }
  37521. else {
  37522. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37523. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37524. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37525. }
  37526. }
  37527. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37528. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37529. }
  37530. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37531. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37532. }
  37533. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37534. if (this._metallicTexture) {
  37535. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37536. }
  37537. else if (this._reflectivityTexture) {
  37538. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37539. }
  37540. if (this._microSurfaceTexture) {
  37541. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37542. }
  37543. }
  37544. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37545. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37546. }
  37547. }
  37548. // Clip plane
  37549. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37550. // Colors
  37551. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37552. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  37553. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  37554. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37555. }
  37556. if (mustRebind || !this.isFrozen) {
  37557. // Lights
  37558. if (scene.lightsEnabled && !this._disableLighting) {
  37559. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37560. }
  37561. // View
  37562. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37563. this.bindView(effect);
  37564. }
  37565. // Fog
  37566. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37567. // Morph targets
  37568. if (defines.NUM_MORPH_INFLUENCERS) {
  37569. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37570. }
  37571. // image processing
  37572. this._imageProcessingConfiguration.bind(this._activeEffect);
  37573. // Log. depth
  37574. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37575. }
  37576. this._uniformBuffer.update();
  37577. this._afterBind(mesh);
  37578. scene = null;
  37579. };
  37580. PBRBaseMaterial.prototype.getAnimatables = function () {
  37581. var results = [];
  37582. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37583. results.push(this._albedoTexture);
  37584. }
  37585. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37586. results.push(this._ambientTexture);
  37587. }
  37588. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37589. results.push(this._opacityTexture);
  37590. }
  37591. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37592. results.push(this._reflectionTexture);
  37593. }
  37594. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37595. results.push(this._emissiveTexture);
  37596. }
  37597. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37598. results.push(this._metallicTexture);
  37599. }
  37600. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37601. results.push(this._reflectivityTexture);
  37602. }
  37603. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37604. results.push(this._bumpTexture);
  37605. }
  37606. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37607. results.push(this._lightmapTexture);
  37608. }
  37609. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37610. results.push(this._refractionTexture);
  37611. }
  37612. return results;
  37613. };
  37614. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37615. if (this._reflectionTexture) {
  37616. return this._reflectionTexture;
  37617. }
  37618. return this.getScene().environmentTexture;
  37619. };
  37620. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37621. if (this._refractionTexture) {
  37622. return this._refractionTexture;
  37623. }
  37624. if (this._linkRefractionWithTransparency) {
  37625. return this.getScene().environmentTexture;
  37626. }
  37627. return null;
  37628. };
  37629. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37630. if (forceDisposeTextures) {
  37631. if (this._albedoTexture) {
  37632. this._albedoTexture.dispose();
  37633. }
  37634. if (this._ambientTexture) {
  37635. this._ambientTexture.dispose();
  37636. }
  37637. if (this._opacityTexture) {
  37638. this._opacityTexture.dispose();
  37639. }
  37640. if (this._reflectionTexture) {
  37641. this._reflectionTexture.dispose();
  37642. }
  37643. if (this._environmentBRDFTexture) {
  37644. this._environmentBRDFTexture.dispose();
  37645. }
  37646. if (this._emissiveTexture) {
  37647. this._emissiveTexture.dispose();
  37648. }
  37649. if (this._metallicTexture) {
  37650. this._metallicTexture.dispose();
  37651. }
  37652. if (this._reflectivityTexture) {
  37653. this._reflectivityTexture.dispose();
  37654. }
  37655. if (this._bumpTexture) {
  37656. this._bumpTexture.dispose();
  37657. }
  37658. if (this._lightmapTexture) {
  37659. this._lightmapTexture.dispose();
  37660. }
  37661. if (this._refractionTexture) {
  37662. this._refractionTexture.dispose();
  37663. }
  37664. }
  37665. this._renderTargets.dispose();
  37666. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37667. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37668. }
  37669. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37670. };
  37671. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37672. __decorate([
  37673. BABYLON.serializeAsImageProcessingConfiguration()
  37674. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37675. __decorate([
  37676. BABYLON.serialize()
  37677. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37678. return PBRBaseMaterial;
  37679. }(BABYLON.PushMaterial));
  37680. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37681. })(BABYLON || (BABYLON = {}));
  37682. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37683. var BABYLON;
  37684. (function (BABYLON) {
  37685. var Internals;
  37686. (function (Internals) {
  37687. /**
  37688. * The Physically based simple base material of BJS.
  37689. *
  37690. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37691. * It is used as the base class for both the specGloss and metalRough conventions.
  37692. */
  37693. var PBRBaseSimpleMaterial = (function (_super) {
  37694. __extends(PBRBaseSimpleMaterial, _super);
  37695. /**
  37696. * Instantiates a new PBRMaterial instance.
  37697. *
  37698. * @param name The material name
  37699. * @param scene The scene the material will be use in.
  37700. */
  37701. function PBRBaseSimpleMaterial(name, scene) {
  37702. var _this = _super.call(this, name, scene) || this;
  37703. /**
  37704. * Number of Simultaneous lights allowed on the material.
  37705. */
  37706. _this.maxSimultaneousLights = 4;
  37707. /**
  37708. * If sets to true, disables all the lights affecting the material.
  37709. */
  37710. _this.disableLighting = false;
  37711. /**
  37712. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37713. */
  37714. _this.invertNormalMapX = false;
  37715. /**
  37716. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37717. */
  37718. _this.invertNormalMapY = false;
  37719. /**
  37720. * Emissivie color used to self-illuminate the model.
  37721. */
  37722. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37723. /**
  37724. * Occlusion Channel Strenght.
  37725. */
  37726. _this.occlusionStrength = 1.0;
  37727. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  37728. _this._useAmbientInGrayScale = true;
  37729. return _this;
  37730. }
  37731. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  37732. /**
  37733. * Gets the current transparency mode.
  37734. */
  37735. get: function () {
  37736. return this._transparencyMode;
  37737. },
  37738. /**
  37739. * Sets the transparency mode of the material.
  37740. */
  37741. set: function (value) {
  37742. if (this._transparencyMode === value) {
  37743. return;
  37744. }
  37745. this._transparencyMode = value;
  37746. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  37747. this._forceAlphaTest = true;
  37748. }
  37749. else {
  37750. this._forceAlphaTest = false;
  37751. }
  37752. this._markAllSubMeshesAsTexturesDirty();
  37753. },
  37754. enumerable: true,
  37755. configurable: true
  37756. });
  37757. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37758. /**
  37759. * Gets the current double sided mode.
  37760. */
  37761. get: function () {
  37762. return this._twoSidedLighting;
  37763. },
  37764. /**
  37765. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37766. */
  37767. set: function (value) {
  37768. if (this._twoSidedLighting === value) {
  37769. return;
  37770. }
  37771. this._twoSidedLighting = value;
  37772. this.backFaceCulling = !value;
  37773. this._markAllSubMeshesAsTexturesDirty();
  37774. },
  37775. enumerable: true,
  37776. configurable: true
  37777. });
  37778. /**
  37779. * Specifies wether or not the alpha value of the albedo texture should be used.
  37780. */
  37781. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37782. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  37783. };
  37784. /**
  37785. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  37786. */
  37787. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  37788. if (this._linkRefractionWithTransparency) {
  37789. return false;
  37790. }
  37791. return (this.alpha < 1.0) ||
  37792. (this._shouldUseAlphaFromAlbedoTexture() &&
  37793. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  37794. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  37795. };
  37796. /**
  37797. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  37798. */
  37799. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  37800. if (this._linkRefractionWithTransparency) {
  37801. return false;
  37802. }
  37803. return this._shouldUseAlphaFromAlbedoTexture() &&
  37804. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  37805. };
  37806. /**
  37807. * Return the active textures of the material.
  37808. */
  37809. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37810. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37811. if (this.environmentTexture) {
  37812. activeTextures.push(this.environmentTexture);
  37813. }
  37814. if (this.normalTexture) {
  37815. activeTextures.push(this.normalTexture);
  37816. }
  37817. if (this.emissiveTexture) {
  37818. activeTextures.push(this.emissiveTexture);
  37819. }
  37820. if (this.occlusionTexture) {
  37821. activeTextures.push(this.occlusionTexture);
  37822. }
  37823. return activeTextures;
  37824. };
  37825. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37826. return "PBRBaseSimpleMaterial";
  37827. };
  37828. __decorate([
  37829. BABYLON.serialize(),
  37830. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37831. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37832. __decorate([
  37833. BABYLON.serialize(),
  37834. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37835. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37836. __decorate([
  37837. BABYLON.serializeAsTexture(),
  37838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37839. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37840. __decorate([
  37841. BABYLON.serialize(),
  37842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37843. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37844. __decorate([
  37845. BABYLON.serialize(),
  37846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37847. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37848. __decorate([
  37849. BABYLON.serializeAsTexture(),
  37850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37851. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37852. __decorate([
  37853. BABYLON.serializeAsColor3("emissive"),
  37854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37855. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37856. __decorate([
  37857. BABYLON.serializeAsTexture(),
  37858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37859. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37860. __decorate([
  37861. BABYLON.serialize(),
  37862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37863. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37864. __decorate([
  37865. BABYLON.serializeAsTexture(),
  37866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37867. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37868. __decorate([
  37869. BABYLON.serialize(),
  37870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37871. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37872. __decorate([
  37873. BABYLON.serialize()
  37874. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  37875. __decorate([
  37876. BABYLON.serialize()
  37877. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37878. return PBRBaseSimpleMaterial;
  37879. }(BABYLON.PBRBaseMaterial));
  37880. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37881. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37882. })(BABYLON || (BABYLON = {}));
  37883. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37884. var BABYLON;
  37885. (function (BABYLON) {
  37886. /**
  37887. * The Physically based material of BJS.
  37888. *
  37889. * This offers the main features of a standard PBR material.
  37890. * For more information, please refer to the documentation :
  37891. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37892. */
  37893. var PBRMaterial = (function (_super) {
  37894. __extends(PBRMaterial, _super);
  37895. /**
  37896. * Instantiates a new PBRMaterial instance.
  37897. *
  37898. * @param name The material name
  37899. * @param scene The scene the material will be use in.
  37900. */
  37901. function PBRMaterial(name, scene) {
  37902. var _this = _super.call(this, name, scene) || this;
  37903. /**
  37904. * Intensity of the direct lights e.g. the four lights available in your scene.
  37905. * This impacts both the direct diffuse and specular highlights.
  37906. */
  37907. _this.directIntensity = 1.0;
  37908. /**
  37909. * Intensity of the emissive part of the material.
  37910. * This helps controlling the emissive effect without modifying the emissive color.
  37911. */
  37912. _this.emissiveIntensity = 1.0;
  37913. /**
  37914. * Intensity of the environment e.g. how much the environment will light the object
  37915. * either through harmonics for rough material or through the refelction for shiny ones.
  37916. */
  37917. _this.environmentIntensity = 1.0;
  37918. /**
  37919. * This is a special control allowing the reduction of the specular highlights coming from the
  37920. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37921. */
  37922. _this.specularIntensity = 1.0;
  37923. /**
  37924. * Debug Control allowing disabling the bump map on this material.
  37925. */
  37926. _this.disableBumpMap = false;
  37927. /**
  37928. * AKA Occlusion Texture Intensity in other nomenclature.
  37929. */
  37930. _this.ambientTextureStrength = 1.0;
  37931. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37932. /**
  37933. * AKA Diffuse Color in other nomenclature.
  37934. */
  37935. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37936. /**
  37937. * AKA Specular Color in other nomenclature.
  37938. */
  37939. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37940. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37941. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37942. /**
  37943. * AKA Glossiness in other nomenclature.
  37944. */
  37945. _this.microSurface = 1.0;
  37946. /**
  37947. * source material index of refraction (IOR)' / 'destination material IOR.
  37948. */
  37949. _this.indexOfRefraction = 0.66;
  37950. /**
  37951. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37952. */
  37953. _this.invertRefractionY = false;
  37954. /**
  37955. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37956. * Materials half opaque for instance using refraction could benefit from this control.
  37957. */
  37958. _this.linkRefractionWithTransparency = false;
  37959. _this.useLightmapAsShadowmap = false;
  37960. /**
  37961. * Specifies that the alpha is coming form the albedo channel alpha channel.
  37962. */
  37963. _this.useAlphaFromAlbedoTexture = false;
  37964. /**
  37965. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37966. */
  37967. _this.forceAlphaTest = false;
  37968. /**
  37969. * Defines the alpha limits in alpha test mode.
  37970. */
  37971. _this.alphaCutOff = 0.4;
  37972. /**
  37973. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37974. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37975. */
  37976. _this.useSpecularOverAlpha = true;
  37977. /**
  37978. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37979. */
  37980. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37981. /**
  37982. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37983. */
  37984. _this.useRoughnessFromMetallicTextureAlpha = true;
  37985. /**
  37986. * Specifies if the metallic texture contains the roughness information in its green channel.
  37987. */
  37988. _this.useRoughnessFromMetallicTextureGreen = false;
  37989. /**
  37990. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37991. */
  37992. _this.useMetallnessFromMetallicTextureBlue = false;
  37993. /**
  37994. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37995. */
  37996. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  37997. /**
  37998. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37999. */
  38000. _this.useAmbientInGrayScale = false;
  38001. /**
  38002. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38003. * The material will try to infer what glossiness each pixel should be.
  38004. */
  38005. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38006. /**
  38007. * BJS is using an harcoded light falloff based on a manually sets up range.
  38008. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38009. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38010. */
  38011. _this.usePhysicalLightFalloff = true;
  38012. /**
  38013. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38014. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38015. */
  38016. _this.useRadianceOverAlpha = true;
  38017. /**
  38018. * Allows using the bump map in parallax mode.
  38019. */
  38020. _this.useParallax = false;
  38021. /**
  38022. * Allows using the bump map in parallax occlusion mode.
  38023. */
  38024. _this.useParallaxOcclusion = false;
  38025. /**
  38026. * Controls the scale bias of the parallax mode.
  38027. */
  38028. _this.parallaxScaleBias = 0.05;
  38029. /**
  38030. * If sets to true, disables all the lights affecting the material.
  38031. */
  38032. _this.disableLighting = false;
  38033. /**
  38034. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38035. */
  38036. _this.forceIrradianceInFragment = false;
  38037. /**
  38038. * Number of Simultaneous lights allowed on the material.
  38039. */
  38040. _this.maxSimultaneousLights = 4;
  38041. /**
  38042. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38043. */
  38044. _this.invertNormalMapX = false;
  38045. /**
  38046. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38047. */
  38048. _this.invertNormalMapY = false;
  38049. /**
  38050. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38051. */
  38052. _this.twoSidedLighting = false;
  38053. /**
  38054. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  38055. * in your scene composition.
  38056. */
  38057. _this.preMultiplyAlpha = false;
  38058. /**
  38059. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38060. * And/Or occlude the blended part.
  38061. */
  38062. _this.useAlphaFresnel = false;
  38063. /**
  38064. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38065. * And/Or occlude the blended part.
  38066. */
  38067. _this.environmentBRDFTexture = null;
  38068. /**
  38069. * Force normal to face away from face.
  38070. * (Temporary internal fix to remove before 3.1)
  38071. */
  38072. _this.forceNormalForward = false;
  38073. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38074. return _this;
  38075. }
  38076. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38077. /**
  38078. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38079. */
  38080. get: function () {
  38081. return this._PBRMATERIAL_OPAQUE;
  38082. },
  38083. enumerable: true,
  38084. configurable: true
  38085. });
  38086. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38087. /**
  38088. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38089. */
  38090. get: function () {
  38091. return this._PBRMATERIAL_ALPHATEST;
  38092. },
  38093. enumerable: true,
  38094. configurable: true
  38095. });
  38096. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38097. /**
  38098. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38099. */
  38100. get: function () {
  38101. return this._PBRMATERIAL_ALPHABLEND;
  38102. },
  38103. enumerable: true,
  38104. configurable: true
  38105. });
  38106. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38107. /**
  38108. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38109. * They are also discarded below the alpha cutoff threshold to improve performances.
  38110. */
  38111. get: function () {
  38112. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38113. },
  38114. enumerable: true,
  38115. configurable: true
  38116. });
  38117. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38118. /**
  38119. * Gets the image processing configuration used either in this material.
  38120. */
  38121. get: function () {
  38122. return this._imageProcessingConfiguration;
  38123. },
  38124. /**
  38125. * Sets the Default image processing configuration used either in the this material.
  38126. *
  38127. * If sets to null, the scene one is in use.
  38128. */
  38129. set: function (value) {
  38130. this._attachImageProcessingConfiguration(value);
  38131. // Ensure the effect will be rebuilt.
  38132. this._markAllSubMeshesAsTexturesDirty();
  38133. },
  38134. enumerable: true,
  38135. configurable: true
  38136. });
  38137. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38138. /**
  38139. * Gets wether the color curves effect is enabled.
  38140. */
  38141. get: function () {
  38142. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38143. },
  38144. /**
  38145. * Sets wether the color curves effect is enabled.
  38146. */
  38147. set: function (value) {
  38148. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38149. },
  38150. enumerable: true,
  38151. configurable: true
  38152. });
  38153. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38154. /**
  38155. * Gets wether the color grading effect is enabled.
  38156. */
  38157. get: function () {
  38158. return this.imageProcessingConfiguration.colorGradingEnabled;
  38159. },
  38160. /**
  38161. * Gets wether the color grading effect is enabled.
  38162. */
  38163. set: function (value) {
  38164. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38165. },
  38166. enumerable: true,
  38167. configurable: true
  38168. });
  38169. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38170. /**
  38171. * Gets wether tonemapping is enabled or not.
  38172. */
  38173. get: function () {
  38174. return this._imageProcessingConfiguration.toneMappingEnabled;
  38175. },
  38176. /**
  38177. * Sets wether tonemapping is enabled or not
  38178. */
  38179. set: function (value) {
  38180. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38181. },
  38182. enumerable: true,
  38183. configurable: true
  38184. });
  38185. ;
  38186. ;
  38187. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38188. /**
  38189. * The camera exposure used on this material.
  38190. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38191. * This corresponds to a photographic exposure.
  38192. */
  38193. get: function () {
  38194. return this._imageProcessingConfiguration.exposure;
  38195. },
  38196. /**
  38197. * The camera exposure used on this material.
  38198. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38199. * This corresponds to a photographic exposure.
  38200. */
  38201. set: function (value) {
  38202. this._imageProcessingConfiguration.exposure = value;
  38203. },
  38204. enumerable: true,
  38205. configurable: true
  38206. });
  38207. ;
  38208. ;
  38209. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38210. /**
  38211. * Gets The camera contrast used on this material.
  38212. */
  38213. get: function () {
  38214. return this._imageProcessingConfiguration.contrast;
  38215. },
  38216. /**
  38217. * Sets The camera contrast used on this material.
  38218. */
  38219. set: function (value) {
  38220. this._imageProcessingConfiguration.contrast = value;
  38221. },
  38222. enumerable: true,
  38223. configurable: true
  38224. });
  38225. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38226. /**
  38227. * Gets the Color Grading 2D Lookup Texture.
  38228. */
  38229. get: function () {
  38230. return this._imageProcessingConfiguration.colorGradingTexture;
  38231. },
  38232. /**
  38233. * Sets the Color Grading 2D Lookup Texture.
  38234. */
  38235. set: function (value) {
  38236. this._imageProcessingConfiguration.colorGradingTexture = value;
  38237. },
  38238. enumerable: true,
  38239. configurable: true
  38240. });
  38241. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38242. /**
  38243. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38244. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38245. * 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;
  38246. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38247. */
  38248. get: function () {
  38249. return this._imageProcessingConfiguration.colorCurves;
  38250. },
  38251. /**
  38252. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38253. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38254. * 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;
  38255. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38256. */
  38257. set: function (value) {
  38258. this._imageProcessingConfiguration.colorCurves = value;
  38259. },
  38260. enumerable: true,
  38261. configurable: true
  38262. });
  38263. PBRMaterial.prototype.getClassName = function () {
  38264. return "PBRMaterial";
  38265. };
  38266. PBRMaterial.prototype.getActiveTextures = function () {
  38267. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38268. if (this._albedoTexture) {
  38269. activeTextures.push(this._albedoTexture);
  38270. }
  38271. if (this._ambientTexture) {
  38272. activeTextures.push(this._ambientTexture);
  38273. }
  38274. if (this._opacityTexture) {
  38275. activeTextures.push(this._opacityTexture);
  38276. }
  38277. if (this._reflectionTexture) {
  38278. activeTextures.push(this._reflectionTexture);
  38279. }
  38280. if (this._emissiveTexture) {
  38281. activeTextures.push(this._emissiveTexture);
  38282. }
  38283. if (this._reflectivityTexture) {
  38284. activeTextures.push(this._reflectivityTexture);
  38285. }
  38286. if (this._metallicTexture) {
  38287. activeTextures.push(this._metallicTexture);
  38288. }
  38289. if (this._microSurfaceTexture) {
  38290. activeTextures.push(this._microSurfaceTexture);
  38291. }
  38292. if (this._bumpTexture) {
  38293. activeTextures.push(this._bumpTexture);
  38294. }
  38295. if (this._lightmapTexture) {
  38296. activeTextures.push(this._lightmapTexture);
  38297. }
  38298. if (this._refractionTexture) {
  38299. activeTextures.push(this._refractionTexture);
  38300. }
  38301. return activeTextures;
  38302. };
  38303. PBRMaterial.prototype.hasTexture = function (texture) {
  38304. if (_super.prototype.hasTexture.call(this, texture)) {
  38305. return true;
  38306. }
  38307. if (this._albedoTexture === texture) {
  38308. return true;
  38309. }
  38310. if (this._ambientTexture === texture) {
  38311. return true;
  38312. }
  38313. if (this._opacityTexture === texture) {
  38314. return true;
  38315. }
  38316. if (this._reflectionTexture === texture) {
  38317. return true;
  38318. }
  38319. if (this._reflectivityTexture === texture) {
  38320. return true;
  38321. }
  38322. if (this._metallicTexture === texture) {
  38323. return true;
  38324. }
  38325. if (this._microSurfaceTexture === texture) {
  38326. return true;
  38327. }
  38328. if (this._bumpTexture === texture) {
  38329. return true;
  38330. }
  38331. if (this._lightmapTexture === texture) {
  38332. return true;
  38333. }
  38334. if (this._refractionTexture === texture) {
  38335. return true;
  38336. }
  38337. return false;
  38338. };
  38339. PBRMaterial.prototype.clone = function (name) {
  38340. var _this = this;
  38341. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38342. };
  38343. PBRMaterial.prototype.serialize = function () {
  38344. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38345. serializationObject.customType = "BABYLON.PBRMaterial";
  38346. return serializationObject;
  38347. };
  38348. // Statics
  38349. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38350. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38351. };
  38352. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38353. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38354. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38355. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38356. __decorate([
  38357. BABYLON.serialize(),
  38358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38359. ], PBRMaterial.prototype, "directIntensity", void 0);
  38360. __decorate([
  38361. BABYLON.serialize(),
  38362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38363. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38364. __decorate([
  38365. BABYLON.serialize(),
  38366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38367. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38368. __decorate([
  38369. BABYLON.serialize(),
  38370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38371. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38372. __decorate([
  38373. BABYLON.serialize(),
  38374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38375. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38376. __decorate([
  38377. BABYLON.serializeAsTexture(),
  38378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38379. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38380. __decorate([
  38381. BABYLON.serializeAsTexture(),
  38382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38383. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38384. __decorate([
  38385. BABYLON.serialize(),
  38386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38387. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38388. __decorate([
  38389. BABYLON.serializeAsTexture(),
  38390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38391. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38392. __decorate([
  38393. BABYLON.serializeAsTexture(),
  38394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38395. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38396. __decorate([
  38397. BABYLON.serializeAsTexture(),
  38398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38399. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38400. __decorate([
  38401. BABYLON.serializeAsTexture(),
  38402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38403. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38404. __decorate([
  38405. BABYLON.serializeAsTexture(),
  38406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38407. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38408. __decorate([
  38409. BABYLON.serialize(),
  38410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38411. ], PBRMaterial.prototype, "metallic", void 0);
  38412. __decorate([
  38413. BABYLON.serialize(),
  38414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38415. ], PBRMaterial.prototype, "roughness", void 0);
  38416. __decorate([
  38417. BABYLON.serializeAsTexture(),
  38418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38419. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38420. __decorate([
  38421. BABYLON.serializeAsTexture(),
  38422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38423. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38424. __decorate([
  38425. BABYLON.serializeAsTexture(),
  38426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38427. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38428. __decorate([
  38429. BABYLON.serializeAsTexture(),
  38430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38431. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38432. __decorate([
  38433. BABYLON.serializeAsColor3("ambient"),
  38434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38435. ], PBRMaterial.prototype, "ambientColor", void 0);
  38436. __decorate([
  38437. BABYLON.serializeAsColor3("albedo"),
  38438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38439. ], PBRMaterial.prototype, "albedoColor", void 0);
  38440. __decorate([
  38441. BABYLON.serializeAsColor3("reflectivity"),
  38442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38443. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38444. __decorate([
  38445. BABYLON.serializeAsColor3("reflection"),
  38446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38447. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38448. __decorate([
  38449. BABYLON.serializeAsColor3("emissive"),
  38450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38451. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38452. __decorate([
  38453. BABYLON.serialize(),
  38454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38455. ], PBRMaterial.prototype, "microSurface", void 0);
  38456. __decorate([
  38457. BABYLON.serialize(),
  38458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38459. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38460. __decorate([
  38461. BABYLON.serialize(),
  38462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38463. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38464. __decorate([
  38465. BABYLON.serialize(),
  38466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38467. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38468. __decorate([
  38469. BABYLON.serialize(),
  38470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38471. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38472. __decorate([
  38473. BABYLON.serialize(),
  38474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38475. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38476. __decorate([
  38477. BABYLON.serialize(),
  38478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38479. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38480. __decorate([
  38481. BABYLON.serialize(),
  38482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38483. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38484. __decorate([
  38485. BABYLON.serialize(),
  38486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38487. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38488. __decorate([
  38489. BABYLON.serialize(),
  38490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38491. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38492. __decorate([
  38493. BABYLON.serialize(),
  38494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38495. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38496. __decorate([
  38497. BABYLON.serialize(),
  38498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38499. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38500. __decorate([
  38501. BABYLON.serialize(),
  38502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38503. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38504. __decorate([
  38505. BABYLON.serialize(),
  38506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38507. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38508. __decorate([
  38509. BABYLON.serialize(),
  38510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38511. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38512. __decorate([
  38513. BABYLON.serialize(),
  38514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38515. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38516. __decorate([
  38517. BABYLON.serialize(),
  38518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38519. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38520. __decorate([
  38521. BABYLON.serialize(),
  38522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38523. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38524. __decorate([
  38525. BABYLON.serialize(),
  38526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38527. ], PBRMaterial.prototype, "useParallax", void 0);
  38528. __decorate([
  38529. BABYLON.serialize(),
  38530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38531. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38532. __decorate([
  38533. BABYLON.serialize(),
  38534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38535. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38536. __decorate([
  38537. BABYLON.serialize(),
  38538. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38539. ], PBRMaterial.prototype, "disableLighting", void 0);
  38540. __decorate([
  38541. BABYLON.serialize(),
  38542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38543. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38544. __decorate([
  38545. BABYLON.serialize(),
  38546. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38547. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38548. __decorate([
  38549. BABYLON.serialize(),
  38550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38551. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38552. __decorate([
  38553. BABYLON.serialize(),
  38554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38555. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38556. __decorate([
  38557. BABYLON.serialize(),
  38558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38559. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38560. __decorate([
  38561. BABYLON.serialize(),
  38562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38563. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  38564. __decorate([
  38565. BABYLON.serialize(),
  38566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38567. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38568. __decorate([
  38569. BABYLON.serializeAsTexture(),
  38570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38571. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38572. __decorate([
  38573. BABYLON.serialize(),
  38574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38575. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38576. return PBRMaterial;
  38577. }(BABYLON.PBRBaseMaterial));
  38578. BABYLON.PBRMaterial = PBRMaterial;
  38579. })(BABYLON || (BABYLON = {}));
  38580. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38581. var BABYLON;
  38582. (function (BABYLON) {
  38583. /**
  38584. * The PBR material of BJS following the metal roughness convention.
  38585. *
  38586. * This fits to the PBR convention in the GLTF definition:
  38587. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38588. */
  38589. var PBRMetallicRoughnessMaterial = (function (_super) {
  38590. __extends(PBRMetallicRoughnessMaterial, _super);
  38591. /**
  38592. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38593. *
  38594. * @param name The material name
  38595. * @param scene The scene the material will be use in.
  38596. */
  38597. function PBRMetallicRoughnessMaterial(name, scene) {
  38598. var _this = _super.call(this, name, scene) || this;
  38599. _this._useRoughnessFromMetallicTextureAlpha = false;
  38600. _this._useRoughnessFromMetallicTextureGreen = true;
  38601. _this._useMetallnessFromMetallicTextureBlue = true;
  38602. return _this;
  38603. }
  38604. /**
  38605. * Return the currrent class name of the material.
  38606. */
  38607. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38608. return "PBRMetallicRoughnessMaterial";
  38609. };
  38610. /**
  38611. * Return the active textures of the material.
  38612. */
  38613. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38614. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38615. if (this.baseTexture) {
  38616. activeTextures.push(this.baseTexture);
  38617. }
  38618. if (this.metallicRoughnessTexture) {
  38619. activeTextures.push(this.metallicRoughnessTexture);
  38620. }
  38621. return activeTextures;
  38622. };
  38623. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38624. if (_super.prototype.hasTexture.call(this, texture)) {
  38625. return true;
  38626. }
  38627. if (this.baseTexture === texture) {
  38628. return true;
  38629. }
  38630. if (this.metallicRoughnessTexture === texture) {
  38631. return true;
  38632. }
  38633. return false;
  38634. };
  38635. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38636. var _this = this;
  38637. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38638. };
  38639. /**
  38640. * Serialize the material to a parsable JSON object.
  38641. */
  38642. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38643. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38644. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38645. return serializationObject;
  38646. };
  38647. /**
  38648. * Parses a JSON object correponding to the serialize function.
  38649. */
  38650. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38651. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38652. };
  38653. __decorate([
  38654. BABYLON.serializeAsColor3(),
  38655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38656. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38657. __decorate([
  38658. BABYLON.serializeAsTexture(),
  38659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38660. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38661. __decorate([
  38662. BABYLON.serialize(),
  38663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38664. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38665. __decorate([
  38666. BABYLON.serialize(),
  38667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38668. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38669. __decorate([
  38670. BABYLON.serializeAsTexture(),
  38671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38672. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38673. return PBRMetallicRoughnessMaterial;
  38674. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38675. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38676. })(BABYLON || (BABYLON = {}));
  38677. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38678. var BABYLON;
  38679. (function (BABYLON) {
  38680. /**
  38681. * The PBR material of BJS following the specular glossiness convention.
  38682. *
  38683. * This fits to the PBR convention in the GLTF definition:
  38684. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38685. */
  38686. var PBRSpecularGlossinessMaterial = (function (_super) {
  38687. __extends(PBRSpecularGlossinessMaterial, _super);
  38688. /**
  38689. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38690. *
  38691. * @param name The material name
  38692. * @param scene The scene the material will be use in.
  38693. */
  38694. function PBRSpecularGlossinessMaterial(name, scene) {
  38695. var _this = _super.call(this, name, scene) || this;
  38696. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38697. return _this;
  38698. }
  38699. /**
  38700. * Return the currrent class name of the material.
  38701. */
  38702. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38703. return "PBRSpecularGlossinessMaterial";
  38704. };
  38705. /**
  38706. * Return the active textures of the material.
  38707. */
  38708. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38709. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38710. if (this.diffuseTexture) {
  38711. activeTextures.push(this.diffuseTexture);
  38712. }
  38713. if (this.specularGlossinessTexture) {
  38714. activeTextures.push(this.specularGlossinessTexture);
  38715. }
  38716. return activeTextures;
  38717. };
  38718. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38719. if (_super.prototype.hasTexture.call(this, texture)) {
  38720. return true;
  38721. }
  38722. if (this.diffuseTexture === texture) {
  38723. return true;
  38724. }
  38725. if (this.specularGlossinessTexture === texture) {
  38726. return true;
  38727. }
  38728. return false;
  38729. };
  38730. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38731. var _this = this;
  38732. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38733. };
  38734. /**
  38735. * Serialize the material to a parsable JSON object.
  38736. */
  38737. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38738. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38739. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38740. return serializationObject;
  38741. };
  38742. /**
  38743. * Parses a JSON object correponding to the serialize function.
  38744. */
  38745. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38746. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38747. };
  38748. __decorate([
  38749. BABYLON.serializeAsColor3("diffuse"),
  38750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38751. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38752. __decorate([
  38753. BABYLON.serializeAsTexture(),
  38754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38755. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38756. __decorate([
  38757. BABYLON.serializeAsColor3("specular"),
  38758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38759. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38760. __decorate([
  38761. BABYLON.serialize(),
  38762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38763. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38764. __decorate([
  38765. BABYLON.serializeAsTexture(),
  38766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38767. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38768. return PBRSpecularGlossinessMaterial;
  38769. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38770. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38771. })(BABYLON || (BABYLON = {}));
  38772. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38773. var BABYLON;
  38774. (function (BABYLON) {
  38775. var ShaderMaterial = (function (_super) {
  38776. __extends(ShaderMaterial, _super);
  38777. function ShaderMaterial(name, scene, shaderPath, options) {
  38778. var _this = _super.call(this, name, scene) || this;
  38779. _this._textures = {};
  38780. _this._textureArrays = {};
  38781. _this._floats = {};
  38782. _this._floatsArrays = {};
  38783. _this._colors3 = {};
  38784. _this._colors3Arrays = {};
  38785. _this._colors4 = {};
  38786. _this._vectors2 = {};
  38787. _this._vectors3 = {};
  38788. _this._vectors4 = {};
  38789. _this._matrices = {};
  38790. _this._matrices3x3 = {};
  38791. _this._matrices2x2 = {};
  38792. _this._vectors3Arrays = {};
  38793. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  38794. _this._shaderPath = shaderPath;
  38795. options.needAlphaBlending = options.needAlphaBlending || false;
  38796. options.needAlphaTesting = options.needAlphaTesting || false;
  38797. options.attributes = options.attributes || ["position", "normal", "uv"];
  38798. options.uniforms = options.uniforms || ["worldViewProjection"];
  38799. options.uniformBuffers = options.uniformBuffers || [];
  38800. options.samplers = options.samplers || [];
  38801. options.defines = options.defines || [];
  38802. _this._options = options;
  38803. return _this;
  38804. }
  38805. ShaderMaterial.prototype.getClassName = function () {
  38806. return "ShaderMaterial";
  38807. };
  38808. ShaderMaterial.prototype.needAlphaBlending = function () {
  38809. return this._options.needAlphaBlending;
  38810. };
  38811. ShaderMaterial.prototype.needAlphaTesting = function () {
  38812. return this._options.needAlphaTesting;
  38813. };
  38814. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  38815. if (this._options.uniforms.indexOf(uniformName) === -1) {
  38816. this._options.uniforms.push(uniformName);
  38817. }
  38818. };
  38819. ShaderMaterial.prototype.setTexture = function (name, texture) {
  38820. if (this._options.samplers.indexOf(name) === -1) {
  38821. this._options.samplers.push(name);
  38822. }
  38823. this._textures[name] = texture;
  38824. return this;
  38825. };
  38826. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  38827. if (this._options.samplers.indexOf(name) === -1) {
  38828. this._options.samplers.push(name);
  38829. }
  38830. this._checkUniform(name);
  38831. this._textureArrays[name] = textures;
  38832. return this;
  38833. };
  38834. ShaderMaterial.prototype.setFloat = function (name, value) {
  38835. this._checkUniform(name);
  38836. this._floats[name] = value;
  38837. return this;
  38838. };
  38839. ShaderMaterial.prototype.setFloats = function (name, value) {
  38840. this._checkUniform(name);
  38841. this._floatsArrays[name] = value;
  38842. return this;
  38843. };
  38844. ShaderMaterial.prototype.setColor3 = function (name, value) {
  38845. this._checkUniform(name);
  38846. this._colors3[name] = value;
  38847. return this;
  38848. };
  38849. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  38850. this._checkUniform(name);
  38851. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  38852. color.toArray(arr, arr.length);
  38853. return arr;
  38854. }, []);
  38855. return this;
  38856. };
  38857. ShaderMaterial.prototype.setColor4 = function (name, value) {
  38858. this._checkUniform(name);
  38859. this._colors4[name] = value;
  38860. return this;
  38861. };
  38862. ShaderMaterial.prototype.setVector2 = function (name, value) {
  38863. this._checkUniform(name);
  38864. this._vectors2[name] = value;
  38865. return this;
  38866. };
  38867. ShaderMaterial.prototype.setVector3 = function (name, value) {
  38868. this._checkUniform(name);
  38869. this._vectors3[name] = value;
  38870. return this;
  38871. };
  38872. ShaderMaterial.prototype.setVector4 = function (name, value) {
  38873. this._checkUniform(name);
  38874. this._vectors4[name] = value;
  38875. return this;
  38876. };
  38877. ShaderMaterial.prototype.setMatrix = function (name, value) {
  38878. this._checkUniform(name);
  38879. this._matrices[name] = value;
  38880. return this;
  38881. };
  38882. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  38883. this._checkUniform(name);
  38884. this._matrices3x3[name] = value;
  38885. return this;
  38886. };
  38887. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  38888. this._checkUniform(name);
  38889. this._matrices2x2[name] = value;
  38890. return this;
  38891. };
  38892. ShaderMaterial.prototype.setArray3 = function (name, value) {
  38893. this._checkUniform(name);
  38894. this._vectors3Arrays[name] = value;
  38895. return this;
  38896. };
  38897. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  38898. if (!mesh) {
  38899. return true;
  38900. }
  38901. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  38902. return false;
  38903. }
  38904. return false;
  38905. };
  38906. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  38907. var scene = this.getScene();
  38908. var engine = scene.getEngine();
  38909. if (!this.checkReadyOnEveryCall) {
  38910. if (this._renderId === scene.getRenderId()) {
  38911. if (this._checkCache(scene, mesh, useInstances)) {
  38912. return true;
  38913. }
  38914. }
  38915. }
  38916. // Instances
  38917. var defines = [];
  38918. var attribs = [];
  38919. var fallbacks = new BABYLON.EffectFallbacks();
  38920. if (useInstances) {
  38921. defines.push("#define INSTANCES");
  38922. }
  38923. for (var index = 0; index < this._options.defines.length; index++) {
  38924. defines.push(this._options.defines[index]);
  38925. }
  38926. for (var index = 0; index < this._options.attributes.length; index++) {
  38927. attribs.push(this._options.attributes[index]);
  38928. }
  38929. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38930. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38931. defines.push("#define VERTEXCOLOR");
  38932. }
  38933. // Bones
  38934. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  38935. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38936. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38937. if (mesh.numBoneInfluencers > 4) {
  38938. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38939. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38940. }
  38941. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38942. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38943. fallbacks.addCPUSkinningFallback(0, mesh);
  38944. if (this._options.uniforms.indexOf("mBones") === -1) {
  38945. this._options.uniforms.push("mBones");
  38946. }
  38947. }
  38948. else {
  38949. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38950. }
  38951. // Textures
  38952. for (var name in this._textures) {
  38953. if (!this._textures[name].isReady()) {
  38954. return false;
  38955. }
  38956. }
  38957. // Alpha test
  38958. if (engine.getAlphaTesting()) {
  38959. defines.push("#define ALPHATEST");
  38960. }
  38961. var previousEffect = this._effect;
  38962. var join = defines.join("\n");
  38963. this._effect = engine.createEffect(this._shaderPath, {
  38964. attributes: attribs,
  38965. uniformsNames: this._options.uniforms,
  38966. uniformBuffersNames: this._options.uniformBuffers,
  38967. samplers: this._options.samplers,
  38968. defines: join,
  38969. fallbacks: fallbacks,
  38970. onCompiled: this.onCompiled,
  38971. onError: this.onError
  38972. }, engine);
  38973. if (!this._effect.isReady()) {
  38974. return false;
  38975. }
  38976. if (previousEffect !== this._effect) {
  38977. scene.resetCachedMaterial();
  38978. }
  38979. this._renderId = scene.getRenderId();
  38980. return true;
  38981. };
  38982. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38983. var scene = this.getScene();
  38984. if (this._options.uniforms.indexOf("world") !== -1) {
  38985. this._effect.setMatrix("world", world);
  38986. }
  38987. if (this._options.uniforms.indexOf("worldView") !== -1) {
  38988. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  38989. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  38990. }
  38991. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  38992. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  38993. }
  38994. };
  38995. ShaderMaterial.prototype.bind = function (world, mesh) {
  38996. // Std values
  38997. this.bindOnlyWorldMatrix(world);
  38998. if (this.getScene().getCachedMaterial() !== this) {
  38999. if (this._options.uniforms.indexOf("view") !== -1) {
  39000. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39001. }
  39002. if (this._options.uniforms.indexOf("projection") !== -1) {
  39003. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39004. }
  39005. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39006. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39007. }
  39008. // Bones
  39009. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39010. var name;
  39011. // Texture
  39012. for (name in this._textures) {
  39013. this._effect.setTexture(name, this._textures[name]);
  39014. }
  39015. // Texture arrays
  39016. for (name in this._textureArrays) {
  39017. this._effect.setTextureArray(name, this._textureArrays[name]);
  39018. }
  39019. // Float
  39020. for (name in this._floats) {
  39021. this._effect.setFloat(name, this._floats[name]);
  39022. }
  39023. // Float s
  39024. for (name in this._floatsArrays) {
  39025. this._effect.setArray(name, this._floatsArrays[name]);
  39026. }
  39027. // Color3
  39028. for (name in this._colors3) {
  39029. this._effect.setColor3(name, this._colors3[name]);
  39030. }
  39031. for (name in this._colors3Arrays) {
  39032. this._effect.setArray3(name, this._colors3Arrays[name]);
  39033. }
  39034. // Color4
  39035. for (name in this._colors4) {
  39036. var color = this._colors4[name];
  39037. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39038. }
  39039. // Vector2
  39040. for (name in this._vectors2) {
  39041. this._effect.setVector2(name, this._vectors2[name]);
  39042. }
  39043. // Vector3
  39044. for (name in this._vectors3) {
  39045. this._effect.setVector3(name, this._vectors3[name]);
  39046. }
  39047. // Vector4
  39048. for (name in this._vectors4) {
  39049. this._effect.setVector4(name, this._vectors4[name]);
  39050. }
  39051. // Matrix
  39052. for (name in this._matrices) {
  39053. this._effect.setMatrix(name, this._matrices[name]);
  39054. }
  39055. // Matrix 3x3
  39056. for (name in this._matrices3x3) {
  39057. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39058. }
  39059. // Matrix 2x2
  39060. for (name in this._matrices2x2) {
  39061. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39062. }
  39063. // Vector3Array
  39064. for (name in this._vectors3Arrays) {
  39065. this._effect.setArray3(name, this._vectors3Arrays[name]);
  39066. }
  39067. }
  39068. this._afterBind(mesh);
  39069. };
  39070. ShaderMaterial.prototype.getActiveTextures = function () {
  39071. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39072. for (var name in this._textures) {
  39073. activeTextures.push(this._textures[name]);
  39074. }
  39075. for (var name in this._textureArrays) {
  39076. var array = this._textureArrays[name];
  39077. for (var index = 0; index < array.length; index++) {
  39078. activeTextures.push(array[index]);
  39079. }
  39080. }
  39081. return activeTextures;
  39082. };
  39083. ShaderMaterial.prototype.hasTexture = function (texture) {
  39084. if (_super.prototype.hasTexture.call(this, texture)) {
  39085. return true;
  39086. }
  39087. for (var name in this._textures) {
  39088. if (this._textures[name] === texture) {
  39089. return true;
  39090. }
  39091. }
  39092. for (var name in this._textureArrays) {
  39093. var array = this._textureArrays[name];
  39094. for (var index = 0; index < array.length; index++) {
  39095. if (array[index] === texture) {
  39096. return true;
  39097. }
  39098. }
  39099. }
  39100. return false;
  39101. };
  39102. ShaderMaterial.prototype.clone = function (name) {
  39103. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39104. return newShaderMaterial;
  39105. };
  39106. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39107. if (forceDisposeTextures) {
  39108. var name;
  39109. for (name in this._textures) {
  39110. this._textures[name].dispose();
  39111. }
  39112. for (name in this._textureArrays) {
  39113. var array = this._textureArrays[name];
  39114. for (var index = 0; index < array.length; index++) {
  39115. array[index].dispose();
  39116. }
  39117. }
  39118. }
  39119. this._textures = {};
  39120. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39121. };
  39122. ShaderMaterial.prototype.serialize = function () {
  39123. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39124. serializationObject.customType = "BABYLON.ShaderMaterial";
  39125. serializationObject.options = this._options;
  39126. serializationObject.shaderPath = this._shaderPath;
  39127. var name;
  39128. // Texture
  39129. serializationObject.textures = {};
  39130. for (name in this._textures) {
  39131. serializationObject.textures[name] = this._textures[name].serialize();
  39132. }
  39133. // Texture arrays
  39134. serializationObject.textureArrays = {};
  39135. for (name in this._textureArrays) {
  39136. serializationObject.textureArrays[name] = [];
  39137. var array = this._textureArrays[name];
  39138. for (var index = 0; index < array.length; index++) {
  39139. serializationObject.textureArrays[name].push(array[index].serialize());
  39140. }
  39141. }
  39142. // Float
  39143. serializationObject.floats = {};
  39144. for (name in this._floats) {
  39145. serializationObject.floats[name] = this._floats[name];
  39146. }
  39147. // Float s
  39148. serializationObject.floatArrays = {};
  39149. for (name in this._floatsArrays) {
  39150. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39151. }
  39152. // Color3
  39153. serializationObject.colors3 = {};
  39154. for (name in this._colors3) {
  39155. serializationObject.colors3[name] = this._colors3[name].asArray();
  39156. }
  39157. // Color3 array
  39158. serializationObject.colors3Arrays = {};
  39159. for (name in this._colors3Arrays) {
  39160. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  39161. }
  39162. // Color4
  39163. serializationObject.colors4 = {};
  39164. for (name in this._colors4) {
  39165. serializationObject.colors4[name] = this._colors4[name].asArray();
  39166. }
  39167. // Vector2
  39168. serializationObject.vectors2 = {};
  39169. for (name in this._vectors2) {
  39170. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  39171. }
  39172. // Vector3
  39173. serializationObject.vectors3 = {};
  39174. for (name in this._vectors3) {
  39175. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  39176. }
  39177. // Vector4
  39178. serializationObject.vectors4 = {};
  39179. for (name in this._vectors4) {
  39180. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  39181. }
  39182. // Matrix
  39183. serializationObject.matrices = {};
  39184. for (name in this._matrices) {
  39185. serializationObject.matrices[name] = this._matrices[name].asArray();
  39186. }
  39187. // Matrix 3x3
  39188. serializationObject.matrices3x3 = {};
  39189. for (name in this._matrices3x3) {
  39190. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  39191. }
  39192. // Matrix 2x2
  39193. serializationObject.matrices2x2 = {};
  39194. for (name in this._matrices2x2) {
  39195. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  39196. }
  39197. // Vector3Array
  39198. serializationObject.vectors3Arrays = {};
  39199. for (name in this._vectors3Arrays) {
  39200. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  39201. }
  39202. return serializationObject;
  39203. };
  39204. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  39205. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  39206. var name;
  39207. // Texture
  39208. for (name in source.textures) {
  39209. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  39210. }
  39211. // Texture arrays
  39212. for (name in source.textureArrays) {
  39213. var array = source.textureArrays[name];
  39214. var textureArray = new Array();
  39215. for (var index = 0; index < array.length; index++) {
  39216. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  39217. }
  39218. material.setTextureArray(name, textureArray);
  39219. }
  39220. // Float
  39221. for (name in source.floats) {
  39222. material.setFloat(name, source.floats[name]);
  39223. }
  39224. // Float s
  39225. for (name in source.floatsArrays) {
  39226. material.setFloats(name, source.floatsArrays[name]);
  39227. }
  39228. // Color3
  39229. for (name in source.colors3) {
  39230. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  39231. }
  39232. // Color3 arrays
  39233. for (name in source.colors3Arrays) {
  39234. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  39235. if (i % 3 === 0) {
  39236. arr.push([num]);
  39237. }
  39238. else {
  39239. arr[arr.length - 1].push(num);
  39240. }
  39241. return arr;
  39242. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  39243. material.setColor3Array(name, colors);
  39244. }
  39245. // Color4
  39246. for (name in source.colors4) {
  39247. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  39248. }
  39249. // Vector2
  39250. for (name in source.vectors2) {
  39251. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  39252. }
  39253. // Vector3
  39254. for (name in source.vectors3) {
  39255. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  39256. }
  39257. // Vector4
  39258. for (name in source.vectors4) {
  39259. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  39260. }
  39261. // Matrix
  39262. for (name in source.matrices) {
  39263. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  39264. }
  39265. // Matrix 3x3
  39266. for (name in source.matrices3x3) {
  39267. material.setMatrix3x3(name, source.matrices3x3[name]);
  39268. }
  39269. // Matrix 2x2
  39270. for (name in source.matrices2x2) {
  39271. material.setMatrix2x2(name, source.matrices2x2[name]);
  39272. }
  39273. // Vector3Array
  39274. for (name in source.vectors3Arrays) {
  39275. material.setArray3(name, source.vectors3Arrays[name]);
  39276. }
  39277. return material;
  39278. };
  39279. return ShaderMaterial;
  39280. }(BABYLON.Material));
  39281. BABYLON.ShaderMaterial = ShaderMaterial;
  39282. })(BABYLON || (BABYLON = {}));
  39283. //# sourceMappingURL=babylon.shaderMaterial.js.map
  39284. var BABYLON;
  39285. (function (BABYLON) {
  39286. var MeshBuilder = (function () {
  39287. function MeshBuilder() {
  39288. }
  39289. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  39290. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  39291. return BABYLON.Mesh.DOUBLESIDE;
  39292. }
  39293. if (orientation === undefined || orientation === null) {
  39294. return BABYLON.Mesh.FRONTSIDE;
  39295. }
  39296. return orientation;
  39297. };
  39298. /**
  39299. * Creates a box mesh.
  39300. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  39301. * The parameter `size` sets the size (float) of each box side (default 1).
  39302. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  39303. * 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).
  39304. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  39305. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39306. * 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).
  39307. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39309. */
  39310. MeshBuilder.CreateBox = function (name, options, scene) {
  39311. var box = new BABYLON.Mesh(name, scene);
  39312. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39313. box.sideOrientation = options.sideOrientation;
  39314. var vertexData = BABYLON.VertexData.CreateBox(options);
  39315. vertexData.applyToMesh(box, options.updatable);
  39316. return box;
  39317. };
  39318. /**
  39319. * Creates a sphere mesh.
  39320. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  39321. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  39322. * 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`).
  39323. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  39324. * 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
  39325. * 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).
  39326. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39327. * 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).
  39328. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39329. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39330. */
  39331. MeshBuilder.CreateSphere = function (name, options, scene) {
  39332. var sphere = new BABYLON.Mesh(name, scene);
  39333. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39334. sphere.sideOrientation = options.sideOrientation;
  39335. var vertexData = BABYLON.VertexData.CreateSphere(options);
  39336. vertexData.applyToMesh(sphere, options.updatable);
  39337. return sphere;
  39338. };
  39339. /**
  39340. * Creates a plane polygonal mesh. By default, this is a disc.
  39341. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  39342. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  39343. * 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.
  39344. * 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
  39345. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39346. * 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).
  39347. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39349. */
  39350. MeshBuilder.CreateDisc = function (name, options, scene) {
  39351. var disc = new BABYLON.Mesh(name, scene);
  39352. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39353. disc.sideOrientation = options.sideOrientation;
  39354. var vertexData = BABYLON.VertexData.CreateDisc(options);
  39355. vertexData.applyToMesh(disc, options.updatable);
  39356. return disc;
  39357. };
  39358. /**
  39359. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  39360. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  39361. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  39362. * 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`).
  39363. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  39364. * 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.
  39365. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39366. * 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).
  39367. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39368. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39369. */
  39370. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  39371. var sphere = new BABYLON.Mesh(name, scene);
  39372. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39373. sphere.sideOrientation = options.sideOrientation;
  39374. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  39375. vertexData.applyToMesh(sphere, options.updatable);
  39376. return sphere;
  39377. };
  39378. ;
  39379. /**
  39380. * Creates a ribbon mesh.
  39381. * 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.
  39382. *
  39383. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  39384. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  39385. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  39386. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  39387. * 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.
  39388. * 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.
  39389. * 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
  39390. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39391. * 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).
  39392. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39393. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39394. * 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.
  39395. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  39396. * 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
  39397. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  39398. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  39399. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39400. */
  39401. MeshBuilder.CreateRibbon = function (name, options, scene) {
  39402. var pathArray = options.pathArray;
  39403. var closeArray = options.closeArray;
  39404. var closePath = options.closePath;
  39405. var offset = options.offset;
  39406. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39407. var instance = options.instance;
  39408. var updatable = options.updatable;
  39409. if (instance) {
  39410. // positionFunction : ribbon case
  39411. // only pathArray and sideOrientation parameters are taken into account for positions update
  39412. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  39413. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  39414. var positionFunction = function (positions) {
  39415. var minlg = pathArray[0].length;
  39416. var i = 0;
  39417. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  39418. for (var si = 1; si <= ns; si++) {
  39419. for (var p = 0; p < pathArray.length; p++) {
  39420. var path = pathArray[p];
  39421. var l = path.length;
  39422. minlg = (minlg < l) ? minlg : l;
  39423. var j = 0;
  39424. while (j < minlg) {
  39425. positions[i] = path[j].x;
  39426. positions[i + 1] = path[j].y;
  39427. positions[i + 2] = path[j].z;
  39428. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  39429. BABYLON.Tmp.Vector3[0].x = path[j].x;
  39430. }
  39431. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  39432. BABYLON.Tmp.Vector3[1].x = path[j].x;
  39433. }
  39434. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  39435. BABYLON.Tmp.Vector3[0].y = path[j].y;
  39436. }
  39437. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  39438. BABYLON.Tmp.Vector3[1].y = path[j].y;
  39439. }
  39440. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  39441. BABYLON.Tmp.Vector3[0].z = path[j].z;
  39442. }
  39443. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  39444. BABYLON.Tmp.Vector3[1].z = path[j].z;
  39445. }
  39446. j++;
  39447. i += 3;
  39448. }
  39449. if (instance._closePath) {
  39450. positions[i] = path[0].x;
  39451. positions[i + 1] = path[0].y;
  39452. positions[i + 2] = path[0].z;
  39453. i += 3;
  39454. }
  39455. }
  39456. }
  39457. };
  39458. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39459. positionFunction(positions);
  39460. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  39461. instance._boundingInfo.update(instance._worldMatrix);
  39462. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  39463. if (options.colors) {
  39464. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39465. for (var c = 0; c < options.colors.length; c++) {
  39466. colors[c * 4] = options.colors[c].r;
  39467. colors[c * 4 + 1] = options.colors[c].g;
  39468. colors[c * 4 + 2] = options.colors[c].b;
  39469. colors[c * 4 + 3] = options.colors[c].a;
  39470. }
  39471. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  39472. }
  39473. if (options.uvs) {
  39474. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39475. for (var i = 0; i < options.uvs.length; i++) {
  39476. uvs[i * 2] = options.uvs[i].x;
  39477. uvs[i * 2 + 1] = options.uvs[i].y;
  39478. }
  39479. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  39480. }
  39481. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  39482. var indices = instance.getIndices();
  39483. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39484. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  39485. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  39486. if (instance._closePath) {
  39487. var indexFirst = 0;
  39488. var indexLast = 0;
  39489. for (var p = 0; p < pathArray.length; p++) {
  39490. indexFirst = instance._idx[p] * 3;
  39491. if (p + 1 < pathArray.length) {
  39492. indexLast = (instance._idx[p + 1] - 1) * 3;
  39493. }
  39494. else {
  39495. indexLast = normals.length - 3;
  39496. }
  39497. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  39498. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  39499. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  39500. normals[indexLast] = normals[indexFirst];
  39501. normals[indexLast + 1] = normals[indexFirst + 1];
  39502. normals[indexLast + 2] = normals[indexFirst + 2];
  39503. }
  39504. }
  39505. if (!(instance.areNormalsFrozen)) {
  39506. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  39507. }
  39508. }
  39509. return instance;
  39510. }
  39511. else {
  39512. var ribbon = new BABYLON.Mesh(name, scene);
  39513. ribbon.sideOrientation = sideOrientation;
  39514. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  39515. if (closePath) {
  39516. ribbon._idx = vertexData._idx;
  39517. }
  39518. ribbon._closePath = closePath;
  39519. ribbon._closeArray = closeArray;
  39520. vertexData.applyToMesh(ribbon, updatable);
  39521. return ribbon;
  39522. }
  39523. };
  39524. /**
  39525. * Creates a cylinder or a cone mesh.
  39526. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  39527. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  39528. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  39529. * 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.
  39530. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  39531. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  39532. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  39533. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  39534. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  39535. * 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).
  39536. * 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
  39537. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  39538. * 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
  39539. * 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.
  39540. * If `enclose` is false, a ring surface is one element.
  39541. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  39542. * 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
  39543. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39544. * 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).
  39545. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39546. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39547. */
  39548. MeshBuilder.CreateCylinder = function (name, options, scene) {
  39549. var cylinder = new BABYLON.Mesh(name, scene);
  39550. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39551. cylinder.sideOrientation = options.sideOrientation;
  39552. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  39553. vertexData.applyToMesh(cylinder, options.updatable);
  39554. return cylinder;
  39555. };
  39556. /**
  39557. * Creates a torus mesh.
  39558. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  39559. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  39560. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  39561. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  39562. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39563. * 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).
  39564. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39565. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39566. */
  39567. MeshBuilder.CreateTorus = function (name, options, scene) {
  39568. var torus = new BABYLON.Mesh(name, scene);
  39569. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39570. torus.sideOrientation = options.sideOrientation;
  39571. var vertexData = BABYLON.VertexData.CreateTorus(options);
  39572. vertexData.applyToMesh(torus, options.updatable);
  39573. return torus;
  39574. };
  39575. /**
  39576. * Creates a torus knot mesh.
  39577. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  39578. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  39579. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  39580. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  39581. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  39582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39583. * 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).
  39584. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39586. */
  39587. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  39588. var torusKnot = new BABYLON.Mesh(name, scene);
  39589. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39590. torusKnot.sideOrientation = options.sideOrientation;
  39591. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  39592. vertexData.applyToMesh(torusKnot, options.updatable);
  39593. return torusKnot;
  39594. };
  39595. /**
  39596. * Creates a line system mesh.
  39597. * A line system is a pool of many lines gathered in a single mesh.
  39598. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  39599. * 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.
  39600. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  39601. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  39602. * 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
  39603. * 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
  39604. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  39605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39606. */
  39607. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  39608. var instance = options.instance;
  39609. var lines = options.lines;
  39610. if (instance) {
  39611. var positionFunction = function (positions) {
  39612. var i = 0;
  39613. for (var l = 0; l < lines.length; l++) {
  39614. var points = lines[l];
  39615. for (var p = 0; p < points.length; p++) {
  39616. positions[i] = points[p].x;
  39617. positions[i + 1] = points[p].y;
  39618. positions[i + 2] = points[p].z;
  39619. i += 3;
  39620. }
  39621. }
  39622. };
  39623. instance.updateMeshPositions(positionFunction, false);
  39624. return instance;
  39625. }
  39626. // line system creation
  39627. var lineSystem = new BABYLON.LinesMesh(name, scene);
  39628. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  39629. vertexData.applyToMesh(lineSystem, options.updatable);
  39630. return lineSystem;
  39631. };
  39632. /**
  39633. * Creates a line mesh.
  39634. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  39635. * 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.
  39636. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39637. * The parameter `points` is an array successive Vector3.
  39638. * 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
  39639. * When updating an instance, remember that only point positions can change, not the number of points.
  39640. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39641. */
  39642. MeshBuilder.CreateLines = function (name, options, scene) {
  39643. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  39644. return lines;
  39645. };
  39646. /**
  39647. * Creates a dashed line mesh.
  39648. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  39649. * 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.
  39650. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39651. * The parameter `points` is an array successive Vector3.
  39652. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  39653. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  39654. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  39655. * 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
  39656. * When updating an instance, remember that only point positions can change, not the number of points.
  39657. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39658. */
  39659. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  39660. var points = options.points;
  39661. var instance = options.instance;
  39662. var gapSize = options.gapSize;
  39663. var dashNb = options.dashNb;
  39664. var dashSize = options.dashSize;
  39665. if (instance) {
  39666. var positionFunction = function (positions) {
  39667. var curvect = BABYLON.Vector3.Zero();
  39668. var nbSeg = positions.length / 6;
  39669. var lg = 0;
  39670. var nb = 0;
  39671. var shft = 0;
  39672. var dashshft = 0;
  39673. var curshft = 0;
  39674. var p = 0;
  39675. var i = 0;
  39676. var j = 0;
  39677. for (i = 0; i < points.length - 1; i++) {
  39678. points[i + 1].subtractToRef(points[i], curvect);
  39679. lg += curvect.length();
  39680. }
  39681. shft = lg / nbSeg;
  39682. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  39683. for (i = 0; i < points.length - 1; i++) {
  39684. points[i + 1].subtractToRef(points[i], curvect);
  39685. nb = Math.floor(curvect.length() / shft);
  39686. curvect.normalize();
  39687. j = 0;
  39688. while (j < nb && p < positions.length) {
  39689. curshft = shft * j;
  39690. positions[p] = points[i].x + curshft * curvect.x;
  39691. positions[p + 1] = points[i].y + curshft * curvect.y;
  39692. positions[p + 2] = points[i].z + curshft * curvect.z;
  39693. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  39694. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  39695. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  39696. p += 6;
  39697. j++;
  39698. }
  39699. }
  39700. while (p < positions.length) {
  39701. positions[p] = points[i].x;
  39702. positions[p + 1] = points[i].y;
  39703. positions[p + 2] = points[i].z;
  39704. p += 3;
  39705. }
  39706. };
  39707. instance.updateMeshPositions(positionFunction, false);
  39708. return instance;
  39709. }
  39710. // dashed lines creation
  39711. var dashedLines = new BABYLON.LinesMesh(name, scene);
  39712. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  39713. vertexData.applyToMesh(dashedLines, options.updatable);
  39714. dashedLines.dashSize = dashSize;
  39715. dashedLines.gapSize = gapSize;
  39716. return dashedLines;
  39717. };
  39718. /**
  39719. * Creates an extruded shape mesh.
  39720. * 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.
  39721. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  39722. *
  39723. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39724. * 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
  39725. * extruded along the Z axis.
  39726. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39727. * 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.
  39728. * The parameter `scale` (float, default 1) is the value to scale the shape.
  39729. * 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
  39730. * 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
  39731. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39732. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39733. * 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).
  39734. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39735. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39736. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39737. */
  39738. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  39739. var path = options.path;
  39740. var shape = options.shape;
  39741. var scale = options.scale || 1;
  39742. var rotation = options.rotation || 0;
  39743. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39744. var updatable = options.updatable;
  39745. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39746. var instance = options.instance;
  39747. var invertUV = options.invertUV || false;
  39748. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  39749. };
  39750. /**
  39751. * Creates an custom extruded shape mesh.
  39752. * 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.
  39753. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  39754. *
  39755. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39756. * 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
  39757. * extruded along the Z axis.
  39758. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39759. * 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
  39760. * and the distance of this point from the begining of the path :
  39761. * ```javascript
  39762. * var rotationFunction = function(i, distance) {
  39763. * // do things
  39764. * return rotationValue; }
  39765. * ```
  39766. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  39767. * 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
  39768. * and the distance of this point from the begining of the path :
  39769. * ```javascript
  39770. * var scaleFunction = function(i, distance) {
  39771. * // do things
  39772. * return scaleValue;}
  39773. * ```
  39774. * It must returns a float value that will be the scale value applied to the shape on each path point.
  39775. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  39776. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  39777. * 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
  39778. * 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
  39779. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  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 mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39785. */
  39786. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  39787. var path = options.path;
  39788. var shape = options.shape;
  39789. var scaleFunction = options.scaleFunction || (function () { return 1; });
  39790. var rotationFunction = options.rotationFunction || (function () { return 0; });
  39791. var ribbonCloseArray = options.ribbonCloseArray || false;
  39792. var ribbonClosePath = options.ribbonClosePath || false;
  39793. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39794. var updatable = options.updatable;
  39795. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39796. var instance = options.instance;
  39797. var invertUV = options.invertUV || false;
  39798. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  39799. };
  39800. /**
  39801. * Creates lathe mesh.
  39802. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  39803. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  39804. *
  39805. * 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
  39806. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  39807. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  39808. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  39809. * 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.
  39810. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  39811. * 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
  39812. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39813. * 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).
  39814. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39815. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39816. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39817. */
  39818. MeshBuilder.CreateLathe = function (name, options, scene) {
  39819. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  39820. var closed = (options.closed === undefined) ? true : options.closed;
  39821. var shape = options.shape;
  39822. var radius = options.radius || 1;
  39823. var tessellation = options.tessellation || 64;
  39824. var updatable = options.updatable;
  39825. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39826. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39827. var pi2 = Math.PI * 2;
  39828. var paths = new Array();
  39829. var invertUV = options.invertUV || false;
  39830. var i = 0;
  39831. var p = 0;
  39832. var step = pi2 / tessellation * arc;
  39833. var rotated;
  39834. var path = new Array();
  39835. ;
  39836. for (i = 0; i <= tessellation; i++) {
  39837. var path = [];
  39838. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  39839. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  39840. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  39841. }
  39842. for (p = 0; p < shape.length; p++) {
  39843. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  39844. path.push(rotated);
  39845. }
  39846. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  39847. 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));
  39848. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  39849. }
  39850. paths.push(path);
  39851. }
  39852. // lathe ribbon
  39853. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  39854. return lathe;
  39855. };
  39856. /**
  39857. * Creates a plane mesh.
  39858. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39859. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  39860. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  39861. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  39862. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39863. * 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).
  39864. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39865. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39866. */
  39867. MeshBuilder.CreatePlane = function (name, options, scene) {
  39868. var plane = new BABYLON.Mesh(name, scene);
  39869. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39870. plane.sideOrientation = options.sideOrientation;
  39871. var vertexData = BABYLON.VertexData.CreatePlane(options);
  39872. vertexData.applyToMesh(plane, options.updatable);
  39873. if (options.sourcePlane) {
  39874. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  39875. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  39876. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  39877. plane.rotate(vectorProduct, product);
  39878. }
  39879. return plane;
  39880. };
  39881. /**
  39882. * Creates a ground mesh.
  39883. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39884. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  39885. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  39886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39887. */
  39888. MeshBuilder.CreateGround = function (name, options, scene) {
  39889. var ground = new BABYLON.GroundMesh(name, scene);
  39890. ground._setReady(false);
  39891. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39892. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39893. ground._width = options.width || 1;
  39894. ground._height = options.height || 1;
  39895. ground._maxX = ground._width / 2;
  39896. ground._maxZ = ground._height / 2;
  39897. ground._minX = -ground._maxX;
  39898. ground._minZ = -ground._maxZ;
  39899. var vertexData = BABYLON.VertexData.CreateGround(options);
  39900. vertexData.applyToMesh(ground, options.updatable);
  39901. ground._setReady(true);
  39902. return ground;
  39903. };
  39904. /**
  39905. * Creates a tiled ground mesh.
  39906. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  39907. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  39908. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  39909. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  39910. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  39911. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  39912. * numbers of subdivisions on the ground width and height of each tile.
  39913. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39914. */
  39915. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  39916. var tiledGround = new BABYLON.Mesh(name, scene);
  39917. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  39918. vertexData.applyToMesh(tiledGround, options.updatable);
  39919. return tiledGround;
  39920. };
  39921. /**
  39922. * Creates a ground mesh from a height map.
  39923. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  39924. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  39925. * The parameter `url` sets the URL of the height map image resource.
  39926. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  39927. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  39928. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  39929. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  39930. * 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.
  39931. * 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).
  39932. * This function is passed the newly built mesh :
  39933. * ```javascript
  39934. * function(mesh) { // do things
  39935. * return; }
  39936. * ```
  39937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39938. */
  39939. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  39940. var width = options.width || 10.0;
  39941. var height = options.height || 10.0;
  39942. var subdivisions = options.subdivisions || 1 | 0;
  39943. var minHeight = options.minHeight || 0.0;
  39944. var maxHeight = options.maxHeight || 10.0;
  39945. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39946. var updatable = options.updatable;
  39947. var onReady = options.onReady;
  39948. var ground = new BABYLON.GroundMesh(name, scene);
  39949. ground._subdivisionsX = subdivisions;
  39950. ground._subdivisionsY = subdivisions;
  39951. ground._width = width;
  39952. ground._height = height;
  39953. ground._maxX = ground._width / 2.0;
  39954. ground._maxZ = ground._height / 2.0;
  39955. ground._minX = -ground._maxX;
  39956. ground._minZ = -ground._maxZ;
  39957. ground._setReady(false);
  39958. var onload = function (img) {
  39959. // Getting height map data
  39960. var canvas = document.createElement("canvas");
  39961. var context = canvas.getContext("2d");
  39962. var bufferWidth = img.width;
  39963. var bufferHeight = img.height;
  39964. canvas.width = bufferWidth;
  39965. canvas.height = bufferHeight;
  39966. context.drawImage(img, 0, 0);
  39967. // Create VertexData from map data
  39968. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  39969. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  39970. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  39971. width: width, height: height,
  39972. subdivisions: subdivisions,
  39973. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  39974. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  39975. });
  39976. vertexData.applyToMesh(ground, updatable);
  39977. ground._setReady(true);
  39978. //execute ready callback, if set
  39979. if (onReady) {
  39980. onReady(ground);
  39981. }
  39982. };
  39983. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  39984. return ground;
  39985. };
  39986. /**
  39987. * Creates a polygon mesh.
  39988. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  39989. * 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.
  39990. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39991. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39992. * 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).
  39993. * Remember you can only change the shape positions, not their number when updating a polygon.
  39994. */
  39995. MeshBuilder.CreatePolygon = function (name, options, scene) {
  39996. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39997. var shape = options.shape;
  39998. var holes = options.holes || [];
  39999. var depth = options.depth || 0;
  40000. var contours = [];
  40001. var hole = [];
  40002. for (var i = 0; i < shape.length; i++) {
  40003. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  40004. }
  40005. var epsilon = 0.00000001;
  40006. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  40007. contours.pop();
  40008. }
  40009. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  40010. for (var hNb = 0; hNb < holes.length; hNb++) {
  40011. hole = [];
  40012. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  40013. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  40014. }
  40015. polygonTriangulation.addHole(hole);
  40016. }
  40017. var polygon = polygonTriangulation.build(options.updatable, depth);
  40018. polygon.sideOrientation = options.sideOrientation;
  40019. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  40020. vertexData.applyToMesh(polygon, options.updatable);
  40021. return polygon;
  40022. };
  40023. ;
  40024. /**
  40025. * Creates an extruded polygon mesh, with depth in the Y direction.
  40026. * 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).
  40027. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40028. */
  40029. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  40030. return MeshBuilder.CreatePolygon(name, options, scene);
  40031. };
  40032. ;
  40033. /**
  40034. * Creates a tube mesh.
  40035. * 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.
  40036. *
  40037. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  40038. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  40039. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  40040. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  40041. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  40042. * 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.
  40043. * It must return a radius value (positive float) :
  40044. * ```javascript
  40045. * var radiusFunction = function(i, distance) {
  40046. * // do things
  40047. * return radius; }
  40048. * ```
  40049. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  40050. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  40051. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  40052. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40053. * 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).
  40054. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40055. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40056. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40057. */
  40058. MeshBuilder.CreateTube = function (name, options, scene) {
  40059. var path = options.path;
  40060. var radius = options.radius || 1.0;
  40061. var tessellation = options.tessellation || 64 | 0;
  40062. var radiusFunction = options.radiusFunction;
  40063. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40064. var invertUV = options.invertUV || false;
  40065. var updatable = options.updatable;
  40066. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40067. var instance = options.instance;
  40068. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  40069. // tube geometry
  40070. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  40071. var tangents = path3D.getTangents();
  40072. var normals = path3D.getNormals();
  40073. var distances = path3D.getDistances();
  40074. var pi2 = Math.PI * 2;
  40075. var step = pi2 / tessellation * arc;
  40076. var returnRadius = function () { return radius; };
  40077. var radiusFunctionFinal = radiusFunction || returnRadius;
  40078. var circlePath;
  40079. var rad;
  40080. var normal;
  40081. var rotated;
  40082. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40083. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40084. for (var i = 0; i < path.length; i++) {
  40085. rad = radiusFunctionFinal(i, distances[i]); // current radius
  40086. circlePath = Array(); // current circle array
  40087. normal = normals[i]; // current normal
  40088. for (var t = 0; t < tessellation; t++) {
  40089. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  40090. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  40091. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  40092. rotated.scaleInPlace(rad).addInPlace(path[i]);
  40093. circlePath[t] = rotated;
  40094. }
  40095. circlePaths[index] = circlePath;
  40096. index++;
  40097. }
  40098. // cap
  40099. var capPath = function (nbPoints, pathIndex) {
  40100. var pointCap = Array();
  40101. for (var i = 0; i < nbPoints; i++) {
  40102. pointCap.push(path[pathIndex]);
  40103. }
  40104. return pointCap;
  40105. };
  40106. switch (cap) {
  40107. case BABYLON.Mesh.NO_CAP:
  40108. break;
  40109. case BABYLON.Mesh.CAP_START:
  40110. circlePaths[0] = capPath(tessellation, 0);
  40111. circlePaths[1] = circlePaths[2].slice(0);
  40112. break;
  40113. case BABYLON.Mesh.CAP_END:
  40114. circlePaths[index] = circlePaths[index - 1].slice(0);
  40115. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40116. break;
  40117. case BABYLON.Mesh.CAP_ALL:
  40118. circlePaths[0] = capPath(tessellation, 0);
  40119. circlePaths[1] = circlePaths[2].slice(0);
  40120. circlePaths[index] = circlePaths[index - 1].slice(0);
  40121. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40122. break;
  40123. default:
  40124. break;
  40125. }
  40126. return circlePaths;
  40127. };
  40128. var path3D;
  40129. var pathArray;
  40130. if (instance) {
  40131. var arc = options.arc || instance.arc;
  40132. path3D = (instance.path3D).update(path);
  40133. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  40134. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  40135. instance.path3D = path3D;
  40136. instance.pathArray = pathArray;
  40137. instance.arc = arc;
  40138. return instance;
  40139. }
  40140. // tube creation
  40141. path3D = new BABYLON.Path3D(path);
  40142. var newPathArray = new Array();
  40143. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40144. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  40145. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40146. tube.pathArray = pathArray;
  40147. tube.path3D = path3D;
  40148. tube.tessellation = tessellation;
  40149. tube.cap = cap;
  40150. tube.arc = options.arc;
  40151. return tube;
  40152. };
  40153. /**
  40154. * Creates a polyhedron mesh.
  40155. *
  40156. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  40157. * 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
  40158. * to choose the wanted type.
  40159. * The parameter `size` (positive float, default 1) sets the polygon size.
  40160. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  40161. * 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`.
  40162. * 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
  40163. * 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)`).
  40164. * 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
  40165. * 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.
  40166. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40167. * 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).
  40168. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40170. */
  40171. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  40172. var polyhedron = new BABYLON.Mesh(name, scene);
  40173. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40174. polyhedron.sideOrientation = options.sideOrientation;
  40175. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  40176. vertexData.applyToMesh(polyhedron, options.updatable);
  40177. return polyhedron;
  40178. };
  40179. /**
  40180. * Creates a decal mesh.
  40181. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  40182. * 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.
  40183. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  40184. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  40185. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  40186. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  40187. */
  40188. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  40189. var indices = sourceMesh.getIndices();
  40190. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40191. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40192. var position = options.position || BABYLON.Vector3.Zero();
  40193. var normal = options.normal || BABYLON.Vector3.Up();
  40194. var size = options.size || BABYLON.Vector3.One();
  40195. var angle = options.angle || 0;
  40196. // Getting correct rotation
  40197. if (!normal) {
  40198. var target = new BABYLON.Vector3(0, 0, 1);
  40199. var camera = sourceMesh.getScene().activeCamera;
  40200. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  40201. normal = camera.globalPosition.subtract(cameraWorldTarget);
  40202. }
  40203. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  40204. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  40205. var pitch = Math.atan2(normal.y, len);
  40206. // Matrix
  40207. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  40208. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  40209. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  40210. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  40211. var vertexData = new BABYLON.VertexData();
  40212. vertexData.indices = [];
  40213. vertexData.positions = [];
  40214. vertexData.normals = [];
  40215. vertexData.uvs = [];
  40216. var currentVertexDataIndex = 0;
  40217. var extractDecalVector3 = function (indexId) {
  40218. var vertexId = indices[indexId];
  40219. var result = new BABYLON.PositionNormalVertex();
  40220. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  40221. // Send vector to decal local world
  40222. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  40223. // Get normal
  40224. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  40225. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  40226. return result;
  40227. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  40228. var clip = function (vertices, axis) {
  40229. if (vertices.length === 0) {
  40230. return vertices;
  40231. }
  40232. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  40233. var clipVertices = function (v0, v1) {
  40234. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  40235. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  40236. };
  40237. var result = new Array();
  40238. for (var index = 0; index < vertices.length; index += 3) {
  40239. var v1Out;
  40240. var v2Out;
  40241. var v3Out;
  40242. var total = 0;
  40243. var nV1, nV2, nV3, nV4;
  40244. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  40245. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  40246. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  40247. v1Out = d1 > 0;
  40248. v2Out = d2 > 0;
  40249. v3Out = d3 > 0;
  40250. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  40251. switch (total) {
  40252. case 0:
  40253. result.push(vertices[index]);
  40254. result.push(vertices[index + 1]);
  40255. result.push(vertices[index + 2]);
  40256. break;
  40257. case 1:
  40258. if (v1Out) {
  40259. nV1 = vertices[index + 1];
  40260. nV2 = vertices[index + 2];
  40261. nV3 = clipVertices(vertices[index], nV1);
  40262. nV4 = clipVertices(vertices[index], nV2);
  40263. }
  40264. if (v2Out) {
  40265. nV1 = vertices[index];
  40266. nV2 = vertices[index + 2];
  40267. nV3 = clipVertices(vertices[index + 1], nV1);
  40268. nV4 = clipVertices(vertices[index + 1], nV2);
  40269. result.push(nV3);
  40270. result.push(nV2.clone());
  40271. result.push(nV1.clone());
  40272. result.push(nV2.clone());
  40273. result.push(nV3.clone());
  40274. result.push(nV4);
  40275. break;
  40276. }
  40277. if (v3Out) {
  40278. nV1 = vertices[index];
  40279. nV2 = vertices[index + 1];
  40280. nV3 = clipVertices(vertices[index + 2], nV1);
  40281. nV4 = clipVertices(vertices[index + 2], nV2);
  40282. }
  40283. result.push(nV1.clone());
  40284. result.push(nV2.clone());
  40285. result.push(nV3);
  40286. result.push(nV4);
  40287. result.push(nV3.clone());
  40288. result.push(nV2.clone());
  40289. break;
  40290. case 2:
  40291. if (!v1Out) {
  40292. nV1 = vertices[index].clone();
  40293. nV2 = clipVertices(nV1, vertices[index + 1]);
  40294. nV3 = clipVertices(nV1, vertices[index + 2]);
  40295. result.push(nV1);
  40296. result.push(nV2);
  40297. result.push(nV3);
  40298. }
  40299. if (!v2Out) {
  40300. nV1 = vertices[index + 1].clone();
  40301. nV2 = clipVertices(nV1, vertices[index + 2]);
  40302. nV3 = clipVertices(nV1, vertices[index]);
  40303. result.push(nV1);
  40304. result.push(nV2);
  40305. result.push(nV3);
  40306. }
  40307. if (!v3Out) {
  40308. nV1 = vertices[index + 2].clone();
  40309. nV2 = clipVertices(nV1, vertices[index]);
  40310. nV3 = clipVertices(nV1, vertices[index + 1]);
  40311. result.push(nV1);
  40312. result.push(nV2);
  40313. result.push(nV3);
  40314. }
  40315. break;
  40316. case 3:
  40317. break;
  40318. }
  40319. }
  40320. return result;
  40321. };
  40322. for (var index = 0; index < indices.length; index += 3) {
  40323. var faceVertices = new Array();
  40324. faceVertices.push(extractDecalVector3(index));
  40325. faceVertices.push(extractDecalVector3(index + 1));
  40326. faceVertices.push(extractDecalVector3(index + 2));
  40327. // Clip
  40328. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  40329. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  40330. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  40331. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  40332. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  40333. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  40334. if (faceVertices.length === 0) {
  40335. continue;
  40336. }
  40337. // Add UVs and get back to world
  40338. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  40339. var vertex = faceVertices[vIndex];
  40340. //TODO check for Int32Array | Uint32Array | Uint16Array
  40341. vertexData.indices.push(currentVertexDataIndex);
  40342. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  40343. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  40344. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  40345. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  40346. currentVertexDataIndex++;
  40347. }
  40348. }
  40349. // Return mesh
  40350. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  40351. vertexData.applyToMesh(decal);
  40352. decal.position = position.clone();
  40353. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  40354. return decal;
  40355. };
  40356. // Privates
  40357. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  40358. // extrusion geometry
  40359. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  40360. var tangents = path3D.getTangents();
  40361. var normals = path3D.getNormals();
  40362. var binormals = path3D.getBinormals();
  40363. var distances = path3D.getDistances();
  40364. var angle = 0;
  40365. var returnScale = function () { return scale; };
  40366. var returnRotation = function () { return rotation; };
  40367. var rotate = custom ? rotateFunction : returnRotation;
  40368. var scl = custom ? scaleFunction : returnScale;
  40369. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40370. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40371. for (var i = 0; i < curve.length; i++) {
  40372. var shapePath = new Array();
  40373. var angleStep = rotate(i, distances[i]);
  40374. var scaleRatio = scl(i, distances[i]);
  40375. for (var p = 0; p < shape.length; p++) {
  40376. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  40377. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  40378. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  40379. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  40380. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  40381. shapePath[p] = rotated;
  40382. }
  40383. shapePaths[index] = shapePath;
  40384. angle += angleStep;
  40385. index++;
  40386. }
  40387. // cap
  40388. var capPath = function (shapePath) {
  40389. var pointCap = Array();
  40390. var barycenter = BABYLON.Vector3.Zero();
  40391. var i;
  40392. for (i = 0; i < shapePath.length; i++) {
  40393. barycenter.addInPlace(shapePath[i]);
  40394. }
  40395. barycenter.scaleInPlace(1.0 / shapePath.length);
  40396. for (i = 0; i < shapePath.length; i++) {
  40397. pointCap.push(barycenter);
  40398. }
  40399. return pointCap;
  40400. };
  40401. switch (cap) {
  40402. case BABYLON.Mesh.NO_CAP:
  40403. break;
  40404. case BABYLON.Mesh.CAP_START:
  40405. shapePaths[0] = capPath(shapePaths[2]);
  40406. shapePaths[1] = shapePaths[2];
  40407. break;
  40408. case BABYLON.Mesh.CAP_END:
  40409. shapePaths[index] = shapePaths[index - 1];
  40410. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40411. break;
  40412. case BABYLON.Mesh.CAP_ALL:
  40413. shapePaths[0] = capPath(shapePaths[2]);
  40414. shapePaths[1] = shapePaths[2];
  40415. shapePaths[index] = shapePaths[index - 1];
  40416. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40417. break;
  40418. default:
  40419. break;
  40420. }
  40421. return shapePaths;
  40422. };
  40423. var path3D;
  40424. var pathArray;
  40425. if (instance) {
  40426. path3D = (instance.path3D).update(curve);
  40427. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  40428. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  40429. return instance;
  40430. }
  40431. // extruded shape creation
  40432. path3D = new BABYLON.Path3D(curve);
  40433. var newShapePaths = new Array();
  40434. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40435. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  40436. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  40437. extrudedGeneric.pathArray = pathArray;
  40438. extrudedGeneric.path3D = path3D;
  40439. extrudedGeneric.cap = cap;
  40440. return extrudedGeneric;
  40441. };
  40442. return MeshBuilder;
  40443. }());
  40444. BABYLON.MeshBuilder = MeshBuilder;
  40445. })(BABYLON || (BABYLON = {}));
  40446. //# sourceMappingURL=babylon.meshBuilder.js.map
  40447. var BABYLON;
  40448. (function (BABYLON) {
  40449. var Layer = (function () {
  40450. function Layer(name, imgUrl, scene, isBackground, color) {
  40451. this.name = name;
  40452. this.scale = new BABYLON.Vector2(1, 1);
  40453. this.offset = new BABYLON.Vector2(0, 0);
  40454. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  40455. this.layerMask = 0x0FFFFFFF;
  40456. this._vertexBuffers = {};
  40457. // Events
  40458. /**
  40459. * An event triggered when the layer is disposed.
  40460. * @type {BABYLON.Observable}
  40461. */
  40462. this.onDisposeObservable = new BABYLON.Observable();
  40463. /**
  40464. * An event triggered before rendering the scene
  40465. * @type {BABYLON.Observable}
  40466. */
  40467. this.onBeforeRenderObservable = new BABYLON.Observable();
  40468. /**
  40469. * An event triggered after rendering the scene
  40470. * @type {BABYLON.Observable}
  40471. */
  40472. this.onAfterRenderObservable = new BABYLON.Observable();
  40473. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  40474. this.isBackground = isBackground === undefined ? true : isBackground;
  40475. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  40476. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40477. this._scene.layers.push(this);
  40478. var engine = this._scene.getEngine();
  40479. this._rebuild();
  40480. // Effects
  40481. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  40482. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  40483. }
  40484. Object.defineProperty(Layer.prototype, "onDispose", {
  40485. set: function (callback) {
  40486. if (this._onDisposeObserver) {
  40487. this.onDisposeObservable.remove(this._onDisposeObserver);
  40488. }
  40489. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40490. },
  40491. enumerable: true,
  40492. configurable: true
  40493. });
  40494. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  40495. set: function (callback) {
  40496. if (this._onBeforeRenderObserver) {
  40497. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40498. }
  40499. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40500. },
  40501. enumerable: true,
  40502. configurable: true
  40503. });
  40504. Object.defineProperty(Layer.prototype, "onAfterRender", {
  40505. set: function (callback) {
  40506. if (this._onAfterRenderObserver) {
  40507. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40508. }
  40509. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40510. },
  40511. enumerable: true,
  40512. configurable: true
  40513. });
  40514. Layer.prototype._rebuild = function () {
  40515. var engine = this._scene.getEngine();
  40516. // VBO
  40517. var vertices = [];
  40518. vertices.push(1, 1);
  40519. vertices.push(-1, 1);
  40520. vertices.push(-1, -1);
  40521. vertices.push(1, -1);
  40522. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40523. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  40524. // Indices
  40525. var indices = [];
  40526. indices.push(0);
  40527. indices.push(1);
  40528. indices.push(2);
  40529. indices.push(0);
  40530. indices.push(2);
  40531. indices.push(3);
  40532. this._indexBuffer = engine.createIndexBuffer(indices);
  40533. };
  40534. Layer.prototype.render = function () {
  40535. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  40536. // Check
  40537. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  40538. return;
  40539. var engine = this._scene.getEngine();
  40540. this.onBeforeRenderObservable.notifyObservers(this);
  40541. // Render
  40542. engine.enableEffect(currentEffect);
  40543. engine.setState(false);
  40544. // Texture
  40545. currentEffect.setTexture("textureSampler", this.texture);
  40546. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  40547. // Color
  40548. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  40549. // Scale / offset
  40550. currentEffect.setVector2("offset", this.offset);
  40551. currentEffect.setVector2("scale", this.scale);
  40552. // VBOs
  40553. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  40554. // Draw order
  40555. if (!this.alphaTest) {
  40556. engine.setAlphaMode(this.alphaBlendingMode);
  40557. engine.draw(true, 0, 6);
  40558. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40559. }
  40560. else {
  40561. engine.draw(true, 0, 6);
  40562. }
  40563. this.onAfterRenderObservable.notifyObservers(this);
  40564. };
  40565. Layer.prototype.dispose = function () {
  40566. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40567. if (vertexBuffer) {
  40568. vertexBuffer.dispose();
  40569. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40570. }
  40571. if (this._indexBuffer) {
  40572. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40573. this._indexBuffer = null;
  40574. }
  40575. if (this.texture) {
  40576. this.texture.dispose();
  40577. this.texture = null;
  40578. }
  40579. // Remove from scene
  40580. var index = this._scene.layers.indexOf(this);
  40581. this._scene.layers.splice(index, 1);
  40582. // Callback
  40583. this.onDisposeObservable.notifyObservers(this);
  40584. this.onDisposeObservable.clear();
  40585. this.onAfterRenderObservable.clear();
  40586. this.onBeforeRenderObservable.clear();
  40587. };
  40588. return Layer;
  40589. }());
  40590. BABYLON.Layer = Layer;
  40591. })(BABYLON || (BABYLON = {}));
  40592. //# sourceMappingURL=babylon.layer.js.map
  40593. var BABYLON;
  40594. (function (BABYLON) {
  40595. var BlurPostProcess = (function (_super) {
  40596. __extends(BlurPostProcess, _super);
  40597. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  40598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40599. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40600. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  40601. _this.direction = direction;
  40602. _this._packedFloat = false;
  40603. _this.onApplyObservable.add(function (effect) {
  40604. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  40605. });
  40606. _this.kernel = kernel;
  40607. return _this;
  40608. }
  40609. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  40610. /**
  40611. * Gets the length in pixels of the blur sample region
  40612. */
  40613. get: function () {
  40614. return this._idealKernel;
  40615. },
  40616. /**
  40617. * Sets the length in pixels of the blur sample region
  40618. */
  40619. set: function (v) {
  40620. if (this._idealKernel === v) {
  40621. return;
  40622. }
  40623. v = Math.max(v, 1);
  40624. this._idealKernel = v;
  40625. this._kernel = this._nearestBestKernel(v);
  40626. this._updateParameters();
  40627. },
  40628. enumerable: true,
  40629. configurable: true
  40630. });
  40631. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  40632. /**
  40633. * Gets wether or not the blur is unpacking/repacking floats
  40634. */
  40635. get: function () {
  40636. return this._packedFloat;
  40637. },
  40638. /**
  40639. * Sets wether or not the blur needs to unpack/repack floats
  40640. */
  40641. set: function (v) {
  40642. if (this._packedFloat === v) {
  40643. return;
  40644. }
  40645. this._packedFloat = v;
  40646. this._updateParameters();
  40647. },
  40648. enumerable: true,
  40649. configurable: true
  40650. });
  40651. BlurPostProcess.prototype._updateParameters = function () {
  40652. // Generate sampling offsets and weights
  40653. var N = this._kernel;
  40654. var centerIndex = (N - 1) / 2;
  40655. // Generate Gaussian sampling weights over kernel
  40656. var offsets = [];
  40657. var weights = [];
  40658. var totalWeight = 0;
  40659. for (var i = 0; i < N; i++) {
  40660. var u = i / (N - 1);
  40661. var w = this._gaussianWeight(u * 2.0 - 1);
  40662. offsets[i] = (i - centerIndex);
  40663. weights[i] = w;
  40664. totalWeight += w;
  40665. }
  40666. // Normalize weights
  40667. for (var i = 0; i < weights.length; i++) {
  40668. weights[i] /= totalWeight;
  40669. }
  40670. // Optimize: combine samples to take advantage of hardware linear sampling
  40671. // Walk from left to center, combining pairs (symmetrically)
  40672. var linearSamplingWeights = [];
  40673. var linearSamplingOffsets = [];
  40674. var linearSamplingMap = [];
  40675. for (var i = 0; i <= centerIndex; i += 2) {
  40676. var j = Math.min(i + 1, Math.floor(centerIndex));
  40677. var singleCenterSample = i === j;
  40678. if (singleCenterSample) {
  40679. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40680. }
  40681. else {
  40682. var sharedCell = j === centerIndex;
  40683. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  40684. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  40685. if (offsetLinear === 0) {
  40686. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40687. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  40688. }
  40689. else {
  40690. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  40691. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  40692. }
  40693. }
  40694. }
  40695. for (var i = 0; i < linearSamplingMap.length; i++) {
  40696. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  40697. linearSamplingWeights[i] = linearSamplingMap[i].w;
  40698. }
  40699. // Replace with optimized
  40700. offsets = linearSamplingOffsets;
  40701. weights = linearSamplingWeights;
  40702. // Generate shaders
  40703. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  40704. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  40705. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  40706. var defines = "";
  40707. for (var i = 0; i < varyingCount; i++) {
  40708. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  40709. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  40710. }
  40711. var depCount = 0;
  40712. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  40713. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  40714. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  40715. depCount++;
  40716. }
  40717. if (this.packedFloat) {
  40718. defines += "#define PACKEDFLOAT 1";
  40719. }
  40720. this.updateEffect(defines, null, null, {
  40721. varyingCount: varyingCount,
  40722. depCount: depCount
  40723. });
  40724. };
  40725. /**
  40726. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  40727. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  40728. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  40729. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  40730. * The gaps between physical kernels are compensated for in the weighting of the samples
  40731. * @param idealKernel Ideal blur kernel.
  40732. * @return Nearest best kernel.
  40733. */
  40734. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  40735. var v = Math.round(idealKernel);
  40736. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  40737. var k = _a[_i];
  40738. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  40739. return Math.max(k, 3);
  40740. }
  40741. }
  40742. return Math.max(v, 3);
  40743. };
  40744. /**
  40745. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  40746. * @param x The point on the Gaussian distribution to sample.
  40747. * @return the value of the Gaussian function at x.
  40748. */
  40749. BlurPostProcess.prototype._gaussianWeight = function (x) {
  40750. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  40751. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  40752. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  40753. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  40754. // truncated at around 1.3% of peak strength.
  40755. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  40756. var sigma = (1 / 3);
  40757. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  40758. var exponent = -((x * x) / (2.0 * sigma * sigma));
  40759. var weight = (1.0 / denominator) * Math.exp(exponent);
  40760. return weight;
  40761. };
  40762. /**
  40763. * Generates a string that can be used as a floating point number in GLSL.
  40764. * @param x Value to print.
  40765. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  40766. * @return GLSL float string.
  40767. */
  40768. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  40769. if (decimalFigures === void 0) { decimalFigures = 8; }
  40770. return x.toFixed(decimalFigures).replace(/0+$/, '');
  40771. };
  40772. return BlurPostProcess;
  40773. }(BABYLON.PostProcess));
  40774. BABYLON.BlurPostProcess = BlurPostProcess;
  40775. })(BABYLON || (BABYLON = {}));
  40776. //# sourceMappingURL=babylon.blurPostProcess.js.map
  40777. var BABYLON;
  40778. (function (BABYLON) {
  40779. var FxaaPostProcess = (function (_super) {
  40780. __extends(FxaaPostProcess, _super);
  40781. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40782. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40783. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  40784. _this.onApplyObservable.add(function (effect) {
  40785. var texelSize = _this.texelSize;
  40786. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  40787. });
  40788. return _this;
  40789. }
  40790. return FxaaPostProcess;
  40791. }(BABYLON.PostProcess));
  40792. BABYLON.FxaaPostProcess = FxaaPostProcess;
  40793. })(BABYLON || (BABYLON = {}));
  40794. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  40795. var BABYLON;
  40796. (function (BABYLON) {
  40797. var HighlightsPostProcess = (function (_super) {
  40798. __extends(HighlightsPostProcess, _super);
  40799. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40800. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40801. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  40802. }
  40803. return HighlightsPostProcess;
  40804. }(BABYLON.PostProcess));
  40805. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  40806. })(BABYLON || (BABYLON = {}));
  40807. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  40808. var BABYLON;
  40809. (function (BABYLON) {
  40810. var ImageProcessingPostProcess = (function (_super) {
  40811. __extends(ImageProcessingPostProcess, _super);
  40812. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40813. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40814. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  40815. _this._fromLinearSpace = true;
  40816. /**
  40817. * Defines cache preventing GC.
  40818. */
  40819. _this._defines = {
  40820. IMAGEPROCESSING: false,
  40821. VIGNETTE: false,
  40822. VIGNETTEBLENDMODEMULTIPLY: false,
  40823. VIGNETTEBLENDMODEOPAQUE: false,
  40824. TONEMAPPING: false,
  40825. CONTRAST: false,
  40826. COLORCURVES: false,
  40827. COLORGRADING: false,
  40828. FROMLINEARSPACE: false,
  40829. SAMPLER3DGREENDEPTH: false,
  40830. SAMPLER3DBGRMAP: false,
  40831. IMAGEPROCESSINGPOSTPROCESS: false,
  40832. EXPOSURE: false,
  40833. };
  40834. // Setup the default processing configuration to the scene.
  40835. _this._attachImageProcessingConfiguration(null, true);
  40836. _this.imageProcessingConfiguration.applyByPostProcess = true;
  40837. _this.onApply = function (effect) {
  40838. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  40839. };
  40840. return _this;
  40841. }
  40842. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  40843. /**
  40844. * Gets the image processing configuration used either in this material.
  40845. */
  40846. get: function () {
  40847. return this._imageProcessingConfiguration;
  40848. },
  40849. /**
  40850. * Sets the Default image processing configuration used either in the this material.
  40851. *
  40852. * If sets to null, the scene one is in use.
  40853. */
  40854. set: function (value) {
  40855. this._attachImageProcessingConfiguration(value);
  40856. },
  40857. enumerable: true,
  40858. configurable: true
  40859. });
  40860. /**
  40861. * Attaches a new image processing configuration to the PBR Material.
  40862. * @param configuration
  40863. */
  40864. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  40865. var _this = this;
  40866. if (doNotBuild === void 0) { doNotBuild = false; }
  40867. if (configuration === this._imageProcessingConfiguration) {
  40868. return;
  40869. }
  40870. // Detaches observer.
  40871. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40872. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40873. }
  40874. // Pick the scene configuration if needed.
  40875. if (!configuration) {
  40876. var camera = this.getCamera();
  40877. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  40878. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  40879. }
  40880. else {
  40881. this._imageProcessingConfiguration = configuration;
  40882. }
  40883. // Attaches observer.
  40884. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40885. _this._updateParameters();
  40886. });
  40887. // Ensure the effect will be rebuilt.
  40888. if (!doNotBuild) {
  40889. this._updateParameters();
  40890. }
  40891. };
  40892. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  40893. /**
  40894. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  40895. */
  40896. get: function () {
  40897. return this.imageProcessingConfiguration.colorCurves;
  40898. },
  40899. /**
  40900. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  40901. */
  40902. set: function (value) {
  40903. this.imageProcessingConfiguration.colorCurves = value;
  40904. },
  40905. enumerable: true,
  40906. configurable: true
  40907. });
  40908. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  40909. /**
  40910. * Gets wether the color curves effect is enabled.
  40911. */
  40912. get: function () {
  40913. return this.imageProcessingConfiguration.colorCurvesEnabled;
  40914. },
  40915. /**
  40916. * Sets wether the color curves effect is enabled.
  40917. */
  40918. set: function (value) {
  40919. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  40920. },
  40921. enumerable: true,
  40922. configurable: true
  40923. });
  40924. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  40925. /**
  40926. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  40927. */
  40928. get: function () {
  40929. return this.imageProcessingConfiguration.colorGradingTexture;
  40930. },
  40931. /**
  40932. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  40933. */
  40934. set: function (value) {
  40935. this.imageProcessingConfiguration.colorGradingTexture = value;
  40936. },
  40937. enumerable: true,
  40938. configurable: true
  40939. });
  40940. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  40941. /**
  40942. * Gets wether the color grading effect is enabled.
  40943. */
  40944. get: function () {
  40945. return this.imageProcessingConfiguration.colorGradingEnabled;
  40946. },
  40947. /**
  40948. * Gets wether the color grading effect is enabled.
  40949. */
  40950. set: function (value) {
  40951. this.imageProcessingConfiguration.colorGradingEnabled = value;
  40952. },
  40953. enumerable: true,
  40954. configurable: true
  40955. });
  40956. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  40957. /**
  40958. * Gets exposure used in the effect.
  40959. */
  40960. get: function () {
  40961. return this.imageProcessingConfiguration.exposure;
  40962. },
  40963. /**
  40964. * Sets exposure used in the effect.
  40965. */
  40966. set: function (value) {
  40967. this.imageProcessingConfiguration.exposure = value;
  40968. },
  40969. enumerable: true,
  40970. configurable: true
  40971. });
  40972. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  40973. /**
  40974. * Gets wether tonemapping is enabled or not.
  40975. */
  40976. get: function () {
  40977. return this._imageProcessingConfiguration.toneMappingEnabled;
  40978. },
  40979. /**
  40980. * Sets wether tonemapping is enabled or not
  40981. */
  40982. set: function (value) {
  40983. this._imageProcessingConfiguration.toneMappingEnabled = value;
  40984. },
  40985. enumerable: true,
  40986. configurable: true
  40987. });
  40988. ;
  40989. ;
  40990. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  40991. /**
  40992. * Gets contrast used in the effect.
  40993. */
  40994. get: function () {
  40995. return this.imageProcessingConfiguration.contrast;
  40996. },
  40997. /**
  40998. * Sets contrast used in the effect.
  40999. */
  41000. set: function (value) {
  41001. this.imageProcessingConfiguration.contrast = value;
  41002. },
  41003. enumerable: true,
  41004. configurable: true
  41005. });
  41006. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  41007. /**
  41008. * Gets Vignette stretch size.
  41009. */
  41010. get: function () {
  41011. return this.imageProcessingConfiguration.vignetteStretch;
  41012. },
  41013. /**
  41014. * Sets Vignette stretch size.
  41015. */
  41016. set: function (value) {
  41017. this.imageProcessingConfiguration.vignetteStretch = value;
  41018. },
  41019. enumerable: true,
  41020. configurable: true
  41021. });
  41022. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  41023. /**
  41024. * Gets Vignette centre X Offset.
  41025. */
  41026. get: function () {
  41027. return this.imageProcessingConfiguration.vignetteCentreX;
  41028. },
  41029. /**
  41030. * Sets Vignette centre X Offset.
  41031. */
  41032. set: function (value) {
  41033. this.imageProcessingConfiguration.vignetteCentreX = value;
  41034. },
  41035. enumerable: true,
  41036. configurable: true
  41037. });
  41038. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  41039. /**
  41040. * Gets Vignette centre Y Offset.
  41041. */
  41042. get: function () {
  41043. return this.imageProcessingConfiguration.vignetteCentreY;
  41044. },
  41045. /**
  41046. * Sets Vignette centre Y Offset.
  41047. */
  41048. set: function (value) {
  41049. this.imageProcessingConfiguration.vignetteCentreY = value;
  41050. },
  41051. enumerable: true,
  41052. configurable: true
  41053. });
  41054. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  41055. /**
  41056. * Gets Vignette weight or intensity of the vignette effect.
  41057. */
  41058. get: function () {
  41059. return this.imageProcessingConfiguration.vignetteWeight;
  41060. },
  41061. /**
  41062. * Sets Vignette weight or intensity of the vignette effect.
  41063. */
  41064. set: function (value) {
  41065. this.imageProcessingConfiguration.vignetteWeight = value;
  41066. },
  41067. enumerable: true,
  41068. configurable: true
  41069. });
  41070. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  41071. /**
  41072. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41073. * if vignetteEnabled is set to true.
  41074. */
  41075. get: function () {
  41076. return this.imageProcessingConfiguration.vignetteColor;
  41077. },
  41078. /**
  41079. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41080. * if vignetteEnabled is set to true.
  41081. */
  41082. set: function (value) {
  41083. this.imageProcessingConfiguration.vignetteColor = value;
  41084. },
  41085. enumerable: true,
  41086. configurable: true
  41087. });
  41088. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  41089. /**
  41090. * Gets Camera field of view used by the Vignette effect.
  41091. */
  41092. get: function () {
  41093. return this.imageProcessingConfiguration.vignetteCameraFov;
  41094. },
  41095. /**
  41096. * Sets Camera field of view used by the Vignette effect.
  41097. */
  41098. set: function (value) {
  41099. this.imageProcessingConfiguration.vignetteCameraFov = value;
  41100. },
  41101. enumerable: true,
  41102. configurable: true
  41103. });
  41104. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  41105. /**
  41106. * Gets the vignette blend mode allowing different kind of effect.
  41107. */
  41108. get: function () {
  41109. return this.imageProcessingConfiguration.vignetteBlendMode;
  41110. },
  41111. /**
  41112. * Sets the vignette blend mode allowing different kind of effect.
  41113. */
  41114. set: function (value) {
  41115. this.imageProcessingConfiguration.vignetteBlendMode = value;
  41116. },
  41117. enumerable: true,
  41118. configurable: true
  41119. });
  41120. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  41121. /**
  41122. * Gets wether the vignette effect is enabled.
  41123. */
  41124. get: function () {
  41125. return this.imageProcessingConfiguration.vignetteEnabled;
  41126. },
  41127. /**
  41128. * Sets wether the vignette effect is enabled.
  41129. */
  41130. set: function (value) {
  41131. this.imageProcessingConfiguration.vignetteEnabled = value;
  41132. },
  41133. enumerable: true,
  41134. configurable: true
  41135. });
  41136. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  41137. /**
  41138. * Gets wether the input of the processing is in Gamma or Linear Space.
  41139. */
  41140. get: function () {
  41141. return this._fromLinearSpace;
  41142. },
  41143. /**
  41144. * Sets wether the input of the processing is in Gamma or Linear Space.
  41145. */
  41146. set: function (value) {
  41147. if (this._fromLinearSpace === value) {
  41148. return;
  41149. }
  41150. this._fromLinearSpace = value;
  41151. this._updateParameters();
  41152. },
  41153. enumerable: true,
  41154. configurable: true
  41155. });
  41156. ImageProcessingPostProcess.prototype.getClassName = function () {
  41157. return "ImageProcessingPostProcess";
  41158. };
  41159. ImageProcessingPostProcess.prototype._updateParameters = function () {
  41160. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  41161. this.imageProcessingConfiguration.prepareDefines(this._defines);
  41162. var defines = "";
  41163. for (var define in this._defines) {
  41164. if (this._defines[define]) {
  41165. defines += "#define " + define + ";\r\n";
  41166. }
  41167. }
  41168. var samplers = ["textureSampler"];
  41169. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  41170. var uniforms = ["scale"];
  41171. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  41172. this.updateEffect(defines, uniforms, samplers);
  41173. };
  41174. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  41175. _super.prototype.dispose.call(this, camera);
  41176. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41177. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41178. }
  41179. this.imageProcessingConfiguration.applyByPostProcess = false;
  41180. };
  41181. __decorate([
  41182. BABYLON.serialize()
  41183. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  41184. return ImageProcessingPostProcess;
  41185. }(BABYLON.PostProcess));
  41186. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  41187. })(BABYLON || (BABYLON = {}));
  41188. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  41189. var BABYLON;
  41190. (function (BABYLON) {
  41191. /**
  41192. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41193. * It can help converting any input color in a desired output one. This can then be used to create effects
  41194. * from sepia, black and white to sixties or futuristic rendering...
  41195. *
  41196. * The only supported format is currently 3dl.
  41197. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41198. */
  41199. var ColorGradingTexture = (function (_super) {
  41200. __extends(ColorGradingTexture, _super);
  41201. /**
  41202. * Instantiates a ColorGradingTexture from the following parameters.
  41203. *
  41204. * @param url The location of the color gradind data (currently only supporting 3dl)
  41205. * @param scene The scene the texture will be used in
  41206. */
  41207. function ColorGradingTexture(url, scene) {
  41208. var _this = _super.call(this, scene) || this;
  41209. if (!url) {
  41210. return _this;
  41211. }
  41212. _this._textureMatrix = BABYLON.Matrix.Identity();
  41213. _this.name = url;
  41214. _this.url = url;
  41215. _this.hasAlpha = false;
  41216. _this.isCube = false;
  41217. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41218. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41219. _this.anisotropicFilteringLevel = 1;
  41220. _this._texture = _this._getFromCache(url, true);
  41221. if (!_this._texture) {
  41222. if (!scene.useDelayedTextureLoading) {
  41223. _this.loadTexture();
  41224. }
  41225. else {
  41226. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41227. }
  41228. }
  41229. return _this;
  41230. }
  41231. /**
  41232. * Returns the texture matrix used in most of the material.
  41233. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41234. */
  41235. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41236. return this._textureMatrix;
  41237. };
  41238. /**
  41239. * Occurs when the file being loaded is a .3dl LUT file.
  41240. */
  41241. ColorGradingTexture.prototype.load3dlTexture = function () {
  41242. var _this = this;
  41243. var mipLevels = 0;
  41244. var floatArrayView = null;
  41245. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41246. this._texture = texture;
  41247. var callback = function (text) {
  41248. var data;
  41249. var tempData;
  41250. var line;
  41251. var lines = text.split('\n');
  41252. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41253. var maxColor = 0;
  41254. for (var i = 0; i < lines.length; i++) {
  41255. line = lines[i];
  41256. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41257. continue;
  41258. if (line.indexOf('#') === 0)
  41259. continue;
  41260. var words = line.split(" ");
  41261. if (size === 0) {
  41262. // Number of space + one
  41263. size = words.length;
  41264. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41265. tempData = new Float32Array(size * size * size * 4);
  41266. continue;
  41267. }
  41268. if (size != 0) {
  41269. var r = Math.max(parseInt(words[0]), 0);
  41270. var g = Math.max(parseInt(words[1]), 0);
  41271. var b = Math.max(parseInt(words[2]), 0);
  41272. maxColor = Math.max(r, maxColor);
  41273. maxColor = Math.max(g, maxColor);
  41274. maxColor = Math.max(b, maxColor);
  41275. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41276. tempData[pixelStorageIndex + 0] = r;
  41277. tempData[pixelStorageIndex + 1] = g;
  41278. tempData[pixelStorageIndex + 2] = b;
  41279. pixelIndexSlice++;
  41280. if (pixelIndexSlice % size == 0) {
  41281. pixelIndexH++;
  41282. pixelIndexSlice = 0;
  41283. if (pixelIndexH % size == 0) {
  41284. pixelIndexW++;
  41285. pixelIndexH = 0;
  41286. }
  41287. }
  41288. }
  41289. }
  41290. for (var i = 0; i < tempData.length; i++) {
  41291. if (i > 0 && (i + 1) % 4 === 0) {
  41292. data[i] = 255;
  41293. }
  41294. else {
  41295. var value = tempData[i];
  41296. data[i] = (value / maxColor * 255);
  41297. }
  41298. }
  41299. texture.updateSize(size * size, size);
  41300. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41301. };
  41302. BABYLON.Tools.LoadFile(this.url, callback);
  41303. return this._texture;
  41304. };
  41305. /**
  41306. * Starts the loading process of the texture.
  41307. */
  41308. ColorGradingTexture.prototype.loadTexture = function () {
  41309. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41310. this.load3dlTexture();
  41311. }
  41312. };
  41313. /**
  41314. * Clones the color gradind texture.
  41315. */
  41316. ColorGradingTexture.prototype.clone = function () {
  41317. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41318. // Base texture
  41319. newTexture.level = this.level;
  41320. return newTexture;
  41321. };
  41322. /**
  41323. * Called during delayed load for textures.
  41324. */
  41325. ColorGradingTexture.prototype.delayLoad = function () {
  41326. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41327. return;
  41328. }
  41329. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41330. this._texture = this._getFromCache(this.url, true);
  41331. if (!this._texture) {
  41332. this.loadTexture();
  41333. }
  41334. };
  41335. /**
  41336. * Parses a color grading texture serialized by Babylon.
  41337. * @param parsedTexture The texture information being parsedTexture
  41338. * @param scene The scene to load the texture in
  41339. * @param rootUrl The root url of the data assets to load
  41340. * @return A color gradind texture
  41341. */
  41342. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41343. var texture = null;
  41344. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41345. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  41346. texture.name = parsedTexture.name;
  41347. texture.level = parsedTexture.level;
  41348. }
  41349. return texture;
  41350. };
  41351. /**
  41352. * Serializes the LUT texture to json format.
  41353. */
  41354. ColorGradingTexture.prototype.serialize = function () {
  41355. if (!this.name) {
  41356. return null;
  41357. }
  41358. var serializationObject = {};
  41359. serializationObject.name = this.name;
  41360. serializationObject.level = this.level;
  41361. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41362. return serializationObject;
  41363. };
  41364. /**
  41365. * Empty line regex stored for GC.
  41366. */
  41367. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41368. return ColorGradingTexture;
  41369. }(BABYLON.BaseTexture));
  41370. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41371. })(BABYLON || (BABYLON = {}));
  41372. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41373. var BABYLON;
  41374. (function (BABYLON) {
  41375. /**
  41376. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41377. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41378. * 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;
  41379. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41380. */
  41381. var ColorCurves = (function () {
  41382. function ColorCurves() {
  41383. this._dirty = true;
  41384. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41385. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41386. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41387. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41388. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41389. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41390. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41391. this._globalHue = 30;
  41392. this._globalDensity = 0;
  41393. this._globalSaturation = 0;
  41394. this._globalExposure = 0;
  41395. this._highlightsHue = 30;
  41396. this._highlightsDensity = 0;
  41397. this._highlightsSaturation = 0;
  41398. this._highlightsExposure = 0;
  41399. this._midtonesHue = 30;
  41400. this._midtonesDensity = 0;
  41401. this._midtonesSaturation = 0;
  41402. this._midtonesExposure = 0;
  41403. this._shadowsHue = 30;
  41404. this._shadowsDensity = 0;
  41405. this._shadowsSaturation = 0;
  41406. this._shadowsExposure = 0;
  41407. }
  41408. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41409. /**
  41410. * Gets the global Hue value.
  41411. * 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).
  41412. */
  41413. get: function () {
  41414. return this._globalHue;
  41415. },
  41416. /**
  41417. * Sets the global Hue value.
  41418. * 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).
  41419. */
  41420. set: function (value) {
  41421. this._globalHue = value;
  41422. this._dirty = true;
  41423. },
  41424. enumerable: true,
  41425. configurable: true
  41426. });
  41427. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41428. /**
  41429. * Gets the global Density value.
  41430. * 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.
  41431. * Values less than zero provide a filter of opposite hue.
  41432. */
  41433. get: function () {
  41434. return this._globalDensity;
  41435. },
  41436. /**
  41437. * Sets the global Density value.
  41438. * 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.
  41439. * Values less than zero provide a filter of opposite hue.
  41440. */
  41441. set: function (value) {
  41442. this._globalDensity = value;
  41443. this._dirty = true;
  41444. },
  41445. enumerable: true,
  41446. configurable: true
  41447. });
  41448. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41449. /**
  41450. * Gets the global Saturation value.
  41451. * 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.
  41452. */
  41453. get: function () {
  41454. return this._globalSaturation;
  41455. },
  41456. /**
  41457. * Sets the global Saturation value.
  41458. * 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.
  41459. */
  41460. set: function (value) {
  41461. this._globalSaturation = value;
  41462. this._dirty = true;
  41463. },
  41464. enumerable: true,
  41465. configurable: true
  41466. });
  41467. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41468. /**
  41469. * Gets the highlights Hue value.
  41470. * 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).
  41471. */
  41472. get: function () {
  41473. return this._highlightsHue;
  41474. },
  41475. /**
  41476. * Sets the highlights Hue value.
  41477. * 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).
  41478. */
  41479. set: function (value) {
  41480. this._highlightsHue = value;
  41481. this._dirty = true;
  41482. },
  41483. enumerable: true,
  41484. configurable: true
  41485. });
  41486. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41487. /**
  41488. * Gets the highlights Density value.
  41489. * 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.
  41490. * Values less than zero provide a filter of opposite hue.
  41491. */
  41492. get: function () {
  41493. return this._highlightsDensity;
  41494. },
  41495. /**
  41496. * Sets the highlights Density value.
  41497. * 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.
  41498. * Values less than zero provide a filter of opposite hue.
  41499. */
  41500. set: function (value) {
  41501. this._highlightsDensity = value;
  41502. this._dirty = true;
  41503. },
  41504. enumerable: true,
  41505. configurable: true
  41506. });
  41507. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41508. /**
  41509. * Gets the highlights Saturation value.
  41510. * 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.
  41511. */
  41512. get: function () {
  41513. return this._highlightsSaturation;
  41514. },
  41515. /**
  41516. * Sets the highlights Saturation value.
  41517. * 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.
  41518. */
  41519. set: function (value) {
  41520. this._highlightsSaturation = value;
  41521. this._dirty = true;
  41522. },
  41523. enumerable: true,
  41524. configurable: true
  41525. });
  41526. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41527. /**
  41528. * Gets the highlights Exposure value.
  41529. * 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.
  41530. */
  41531. get: function () {
  41532. return this._highlightsExposure;
  41533. },
  41534. /**
  41535. * Sets the highlights Exposure value.
  41536. * 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.
  41537. */
  41538. set: function (value) {
  41539. this._highlightsExposure = value;
  41540. this._dirty = true;
  41541. },
  41542. enumerable: true,
  41543. configurable: true
  41544. });
  41545. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41546. /**
  41547. * Gets the midtones Hue value.
  41548. * 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).
  41549. */
  41550. get: function () {
  41551. return this._midtonesHue;
  41552. },
  41553. /**
  41554. * Sets the midtones Hue value.
  41555. * 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).
  41556. */
  41557. set: function (value) {
  41558. this._midtonesHue = value;
  41559. this._dirty = true;
  41560. },
  41561. enumerable: true,
  41562. configurable: true
  41563. });
  41564. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41565. /**
  41566. * Gets the midtones Density value.
  41567. * 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.
  41568. * Values less than zero provide a filter of opposite hue.
  41569. */
  41570. get: function () {
  41571. return this._midtonesDensity;
  41572. },
  41573. /**
  41574. * Sets the midtones Density value.
  41575. * 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.
  41576. * Values less than zero provide a filter of opposite hue.
  41577. */
  41578. set: function (value) {
  41579. this._midtonesDensity = value;
  41580. this._dirty = true;
  41581. },
  41582. enumerable: true,
  41583. configurable: true
  41584. });
  41585. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41586. /**
  41587. * Gets the midtones Saturation value.
  41588. * 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.
  41589. */
  41590. get: function () {
  41591. return this._midtonesSaturation;
  41592. },
  41593. /**
  41594. * Sets the midtones Saturation value.
  41595. * 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.
  41596. */
  41597. set: function (value) {
  41598. this._midtonesSaturation = value;
  41599. this._dirty = true;
  41600. },
  41601. enumerable: true,
  41602. configurable: true
  41603. });
  41604. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41605. /**
  41606. * Gets the midtones Exposure value.
  41607. * 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.
  41608. */
  41609. get: function () {
  41610. return this._midtonesExposure;
  41611. },
  41612. /**
  41613. * Sets the midtones Exposure value.
  41614. * 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.
  41615. */
  41616. set: function (value) {
  41617. this._midtonesExposure = value;
  41618. this._dirty = true;
  41619. },
  41620. enumerable: true,
  41621. configurable: true
  41622. });
  41623. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41624. /**
  41625. * Gets the shadows Hue value.
  41626. * 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).
  41627. */
  41628. get: function () {
  41629. return this._shadowsHue;
  41630. },
  41631. /**
  41632. * Sets the shadows Hue value.
  41633. * 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).
  41634. */
  41635. set: function (value) {
  41636. this._shadowsHue = value;
  41637. this._dirty = true;
  41638. },
  41639. enumerable: true,
  41640. configurable: true
  41641. });
  41642. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41643. /**
  41644. * Gets the shadows Density value.
  41645. * 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.
  41646. * Values less than zero provide a filter of opposite hue.
  41647. */
  41648. get: function () {
  41649. return this._shadowsDensity;
  41650. },
  41651. /**
  41652. * Sets the shadows Density value.
  41653. * 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.
  41654. * Values less than zero provide a filter of opposite hue.
  41655. */
  41656. set: function (value) {
  41657. this._shadowsDensity = value;
  41658. this._dirty = true;
  41659. },
  41660. enumerable: true,
  41661. configurable: true
  41662. });
  41663. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41664. /**
  41665. * Gets the shadows Saturation value.
  41666. * 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.
  41667. */
  41668. get: function () {
  41669. return this._shadowsSaturation;
  41670. },
  41671. /**
  41672. * Sets the shadows Saturation value.
  41673. * 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.
  41674. */
  41675. set: function (value) {
  41676. this._shadowsSaturation = value;
  41677. this._dirty = true;
  41678. },
  41679. enumerable: true,
  41680. configurable: true
  41681. });
  41682. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41683. /**
  41684. * Gets the shadows Exposure value.
  41685. * 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.
  41686. */
  41687. get: function () {
  41688. return this._shadowsExposure;
  41689. },
  41690. /**
  41691. * Sets the shadows Exposure value.
  41692. * 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.
  41693. */
  41694. set: function (value) {
  41695. this._shadowsExposure = value;
  41696. this._dirty = true;
  41697. },
  41698. enumerable: true,
  41699. configurable: true
  41700. });
  41701. ColorCurves.prototype.getClassName = function () {
  41702. return "ColorCurves";
  41703. };
  41704. /**
  41705. * Binds the color curves to the shader.
  41706. * @param colorCurves The color curve to bind
  41707. * @param effect The effect to bind to
  41708. */
  41709. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41710. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41711. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41712. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41713. if (colorCurves._dirty) {
  41714. colorCurves._dirty = false;
  41715. // Fill in global info.
  41716. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41717. // Compute highlights info.
  41718. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41719. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41720. // Compute midtones info.
  41721. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41722. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41723. // Compute shadows info.
  41724. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41725. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41726. // Compute deltas (neutral is midtones).
  41727. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41728. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41729. }
  41730. if (effect) {
  41731. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41732. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41733. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41734. }
  41735. };
  41736. /**
  41737. * Prepare the list of uniforms associated with the ColorCurves effects.
  41738. * @param uniformsList The list of uniforms used in the effect
  41739. */
  41740. ColorCurves.PrepareUniforms = function (uniformsList) {
  41741. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41742. };
  41743. /**
  41744. * Returns color grading data based on a hue, density, saturation and exposure value.
  41745. * @param filterHue The hue of the color filter.
  41746. * @param filterDensity The density of the color filter.
  41747. * @param saturation The saturation.
  41748. * @param exposure The exposure.
  41749. * @param result The result data container.
  41750. */
  41751. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41752. if (hue == null) {
  41753. return;
  41754. }
  41755. hue = ColorCurves.clamp(hue, 0, 360);
  41756. density = ColorCurves.clamp(density, -100, 100);
  41757. saturation = ColorCurves.clamp(saturation, -100, 100);
  41758. exposure = ColorCurves.clamp(exposure, -100, 100);
  41759. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41760. // so that the maximum filter density is only 50% control. This provides fine control
  41761. // for small values and reasonable range.
  41762. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41763. density *= 0.5;
  41764. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41765. if (density < 0) {
  41766. density *= -1;
  41767. hue = (hue + 180) % 360;
  41768. }
  41769. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41770. result.scaleToRef(2, result);
  41771. result.a = 1 + 0.01 * saturation;
  41772. };
  41773. /**
  41774. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41775. * @param value The input slider value in range [-100,100].
  41776. * @returns Adjusted value.
  41777. */
  41778. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41779. value /= 100;
  41780. var x = Math.abs(value);
  41781. x = Math.pow(x, 2);
  41782. if (value < 0) {
  41783. x *= -1;
  41784. }
  41785. x *= 100;
  41786. return x;
  41787. };
  41788. /**
  41789. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41790. * @param hue The hue (H) input.
  41791. * @param saturation The saturation (S) input.
  41792. * @param brightness The brightness (B) input.
  41793. * @result An RGBA color represented as Vector4.
  41794. */
  41795. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41796. var h = ColorCurves.clamp(hue, 0, 360);
  41797. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41798. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41799. if (s === 0) {
  41800. result.r = v;
  41801. result.g = v;
  41802. result.b = v;
  41803. }
  41804. else {
  41805. // sector 0 to 5
  41806. h /= 60;
  41807. var i = Math.floor(h);
  41808. // fractional part of h
  41809. var f = h - i;
  41810. var p = v * (1 - s);
  41811. var q = v * (1 - s * f);
  41812. var t = v * (1 - s * (1 - f));
  41813. switch (i) {
  41814. case 0:
  41815. result.r = v;
  41816. result.g = t;
  41817. result.b = p;
  41818. break;
  41819. case 1:
  41820. result.r = q;
  41821. result.g = v;
  41822. result.b = p;
  41823. break;
  41824. case 2:
  41825. result.r = p;
  41826. result.g = v;
  41827. result.b = t;
  41828. break;
  41829. case 3:
  41830. result.r = p;
  41831. result.g = q;
  41832. result.b = v;
  41833. break;
  41834. case 4:
  41835. result.r = t;
  41836. result.g = p;
  41837. result.b = v;
  41838. break;
  41839. default:// case 5:
  41840. result.r = v;
  41841. result.g = p;
  41842. result.b = q;
  41843. break;
  41844. }
  41845. }
  41846. result.a = 1;
  41847. };
  41848. /**
  41849. * Returns a value clamped between min and max
  41850. * @param value The value to clamp
  41851. * @param min The minimum of value
  41852. * @param max The maximum of value
  41853. * @returns The clamped value.
  41854. */
  41855. ColorCurves.clamp = function (value, min, max) {
  41856. return Math.min(Math.max(value, min), max);
  41857. };
  41858. /**
  41859. * Clones the current color curve instance.
  41860. * @return The cloned curves
  41861. */
  41862. ColorCurves.prototype.clone = function () {
  41863. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41864. };
  41865. /**
  41866. * Serializes the current color curve instance to a json representation.
  41867. * @return a JSON representation
  41868. */
  41869. ColorCurves.prototype.serialize = function () {
  41870. return BABYLON.SerializationHelper.Serialize(this);
  41871. };
  41872. /**
  41873. * Parses the color curve from a json representation.
  41874. * @param source the JSON source to parse
  41875. * @return The parsed curves
  41876. */
  41877. ColorCurves.Parse = function (source) {
  41878. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41879. };
  41880. __decorate([
  41881. BABYLON.serialize()
  41882. ], ColorCurves.prototype, "_globalHue", void 0);
  41883. __decorate([
  41884. BABYLON.serialize()
  41885. ], ColorCurves.prototype, "_globalDensity", void 0);
  41886. __decorate([
  41887. BABYLON.serialize()
  41888. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41889. __decorate([
  41890. BABYLON.serialize()
  41891. ], ColorCurves.prototype, "_globalExposure", void 0);
  41892. __decorate([
  41893. BABYLON.serialize()
  41894. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41895. __decorate([
  41896. BABYLON.serialize()
  41897. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41898. __decorate([
  41899. BABYLON.serialize()
  41900. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41901. __decorate([
  41902. BABYLON.serialize()
  41903. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41904. __decorate([
  41905. BABYLON.serialize()
  41906. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41907. __decorate([
  41908. BABYLON.serialize()
  41909. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41910. __decorate([
  41911. BABYLON.serialize()
  41912. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41913. __decorate([
  41914. BABYLON.serialize()
  41915. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41916. return ColorCurves;
  41917. }());
  41918. BABYLON.ColorCurves = ColorCurves;
  41919. })(BABYLON || (BABYLON = {}));
  41920. //# sourceMappingURL=babylon.colorCurves.js.map
  41921. var BABYLON;
  41922. (function (BABYLON) {
  41923. var PostProcessRenderPipelineManager = (function () {
  41924. function PostProcessRenderPipelineManager() {
  41925. this._renderPipelines = {};
  41926. }
  41927. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  41928. this._renderPipelines[renderPipeline._name] = renderPipeline;
  41929. };
  41930. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  41931. var renderPipeline = this._renderPipelines[renderPipelineName];
  41932. if (!renderPipeline) {
  41933. return;
  41934. }
  41935. renderPipeline._attachCameras(cameras, unique);
  41936. };
  41937. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  41938. var renderPipeline = this._renderPipelines[renderPipelineName];
  41939. if (!renderPipeline) {
  41940. return;
  41941. }
  41942. renderPipeline._detachCameras(cameras);
  41943. };
  41944. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  41945. var renderPipeline = this._renderPipelines[renderPipelineName];
  41946. if (!renderPipeline) {
  41947. return;
  41948. }
  41949. renderPipeline._enableEffect(renderEffectName, cameras);
  41950. };
  41951. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  41952. var renderPipeline = this._renderPipelines[renderPipelineName];
  41953. if (!renderPipeline) {
  41954. return;
  41955. }
  41956. renderPipeline._disableEffect(renderEffectName, cameras);
  41957. };
  41958. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  41959. var renderPipeline = this._renderPipelines[renderPipelineName];
  41960. if (!renderPipeline) {
  41961. return;
  41962. }
  41963. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  41964. };
  41965. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  41966. var renderPipeline = this._renderPipelines[renderPipelineName];
  41967. if (!renderPipeline) {
  41968. return;
  41969. }
  41970. renderPipeline._disableDisplayOnlyPass(cameras);
  41971. };
  41972. PostProcessRenderPipelineManager.prototype.update = function () {
  41973. for (var renderPipelineName in this._renderPipelines) {
  41974. var pipeline = this._renderPipelines[renderPipelineName];
  41975. if (!pipeline.isSupported) {
  41976. pipeline.dispose();
  41977. delete this._renderPipelines[renderPipelineName];
  41978. }
  41979. else {
  41980. pipeline._update();
  41981. }
  41982. }
  41983. };
  41984. return PostProcessRenderPipelineManager;
  41985. }());
  41986. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  41987. })(BABYLON || (BABYLON = {}));
  41988. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  41989. var BABYLON;
  41990. (function (BABYLON) {
  41991. var PostProcessRenderPass = (function () {
  41992. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  41993. this._enabled = true;
  41994. this._refCount = 0;
  41995. this._name = name;
  41996. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  41997. this.setRenderList(renderList);
  41998. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  41999. this._renderTexture.onAfterRenderObservable.add(afterRender);
  42000. this._scene = scene;
  42001. this._renderList = renderList;
  42002. }
  42003. // private
  42004. PostProcessRenderPass.prototype._incRefCount = function () {
  42005. if (this._refCount === 0) {
  42006. this._scene.customRenderTargets.push(this._renderTexture);
  42007. }
  42008. return ++this._refCount;
  42009. };
  42010. PostProcessRenderPass.prototype._decRefCount = function () {
  42011. this._refCount--;
  42012. if (this._refCount <= 0) {
  42013. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  42014. }
  42015. return this._refCount;
  42016. };
  42017. PostProcessRenderPass.prototype._update = function () {
  42018. this.setRenderList(this._renderList);
  42019. };
  42020. // public
  42021. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  42022. this._renderTexture.renderList = renderList;
  42023. };
  42024. PostProcessRenderPass.prototype.getRenderTexture = function () {
  42025. return this._renderTexture;
  42026. };
  42027. return PostProcessRenderPass;
  42028. }());
  42029. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  42030. })(BABYLON || (BABYLON = {}));
  42031. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  42032. var BABYLON;
  42033. (function (BABYLON) {
  42034. var PostProcessRenderEffect = (function () {
  42035. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  42036. this._engine = engine;
  42037. this._name = name;
  42038. this._singleInstance = singleInstance || true;
  42039. this._getPostProcess = getPostProcess;
  42040. this._cameras = [];
  42041. this._indicesForCamera = [];
  42042. this._postProcesses = {};
  42043. this._renderPasses = {};
  42044. this._renderEffectAsPasses = {};
  42045. }
  42046. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  42047. get: function () {
  42048. for (var index in this._postProcesses) {
  42049. if (!this._postProcesses[index].isSupported) {
  42050. return false;
  42051. }
  42052. }
  42053. return true;
  42054. },
  42055. enumerable: true,
  42056. configurable: true
  42057. });
  42058. PostProcessRenderEffect.prototype._update = function () {
  42059. for (var renderPassName in this._renderPasses) {
  42060. this._renderPasses[renderPassName]._update();
  42061. }
  42062. };
  42063. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  42064. this._renderPasses[renderPass._name] = renderPass;
  42065. this._linkParameters();
  42066. };
  42067. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  42068. delete this._renderPasses[renderPass._name];
  42069. this._linkParameters();
  42070. };
  42071. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  42072. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  42073. this._linkParameters();
  42074. };
  42075. PostProcessRenderEffect.prototype.getPass = function (passName) {
  42076. for (var renderPassName in this._renderPasses) {
  42077. if (renderPassName === passName) {
  42078. return this._renderPasses[passName];
  42079. }
  42080. }
  42081. };
  42082. PostProcessRenderEffect.prototype.emptyPasses = function () {
  42083. this._renderPasses = {};
  42084. this._linkParameters();
  42085. };
  42086. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  42087. var cameraKey;
  42088. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42089. for (var i = 0; i < _cam.length; i++) {
  42090. var camera = _cam[i];
  42091. var cameraName = camera.name;
  42092. if (this._singleInstance) {
  42093. cameraKey = 0;
  42094. }
  42095. else {
  42096. cameraKey = cameraName;
  42097. }
  42098. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  42099. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  42100. if (!this._indicesForCamera[cameraName]) {
  42101. this._indicesForCamera[cameraName] = [];
  42102. }
  42103. this._indicesForCamera[cameraName].push(index);
  42104. if (this._cameras.indexOf(camera) === -1) {
  42105. this._cameras[cameraName] = camera;
  42106. }
  42107. for (var passName in this._renderPasses) {
  42108. this._renderPasses[passName]._incRefCount();
  42109. }
  42110. }
  42111. this._linkParameters();
  42112. };
  42113. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  42114. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42115. for (var i = 0; i < _cam.length; i++) {
  42116. var camera = _cam[i];
  42117. var cameraName = camera.name;
  42118. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42119. var index = this._cameras.indexOf(cameraName);
  42120. this._indicesForCamera.splice(index, 1);
  42121. this._cameras.splice(index, 1);
  42122. for (var passName in this._renderPasses) {
  42123. this._renderPasses[passName]._decRefCount();
  42124. }
  42125. }
  42126. };
  42127. PostProcessRenderEffect.prototype._enable = function (cameras) {
  42128. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42129. for (var i = 0; i < _cam.length; i++) {
  42130. var camera = _cam[i];
  42131. var cameraName = camera.name;
  42132. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  42133. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  42134. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  42135. }
  42136. }
  42137. for (var passName in this._renderPasses) {
  42138. this._renderPasses[passName]._incRefCount();
  42139. }
  42140. }
  42141. };
  42142. PostProcessRenderEffect.prototype._disable = function (cameras) {
  42143. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42144. for (var i = 0; i < _cam.length; i++) {
  42145. var camera = _cam[i];
  42146. var cameraName = camera.Name;
  42147. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42148. for (var passName in this._renderPasses) {
  42149. this._renderPasses[passName]._decRefCount();
  42150. }
  42151. }
  42152. };
  42153. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  42154. if (this._singleInstance) {
  42155. return this._postProcesses[0];
  42156. }
  42157. else {
  42158. return this._postProcesses[camera.name];
  42159. }
  42160. };
  42161. PostProcessRenderEffect.prototype._linkParameters = function () {
  42162. var _this = this;
  42163. for (var index in this._postProcesses) {
  42164. if (this.applyParameters) {
  42165. this.applyParameters(this._postProcesses[index]);
  42166. }
  42167. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  42168. _this._linkTextures(effect);
  42169. });
  42170. }
  42171. };
  42172. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  42173. for (var renderPassName in this._renderPasses) {
  42174. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  42175. }
  42176. for (var renderEffectName in this._renderEffectAsPasses) {
  42177. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  42178. }
  42179. };
  42180. return PostProcessRenderEffect;
  42181. }());
  42182. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  42183. })(BABYLON || (BABYLON = {}));
  42184. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  42185. var BABYLON;
  42186. (function (BABYLON) {
  42187. var PostProcessRenderPipeline = (function () {
  42188. function PostProcessRenderPipeline(engine, name) {
  42189. this._engine = engine;
  42190. this._name = name;
  42191. this._renderEffects = new Array();
  42192. this._renderEffectsForIsolatedPass = new Array();
  42193. this._cameras = [];
  42194. }
  42195. PostProcessRenderPipeline.prototype.getClassName = function () {
  42196. return "PostProcessRenderPipeline";
  42197. };
  42198. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  42199. get: function () {
  42200. for (var renderEffectName in this._renderEffects) {
  42201. if (!this._renderEffects[renderEffectName].isSupported) {
  42202. return false;
  42203. }
  42204. }
  42205. return true;
  42206. },
  42207. enumerable: true,
  42208. configurable: true
  42209. });
  42210. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  42211. this._renderEffects[renderEffect._name] = renderEffect;
  42212. };
  42213. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  42214. var renderEffects = this._renderEffects[renderEffectName];
  42215. if (!renderEffects) {
  42216. return;
  42217. }
  42218. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42219. };
  42220. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  42221. var renderEffects = this._renderEffects[renderEffectName];
  42222. if (!renderEffects) {
  42223. return;
  42224. }
  42225. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42226. };
  42227. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  42228. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42229. var indicesToDelete = [];
  42230. var i;
  42231. for (i = 0; i < _cam.length; i++) {
  42232. var camera = _cam[i];
  42233. var cameraName = camera.name;
  42234. if (this._cameras.indexOf(camera) === -1) {
  42235. this._cameras[cameraName] = camera;
  42236. }
  42237. else if (unique) {
  42238. indicesToDelete.push(i);
  42239. }
  42240. }
  42241. for (i = 0; i < indicesToDelete.length; i++) {
  42242. cameras.splice(indicesToDelete[i], 1);
  42243. }
  42244. for (var renderEffectName in this._renderEffects) {
  42245. this._renderEffects[renderEffectName]._attachCameras(_cam);
  42246. }
  42247. };
  42248. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  42249. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42250. for (var renderEffectName in this._renderEffects) {
  42251. this._renderEffects[renderEffectName]._detachCameras(_cam);
  42252. }
  42253. for (var i = 0; i < _cam.length; i++) {
  42254. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  42255. }
  42256. };
  42257. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  42258. var _this = this;
  42259. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42260. var pass = null;
  42261. var renderEffectName;
  42262. for (renderEffectName in this._renderEffects) {
  42263. pass = this._renderEffects[renderEffectName].getPass(passName);
  42264. if (pass != null) {
  42265. break;
  42266. }
  42267. }
  42268. if (pass === null) {
  42269. return;
  42270. }
  42271. for (renderEffectName in this._renderEffects) {
  42272. this._renderEffects[renderEffectName]._disable(_cam);
  42273. }
  42274. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  42275. for (var i = 0; i < _cam.length; i++) {
  42276. var camera = _cam[i];
  42277. var cameraName = camera.name;
  42278. 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); });
  42279. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  42280. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  42281. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  42282. }
  42283. };
  42284. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  42285. var _this = this;
  42286. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42287. for (var i = 0; i < _cam.length; i++) {
  42288. var camera = _cam[i];
  42289. var cameraName = camera.name;
  42290. 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); });
  42291. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  42292. }
  42293. for (var renderEffectName in this._renderEffects) {
  42294. this._renderEffects[renderEffectName]._enable(_cam);
  42295. }
  42296. };
  42297. PostProcessRenderPipeline.prototype._update = function () {
  42298. for (var renderEffectName in this._renderEffects) {
  42299. this._renderEffects[renderEffectName]._update();
  42300. }
  42301. for (var i = 0; i < this._cameras.length; i++) {
  42302. var cameraName = this._cameras[i].name;
  42303. if (this._renderEffectsForIsolatedPass[cameraName]) {
  42304. this._renderEffectsForIsolatedPass[cameraName]._update();
  42305. }
  42306. }
  42307. };
  42308. PostProcessRenderPipeline.prototype._reset = function () {
  42309. this._renderEffects = new Array();
  42310. this._renderEffectsForIsolatedPass = new Array();
  42311. };
  42312. PostProcessRenderPipeline.prototype.dispose = function () {
  42313. // Must be implemented by children
  42314. };
  42315. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  42316. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  42317. __decorate([
  42318. BABYLON.serialize()
  42319. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  42320. return PostProcessRenderPipeline;
  42321. }());
  42322. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  42323. })(BABYLON || (BABYLON = {}));
  42324. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  42325. var BABYLON;
  42326. (function (BABYLON) {
  42327. var DefaultRenderingPipeline = (function (_super) {
  42328. __extends(DefaultRenderingPipeline, _super);
  42329. /**
  42330. * @constructor
  42331. * @param {string} name - The rendering pipeline name
  42332. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  42333. * @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)
  42334. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  42335. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  42336. */
  42337. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  42338. if (automaticBuild === void 0) { automaticBuild = true; }
  42339. var _this = _super.call(this, scene.getEngine(), name) || this;
  42340. _this.PassPostProcessId = "PassPostProcessEffect";
  42341. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  42342. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  42343. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  42344. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  42345. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  42346. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  42347. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  42348. // IAnimatable
  42349. _this.animations = [];
  42350. // Values
  42351. _this._bloomEnabled = false;
  42352. _this._fxaaEnabled = false;
  42353. _this._imageProcessingEnabled = true;
  42354. _this._bloomScale = 0.6;
  42355. _this._buildAllowed = true;
  42356. /**
  42357. * Specifies the size of the bloom blur kernel, relative to the final output size
  42358. */
  42359. _this.bloomKernel = 64;
  42360. /**
  42361. * Specifies the weight of the bloom in the final rendering
  42362. */
  42363. _this._bloomWeight = 0.15;
  42364. _this._cameras = cameras || [];
  42365. _this._buildAllowed = automaticBuild;
  42366. // Initialize
  42367. _this._scene = scene;
  42368. var caps = _this._scene.getEngine().getCaps();
  42369. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  42370. // Misc
  42371. if (_this._hdr) {
  42372. if (caps.textureHalfFloatRender) {
  42373. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  42374. }
  42375. else if (caps.textureFloatRender) {
  42376. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42377. }
  42378. }
  42379. else {
  42380. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42381. }
  42382. // Attach
  42383. scene.postProcessRenderPipelineManager.addPipeline(_this);
  42384. _this._buildPipeline();
  42385. return _this;
  42386. }
  42387. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  42388. get: function () {
  42389. return this._bloomWeight;
  42390. },
  42391. set: function (value) {
  42392. if (this._bloomWeight === value) {
  42393. return;
  42394. }
  42395. this._bloomWeight = value;
  42396. if (this._hdr && this.copyBack) {
  42397. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  42398. }
  42399. },
  42400. enumerable: true,
  42401. configurable: true
  42402. });
  42403. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  42404. get: function () {
  42405. return this._bloomScale;
  42406. },
  42407. set: function (value) {
  42408. if (this._bloomScale === value) {
  42409. return;
  42410. }
  42411. this._bloomScale = value;
  42412. this._buildPipeline();
  42413. },
  42414. enumerable: true,
  42415. configurable: true
  42416. });
  42417. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  42418. get: function () {
  42419. return this._bloomEnabled;
  42420. },
  42421. set: function (enabled) {
  42422. if (this._bloomEnabled === enabled) {
  42423. return;
  42424. }
  42425. this._bloomEnabled = enabled;
  42426. this._buildPipeline();
  42427. },
  42428. enumerable: true,
  42429. configurable: true
  42430. });
  42431. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  42432. get: function () {
  42433. return this._fxaaEnabled;
  42434. },
  42435. set: function (enabled) {
  42436. if (this._fxaaEnabled === enabled) {
  42437. return;
  42438. }
  42439. this._fxaaEnabled = enabled;
  42440. this._buildPipeline();
  42441. },
  42442. enumerable: true,
  42443. configurable: true
  42444. });
  42445. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  42446. get: function () {
  42447. return this._imageProcessingEnabled;
  42448. },
  42449. set: function (enabled) {
  42450. if (this._imageProcessingEnabled === enabled) {
  42451. return;
  42452. }
  42453. this._imageProcessingEnabled = enabled;
  42454. this._buildPipeline();
  42455. },
  42456. enumerable: true,
  42457. configurable: true
  42458. });
  42459. /**
  42460. * Force the compilation of the entire pipeline.
  42461. */
  42462. DefaultRenderingPipeline.prototype.prepare = function () {
  42463. var previousState = this._buildAllowed;
  42464. this._buildAllowed = true;
  42465. this._buildPipeline();
  42466. this._buildAllowed = previousState;
  42467. };
  42468. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  42469. var _this = this;
  42470. if (!this._buildAllowed) {
  42471. return;
  42472. }
  42473. var engine = this._scene.getEngine();
  42474. this._disposePostProcesses();
  42475. this._reset();
  42476. if (this.bloomEnabled) {
  42477. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42478. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  42479. if (!this._hdr) {
  42480. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42481. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  42482. this.highlights.autoClear = false;
  42483. this.highlights.alwaysForcePOT = true;
  42484. }
  42485. 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);
  42486. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  42487. this.blurX.alwaysForcePOT = true;
  42488. this.blurX.autoClear = false;
  42489. this.blurX.onActivateObservable.add(function () {
  42490. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  42491. _this.blurX.kernel = _this.bloomKernel * dw;
  42492. });
  42493. 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);
  42494. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  42495. this.blurY.alwaysForcePOT = true;
  42496. this.blurY.autoClear = false;
  42497. this.blurY.onActivateObservable.add(function () {
  42498. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  42499. _this.blurY.kernel = _this.bloomKernel * dh;
  42500. });
  42501. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42502. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  42503. this.copyBack.alwaysForcePOT = true;
  42504. if (this._hdr) {
  42505. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  42506. var w = this.bloomWeight;
  42507. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  42508. }
  42509. else {
  42510. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  42511. }
  42512. this.copyBack.autoClear = false;
  42513. }
  42514. if (this._imageProcessingEnabled) {
  42515. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42516. if (this._hdr) {
  42517. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  42518. }
  42519. }
  42520. if (this.fxaaEnabled) {
  42521. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42522. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  42523. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42524. }
  42525. else {
  42526. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42527. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  42528. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42529. }
  42530. if (this.bloomEnabled) {
  42531. if (this._hdr) {
  42532. this.copyBack.shareOutputWith(this.blurX);
  42533. if (this.imageProcessing) {
  42534. this.imageProcessing.shareOutputWith(this.pass);
  42535. this.imageProcessing.autoClear = false;
  42536. }
  42537. else if (this.fxaa) {
  42538. this.fxaa.shareOutputWith(this.pass);
  42539. }
  42540. else {
  42541. this.finalMerge.shareOutputWith(this.pass);
  42542. }
  42543. }
  42544. else {
  42545. if (this.fxaa) {
  42546. this.fxaa.shareOutputWith(this.pass);
  42547. }
  42548. else {
  42549. this.finalMerge.shareOutputWith(this.pass);
  42550. }
  42551. }
  42552. }
  42553. if (this._cameras !== null) {
  42554. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  42555. }
  42556. };
  42557. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  42558. for (var i = 0; i < this._cameras.length; i++) {
  42559. var camera = this._cameras[i];
  42560. if (this.pass) {
  42561. this.pass.dispose(camera);
  42562. }
  42563. if (this.highlights) {
  42564. this.highlights.dispose(camera);
  42565. }
  42566. if (this.blurX) {
  42567. this.blurX.dispose(camera);
  42568. }
  42569. if (this.blurY) {
  42570. this.blurY.dispose(camera);
  42571. }
  42572. if (this.copyBack) {
  42573. this.copyBack.dispose(camera);
  42574. }
  42575. if (this.imageProcessing) {
  42576. this.imageProcessing.dispose(camera);
  42577. }
  42578. if (this.fxaa) {
  42579. this.fxaa.dispose(camera);
  42580. }
  42581. if (this.finalMerge) {
  42582. this.finalMerge.dispose(camera);
  42583. }
  42584. }
  42585. this.pass = null;
  42586. this.highlights = null;
  42587. this.blurX = null;
  42588. this.blurY = null;
  42589. this.copyBack = null;
  42590. this.imageProcessing = null;
  42591. this.fxaa = null;
  42592. this.finalMerge = null;
  42593. };
  42594. // Dispose
  42595. DefaultRenderingPipeline.prototype.dispose = function () {
  42596. this._disposePostProcesses();
  42597. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  42598. _super.prototype.dispose.call(this);
  42599. };
  42600. // Serialize rendering pipeline
  42601. DefaultRenderingPipeline.prototype.serialize = function () {
  42602. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42603. serializationObject.customType = "DefaultRenderingPipeline";
  42604. return serializationObject;
  42605. };
  42606. // Parse serialized pipeline
  42607. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  42608. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  42609. };
  42610. __decorate([
  42611. BABYLON.serialize()
  42612. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  42613. __decorate([
  42614. BABYLON.serialize()
  42615. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  42616. __decorate([
  42617. BABYLON.serialize()
  42618. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  42619. __decorate([
  42620. BABYLON.serialize()
  42621. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  42622. __decorate([
  42623. BABYLON.serialize()
  42624. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  42625. __decorate([
  42626. BABYLON.serialize()
  42627. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  42628. __decorate([
  42629. BABYLON.serialize()
  42630. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  42631. __decorate([
  42632. BABYLON.serialize()
  42633. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  42634. return DefaultRenderingPipeline;
  42635. }(BABYLON.PostProcessRenderPipeline));
  42636. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  42637. })(BABYLON || (BABYLON = {}));
  42638. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  42639. var BABYLON;
  42640. (function (BABYLON) {
  42641. /**
  42642. * This groups together the common properties used for image processing either in direct forward pass
  42643. * or through post processing effect depending on the use of the image processing pipeline in your scene
  42644. * or not.
  42645. */
  42646. var ImageProcessingConfiguration = (function () {
  42647. function ImageProcessingConfiguration() {
  42648. /**
  42649. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  42650. */
  42651. this.colorCurves = new BABYLON.ColorCurves();
  42652. this._colorCurvesEnabled = false;
  42653. this._colorGradingEnabled = false;
  42654. this._colorGradingWithGreenDepth = false;
  42655. this._colorGradingBGR = false;
  42656. this._exposure = 1.0;
  42657. this._toneMappingEnabled = false;
  42658. this._contrast = 1.0;
  42659. /**
  42660. * Vignette stretch size.
  42661. */
  42662. this.vignetteStretch = 0;
  42663. /**
  42664. * Vignette centre X Offset.
  42665. */
  42666. this.vignetteCentreX = 0;
  42667. /**
  42668. * Vignette centre Y Offset.
  42669. */
  42670. this.vignetteCentreY = 0;
  42671. /**
  42672. * Vignette weight or intensity of the vignette effect.
  42673. */
  42674. this.vignetteWeight = 1.5;
  42675. /**
  42676. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  42677. * if vignetteEnabled is set to true.
  42678. */
  42679. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  42680. /**
  42681. * Camera field of view used by the Vignette effect.
  42682. */
  42683. this.vignetteCameraFov = 0.5;
  42684. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  42685. this._vignetteEnabled = false;
  42686. this._applyByPostProcess = false;
  42687. /**
  42688. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  42689. * @type {BABYLON.Observable}
  42690. */
  42691. this.onUpdateParameters = new BABYLON.Observable();
  42692. }
  42693. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  42694. /**
  42695. * Gets wether the color curves effect is enabled.
  42696. */
  42697. get: function () {
  42698. return this._colorCurvesEnabled;
  42699. },
  42700. /**
  42701. * Sets wether the color curves effect is enabled.
  42702. */
  42703. set: function (value) {
  42704. if (this._colorCurvesEnabled === value) {
  42705. return;
  42706. }
  42707. this._colorCurvesEnabled = value;
  42708. this._updateParameters();
  42709. },
  42710. enumerable: true,
  42711. configurable: true
  42712. });
  42713. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  42714. /**
  42715. * Gets wether the color grading effect is enabled.
  42716. */
  42717. get: function () {
  42718. return this._colorGradingEnabled;
  42719. },
  42720. /**
  42721. * Sets wether the color grading effect is enabled.
  42722. */
  42723. set: function (value) {
  42724. if (this._colorGradingEnabled === value) {
  42725. return;
  42726. }
  42727. this._colorGradingEnabled = value;
  42728. this._updateParameters();
  42729. },
  42730. enumerable: true,
  42731. configurable: true
  42732. });
  42733. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  42734. /**
  42735. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  42736. */
  42737. get: function () {
  42738. return this._colorGradingWithGreenDepth;
  42739. },
  42740. /**
  42741. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  42742. */
  42743. set: function (value) {
  42744. if (this._colorGradingWithGreenDepth === value) {
  42745. return;
  42746. }
  42747. this._colorGradingWithGreenDepth = value;
  42748. this._updateParameters();
  42749. },
  42750. enumerable: true,
  42751. configurable: true
  42752. });
  42753. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  42754. /**
  42755. * Gets wether the color grading texture contains BGR values.
  42756. */
  42757. get: function () {
  42758. return this._colorGradingBGR;
  42759. },
  42760. /**
  42761. * Sets wether the color grading texture contains BGR values.
  42762. */
  42763. set: function (value) {
  42764. if (this._colorGradingBGR === value) {
  42765. return;
  42766. }
  42767. this._colorGradingBGR = value;
  42768. this._updateParameters();
  42769. },
  42770. enumerable: true,
  42771. configurable: true
  42772. });
  42773. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  42774. /**
  42775. * Gets the Exposure used in the effect.
  42776. */
  42777. get: function () {
  42778. return this._exposure;
  42779. },
  42780. /**
  42781. * Sets the Exposure used in the effect.
  42782. */
  42783. set: function (value) {
  42784. if (this._exposure === value) {
  42785. return;
  42786. }
  42787. this._exposure = value;
  42788. this._updateParameters();
  42789. },
  42790. enumerable: true,
  42791. configurable: true
  42792. });
  42793. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  42794. /**
  42795. * Gets wether the tone mapping effect is enabled.
  42796. */
  42797. get: function () {
  42798. return this._toneMappingEnabled;
  42799. },
  42800. /**
  42801. * Sets wether the tone mapping effect is enabled.
  42802. */
  42803. set: function (value) {
  42804. if (this._toneMappingEnabled === value) {
  42805. return;
  42806. }
  42807. this._toneMappingEnabled = value;
  42808. this._updateParameters();
  42809. },
  42810. enumerable: true,
  42811. configurable: true
  42812. });
  42813. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  42814. /**
  42815. * Gets the contrast used in the effect.
  42816. */
  42817. get: function () {
  42818. return this._contrast;
  42819. },
  42820. /**
  42821. * Sets the contrast used in the effect.
  42822. */
  42823. set: function (value) {
  42824. if (this._contrast === value) {
  42825. return;
  42826. }
  42827. this._contrast = value;
  42828. this._updateParameters();
  42829. },
  42830. enumerable: true,
  42831. configurable: true
  42832. });
  42833. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  42834. /**
  42835. * Gets the vignette blend mode allowing different kind of effect.
  42836. */
  42837. get: function () {
  42838. return this._vignetteBlendMode;
  42839. },
  42840. /**
  42841. * Sets the vignette blend mode allowing different kind of effect.
  42842. */
  42843. set: function (value) {
  42844. if (this._vignetteBlendMode === value) {
  42845. return;
  42846. }
  42847. this._vignetteBlendMode = value;
  42848. this._updateParameters();
  42849. },
  42850. enumerable: true,
  42851. configurable: true
  42852. });
  42853. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  42854. /**
  42855. * Gets wether the vignette effect is enabled.
  42856. */
  42857. get: function () {
  42858. return this._vignetteEnabled;
  42859. },
  42860. /**
  42861. * Sets wether the vignette effect is enabled.
  42862. */
  42863. set: function (value) {
  42864. if (this._vignetteEnabled === value) {
  42865. return;
  42866. }
  42867. this._vignetteEnabled = value;
  42868. this._updateParameters();
  42869. },
  42870. enumerable: true,
  42871. configurable: true
  42872. });
  42873. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  42874. /**
  42875. * Gets wether the image processing is applied through a post process or not.
  42876. */
  42877. get: function () {
  42878. return this._applyByPostProcess;
  42879. },
  42880. /**
  42881. * Sets wether the image processing is applied through a post process or not.
  42882. */
  42883. set: function (value) {
  42884. if (this._applyByPostProcess === value) {
  42885. return;
  42886. }
  42887. this._applyByPostProcess = value;
  42888. this._updateParameters();
  42889. },
  42890. enumerable: true,
  42891. configurable: true
  42892. });
  42893. /**
  42894. * Method called each time the image processing information changes requires to recompile the effect.
  42895. */
  42896. ImageProcessingConfiguration.prototype._updateParameters = function () {
  42897. this.onUpdateParameters.notifyObservers(this);
  42898. };
  42899. ImageProcessingConfiguration.prototype.getClassName = function () {
  42900. return "ImageProcessingConfiguration";
  42901. };
  42902. /**
  42903. * Prepare the list of uniforms associated with the Image Processing effects.
  42904. * @param uniformsList The list of uniforms used in the effect
  42905. * @param defines the list of defines currently in use
  42906. */
  42907. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  42908. if (defines.EXPOSURE) {
  42909. uniforms.push("exposureLinear");
  42910. }
  42911. if (defines.CONTRAST) {
  42912. uniforms.push("contrast");
  42913. }
  42914. if (defines.COLORGRADING) {
  42915. uniforms.push("colorTransformSettings");
  42916. }
  42917. if (defines.VIGNETTE) {
  42918. uniforms.push("vInverseScreenSize");
  42919. uniforms.push("vignetteSettings1");
  42920. uniforms.push("vignetteSettings2");
  42921. }
  42922. if (defines.COLORCURVES) {
  42923. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  42924. }
  42925. };
  42926. /**
  42927. * Prepare the list of samplers associated with the Image Processing effects.
  42928. * @param uniformsList The list of uniforms used in the effect
  42929. * @param defines the list of defines currently in use
  42930. */
  42931. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  42932. if (defines.COLORGRADING) {
  42933. samplersList.push("txColorTransform");
  42934. }
  42935. };
  42936. /**
  42937. * Prepare the list of defines associated to the shader.
  42938. * @param defines the list of defines to complete
  42939. */
  42940. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  42941. defines.VIGNETTE = this.vignetteEnabled;
  42942. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  42943. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  42944. defines.TONEMAPPING = this.toneMappingEnabled;
  42945. defines.CONTRAST = (this.contrast !== 1.0);
  42946. defines.EXPOSURE = (this.exposure !== 1.0);
  42947. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  42948. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  42949. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  42950. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  42951. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  42952. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  42953. };
  42954. /**
  42955. * Returns true if all the image processing information are ready.
  42956. */
  42957. ImageProcessingConfiguration.prototype.isReady = function () {
  42958. // Color Grading texure can not be none blocking.
  42959. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  42960. };
  42961. /**
  42962. * Binds the image processing to the shader.
  42963. * @param effect The effect to bind to
  42964. */
  42965. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  42966. if (aspectRatio === void 0) { aspectRatio = 1; }
  42967. // Color Curves
  42968. if (this._colorCurvesEnabled) {
  42969. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  42970. }
  42971. // Vignette
  42972. if (this._vignetteEnabled) {
  42973. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  42974. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  42975. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  42976. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  42977. var vignetteScaleX = vignetteScaleY * aspectRatio;
  42978. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  42979. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  42980. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  42981. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  42982. var vignettePower = -2.0 * this.vignetteWeight;
  42983. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  42984. }
  42985. // Exposure
  42986. effect.setFloat("exposureLinear", this.exposure);
  42987. // Contrast
  42988. effect.setFloat("contrast", this.contrast);
  42989. // Color transform settings
  42990. if (this.colorGradingTexture) {
  42991. effect.setTexture("txColorTransform", this.colorGradingTexture);
  42992. var textureSize = this.colorGradingTexture.getSize().height;
  42993. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  42994. 0.5 / textureSize, // textureOffset
  42995. textureSize, // textureSize
  42996. this.colorGradingTexture.level // weight
  42997. );
  42998. }
  42999. };
  43000. /**
  43001. * Clones the current image processing instance.
  43002. * @return The cloned image processing
  43003. */
  43004. ImageProcessingConfiguration.prototype.clone = function () {
  43005. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  43006. };
  43007. /**
  43008. * Serializes the current image processing instance to a json representation.
  43009. * @return a JSON representation
  43010. */
  43011. ImageProcessingConfiguration.prototype.serialize = function () {
  43012. return BABYLON.SerializationHelper.Serialize(this);
  43013. };
  43014. /**
  43015. * Parses the image processing from a json representation.
  43016. * @param source the JSON source to parse
  43017. * @return The parsed image processing
  43018. */
  43019. ImageProcessingConfiguration.Parse = function (source) {
  43020. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  43021. };
  43022. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  43023. /**
  43024. * Used to apply the vignette as a mix with the pixel color.
  43025. */
  43026. get: function () {
  43027. return this._VIGNETTEMODE_MULTIPLY;
  43028. },
  43029. enumerable: true,
  43030. configurable: true
  43031. });
  43032. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  43033. /**
  43034. * Used to apply the vignette as a replacement of the pixel color.
  43035. */
  43036. get: function () {
  43037. return this._VIGNETTEMODE_OPAQUE;
  43038. },
  43039. enumerable: true,
  43040. configurable: true
  43041. });
  43042. // Static constants associated to the image processing.
  43043. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  43044. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  43045. __decorate([
  43046. BABYLON.serializeAsColorCurves()
  43047. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  43048. __decorate([
  43049. BABYLON.serialize()
  43050. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  43051. __decorate([
  43052. BABYLON.serializeAsTexture()
  43053. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  43054. __decorate([
  43055. BABYLON.serialize()
  43056. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  43057. __decorate([
  43058. BABYLON.serialize()
  43059. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  43060. __decorate([
  43061. BABYLON.serialize()
  43062. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  43063. __decorate([
  43064. BABYLON.serialize()
  43065. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  43066. __decorate([
  43067. BABYLON.serialize()
  43068. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  43069. __decorate([
  43070. BABYLON.serialize()
  43071. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  43072. __decorate([
  43073. BABYLON.serialize()
  43074. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  43075. __decorate([
  43076. BABYLON.serialize()
  43077. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  43078. __decorate([
  43079. BABYLON.serialize()
  43080. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  43081. __decorate([
  43082. BABYLON.serialize()
  43083. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  43084. __decorate([
  43085. BABYLON.serializeAsColor4()
  43086. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  43087. __decorate([
  43088. BABYLON.serialize()
  43089. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  43090. __decorate([
  43091. BABYLON.serialize()
  43092. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  43093. __decorate([
  43094. BABYLON.serialize()
  43095. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  43096. __decorate([
  43097. BABYLON.serialize()
  43098. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  43099. return ImageProcessingConfiguration;
  43100. }());
  43101. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  43102. })(BABYLON || (BABYLON = {}));
  43103. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  43104. /// <reference path="babylon.mesh.ts" />
  43105. var BABYLON;
  43106. (function (BABYLON) {
  43107. var GroundMesh = (function (_super) {
  43108. __extends(GroundMesh, _super);
  43109. function GroundMesh(name, scene) {
  43110. var _this = _super.call(this, name, scene) || this;
  43111. _this.generateOctree = false;
  43112. _this._worldInverse = new BABYLON.Matrix();
  43113. return _this;
  43114. }
  43115. GroundMesh.prototype.getClassName = function () {
  43116. return "GroundMesh";
  43117. };
  43118. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  43119. get: function () {
  43120. return Math.min(this._subdivisionsX, this._subdivisionsY);
  43121. },
  43122. enumerable: true,
  43123. configurable: true
  43124. });
  43125. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  43126. get: function () {
  43127. return this._subdivisionsX;
  43128. },
  43129. enumerable: true,
  43130. configurable: true
  43131. });
  43132. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  43133. get: function () {
  43134. return this._subdivisionsY;
  43135. },
  43136. enumerable: true,
  43137. configurable: true
  43138. });
  43139. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  43140. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  43141. this._subdivisionsX = chunksCount;
  43142. this._subdivisionsY = chunksCount;
  43143. this.subdivide(chunksCount);
  43144. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  43145. };
  43146. /**
  43147. * Returns a height (y) value in the Worl system :
  43148. * the ground altitude at the coordinates (x, z) expressed in the World system.
  43149. * Returns the ground y position if (x, z) are outside the ground surface.
  43150. */
  43151. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  43152. var world = this.getWorldMatrix();
  43153. var invMat = BABYLON.Tmp.Matrix[5];
  43154. world.invertToRef(invMat);
  43155. var tmpVect = BABYLON.Tmp.Vector3[8];
  43156. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  43157. x = tmpVect.x;
  43158. z = tmpVect.z;
  43159. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43160. return this.position.y;
  43161. }
  43162. if (!this._heightQuads || this._heightQuads.length == 0) {
  43163. this._initHeightQuads();
  43164. this._computeHeightQuads();
  43165. }
  43166. var facet = this._getFacetAt(x, z);
  43167. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  43168. // return y in the World system
  43169. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  43170. return tmpVect.y;
  43171. };
  43172. /**
  43173. * Returns a normalized vector (Vector3) orthogonal to the ground
  43174. * at the ground coordinates (x, z) expressed in the World system.
  43175. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  43176. */
  43177. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  43178. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  43179. this.getNormalAtCoordinatesToRef(x, z, normal);
  43180. return normal;
  43181. };
  43182. /**
  43183. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  43184. * at the ground coordinates (x, z) expressed in the World system.
  43185. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  43186. * Returns the GroundMesh.
  43187. */
  43188. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  43189. var world = this.getWorldMatrix();
  43190. var tmpMat = BABYLON.Tmp.Matrix[5];
  43191. world.invertToRef(tmpMat);
  43192. var tmpVect = BABYLON.Tmp.Vector3[8];
  43193. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  43194. x = tmpVect.x;
  43195. z = tmpVect.z;
  43196. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43197. return this;
  43198. }
  43199. if (!this._heightQuads || this._heightQuads.length == 0) {
  43200. this._initHeightQuads();
  43201. this._computeHeightQuads();
  43202. }
  43203. var facet = this._getFacetAt(x, z);
  43204. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  43205. return this;
  43206. };
  43207. /**
  43208. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  43209. * if the ground has been updated.
  43210. * This can be used in the render loop.
  43211. * Returns the GroundMesh.
  43212. */
  43213. GroundMesh.prototype.updateCoordinateHeights = function () {
  43214. if (!this._heightQuads || this._heightQuads.length == 0) {
  43215. this._initHeightQuads();
  43216. }
  43217. this._computeHeightQuads();
  43218. return this;
  43219. };
  43220. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  43221. GroundMesh.prototype._getFacetAt = function (x, z) {
  43222. // retrieve col and row from x, z coordinates in the ground local system
  43223. var subdivisionsX = this._subdivisionsX;
  43224. var subdivisionsY = this._subdivisionsY;
  43225. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  43226. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  43227. var quad = this._heightQuads[row * this._subdivisionsX + col];
  43228. var facet;
  43229. if (z < quad.slope.x * x + quad.slope.y) {
  43230. facet = quad.facet1;
  43231. }
  43232. else {
  43233. facet = quad.facet2;
  43234. }
  43235. return facet;
  43236. };
  43237. // Creates and populates the heightMap array with "facet" elements :
  43238. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  43239. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43240. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43241. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43242. // Returns the GroundMesh.
  43243. GroundMesh.prototype._initHeightQuads = function () {
  43244. var subdivisionsX = this._subdivisionsX;
  43245. var subdivisionsY = this._subdivisionsY;
  43246. this._heightQuads = new Array();
  43247. for (var row = 0; row < subdivisionsY; row++) {
  43248. for (var col = 0; col < subdivisionsX; col++) {
  43249. 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) };
  43250. this._heightQuads[row * subdivisionsX + col] = quad;
  43251. }
  43252. }
  43253. return this;
  43254. };
  43255. // Compute each quad element values and update the the heightMap array :
  43256. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43257. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43258. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43259. // Returns the GroundMesh.
  43260. GroundMesh.prototype._computeHeightQuads = function () {
  43261. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43262. var v1 = BABYLON.Tmp.Vector3[3];
  43263. var v2 = BABYLON.Tmp.Vector3[2];
  43264. var v3 = BABYLON.Tmp.Vector3[1];
  43265. var v4 = BABYLON.Tmp.Vector3[0];
  43266. var v1v2 = BABYLON.Tmp.Vector3[4];
  43267. var v1v3 = BABYLON.Tmp.Vector3[5];
  43268. var v1v4 = BABYLON.Tmp.Vector3[6];
  43269. var norm1 = BABYLON.Tmp.Vector3[7];
  43270. var norm2 = BABYLON.Tmp.Vector3[8];
  43271. var i = 0;
  43272. var j = 0;
  43273. var k = 0;
  43274. var cd = 0; // 2D slope coefficient : z = cd * x + h
  43275. var h = 0;
  43276. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  43277. var d2 = 0;
  43278. var subdivisionsX = this._subdivisionsX;
  43279. var subdivisionsY = this._subdivisionsY;
  43280. for (var row = 0; row < subdivisionsY; row++) {
  43281. for (var col = 0; col < subdivisionsX; col++) {
  43282. i = col * 3;
  43283. j = row * (subdivisionsX + 1) * 3;
  43284. k = (row + 1) * (subdivisionsX + 1) * 3;
  43285. v1.x = positions[j + i];
  43286. v1.y = positions[j + i + 1];
  43287. v1.z = positions[j + i + 2];
  43288. v2.x = positions[j + i + 3];
  43289. v2.y = positions[j + i + 4];
  43290. v2.z = positions[j + i + 5];
  43291. v3.x = positions[k + i];
  43292. v3.y = positions[k + i + 1];
  43293. v3.z = positions[k + i + 2];
  43294. v4.x = positions[k + i + 3];
  43295. v4.y = positions[k + i + 4];
  43296. v4.z = positions[k + i + 5];
  43297. // 2D slope V1V4
  43298. cd = (v4.z - v1.z) / (v4.x - v1.x);
  43299. h = v1.z - cd * v1.x; // v1 belongs to the slope
  43300. // facet equations :
  43301. // we compute each facet normal vector
  43302. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  43303. // we compute the value d by applying the equation to v1 which belongs to the plane
  43304. // then we store the facet equation in a Vector4
  43305. v2.subtractToRef(v1, v1v2);
  43306. v3.subtractToRef(v1, v1v3);
  43307. v4.subtractToRef(v1, v1v4);
  43308. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  43309. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  43310. norm1.normalize();
  43311. norm2.normalize();
  43312. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  43313. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  43314. var quad = this._heightQuads[row * subdivisionsX + col];
  43315. quad.slope.copyFromFloats(cd, h);
  43316. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  43317. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  43318. }
  43319. }
  43320. return this;
  43321. };
  43322. GroundMesh.prototype.serialize = function (serializationObject) {
  43323. _super.prototype.serialize.call(this, serializationObject);
  43324. serializationObject.subdivisionsX = this._subdivisionsX;
  43325. serializationObject.subdivisionsY = this._subdivisionsY;
  43326. serializationObject.minX = this._minX;
  43327. serializationObject.maxX = this._maxX;
  43328. serializationObject.minZ = this._minZ;
  43329. serializationObject.maxZ = this._maxZ;
  43330. serializationObject.width = this._width;
  43331. serializationObject.height = this._height;
  43332. };
  43333. GroundMesh.Parse = function (parsedMesh, scene) {
  43334. var result = new GroundMesh(parsedMesh.name, scene);
  43335. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  43336. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  43337. result._minX = parsedMesh.minX;
  43338. result._maxX = parsedMesh.maxX;
  43339. result._minZ = parsedMesh.minZ;
  43340. result._maxZ = parsedMesh.maxZ;
  43341. result._width = parsedMesh.width;
  43342. result._height = parsedMesh.height;
  43343. return result;
  43344. };
  43345. return GroundMesh;
  43346. }(BABYLON.Mesh));
  43347. BABYLON.GroundMesh = GroundMesh;
  43348. })(BABYLON || (BABYLON = {}));
  43349. //# sourceMappingURL=babylon.groundMesh.js.map
  43350. var BABYLON;
  43351. (function (BABYLON) {
  43352. /**
  43353. * Creates an instance based on a source mesh.
  43354. */
  43355. var InstancedMesh = (function (_super) {
  43356. __extends(InstancedMesh, _super);
  43357. function InstancedMesh(name, source) {
  43358. var _this = _super.call(this, name, source.getScene()) || this;
  43359. source.instances.push(_this);
  43360. _this._sourceMesh = source;
  43361. _this.position.copyFrom(source.position);
  43362. _this.rotation.copyFrom(source.rotation);
  43363. _this.scaling.copyFrom(source.scaling);
  43364. if (source.rotationQuaternion) {
  43365. _this.rotationQuaternion = source.rotationQuaternion.clone();
  43366. }
  43367. _this.infiniteDistance = source.infiniteDistance;
  43368. _this.setPivotMatrix(source.getPivotMatrix());
  43369. _this.refreshBoundingInfo();
  43370. _this._syncSubMeshes();
  43371. return _this;
  43372. }
  43373. /**
  43374. * Returns the string "InstancedMesh".
  43375. */
  43376. InstancedMesh.prototype.getClassName = function () {
  43377. return "InstancedMesh";
  43378. };
  43379. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  43380. // Methods
  43381. get: function () {
  43382. return this._sourceMesh.receiveShadows;
  43383. },
  43384. enumerable: true,
  43385. configurable: true
  43386. });
  43387. Object.defineProperty(InstancedMesh.prototype, "material", {
  43388. get: function () {
  43389. return this._sourceMesh.material;
  43390. },
  43391. enumerable: true,
  43392. configurable: true
  43393. });
  43394. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  43395. get: function () {
  43396. return this._sourceMesh.visibility;
  43397. },
  43398. enumerable: true,
  43399. configurable: true
  43400. });
  43401. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  43402. get: function () {
  43403. return this._sourceMesh.skeleton;
  43404. },
  43405. enumerable: true,
  43406. configurable: true
  43407. });
  43408. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  43409. get: function () {
  43410. return this._sourceMesh.renderingGroupId;
  43411. },
  43412. enumerable: true,
  43413. configurable: true
  43414. });
  43415. /**
  43416. * Returns the total number of vertices (integer).
  43417. */
  43418. InstancedMesh.prototype.getTotalVertices = function () {
  43419. return this._sourceMesh.getTotalVertices();
  43420. };
  43421. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  43422. get: function () {
  43423. return this._sourceMesh;
  43424. },
  43425. enumerable: true,
  43426. configurable: true
  43427. });
  43428. /**
  43429. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  43430. */
  43431. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  43432. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  43433. };
  43434. /**
  43435. * Sets the vertex data of the mesh geometry for the requested `kind`.
  43436. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  43437. * The `data` are either a numeric array either a Float32Array.
  43438. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  43439. * 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).
  43440. * Note that a new underlying VertexBuffer object is created each call.
  43441. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  43442. *
  43443. * Possible `kind` values :
  43444. * - BABYLON.VertexBuffer.PositionKind
  43445. * - BABYLON.VertexBuffer.UVKind
  43446. * - BABYLON.VertexBuffer.UV2Kind
  43447. * - BABYLON.VertexBuffer.UV3Kind
  43448. * - BABYLON.VertexBuffer.UV4Kind
  43449. * - BABYLON.VertexBuffer.UV5Kind
  43450. * - BABYLON.VertexBuffer.UV6Kind
  43451. * - BABYLON.VertexBuffer.ColorKind
  43452. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43453. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43454. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43455. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43456. *
  43457. * Returns the Mesh.
  43458. */
  43459. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  43460. if (this.sourceMesh) {
  43461. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  43462. }
  43463. return this.sourceMesh;
  43464. };
  43465. /**
  43466. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  43467. * If the mesh has no geometry, it is simply returned as it is.
  43468. * The `data` are either a numeric array either a Float32Array.
  43469. * No new underlying VertexBuffer object is created.
  43470. * 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.
  43471. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  43472. *
  43473. * Possible `kind` values :
  43474. * - BABYLON.VertexBuffer.PositionKind
  43475. * - BABYLON.VertexBuffer.UVKind
  43476. * - BABYLON.VertexBuffer.UV2Kind
  43477. * - BABYLON.VertexBuffer.UV3Kind
  43478. * - BABYLON.VertexBuffer.UV4Kind
  43479. * - BABYLON.VertexBuffer.UV5Kind
  43480. * - BABYLON.VertexBuffer.UV6Kind
  43481. * - BABYLON.VertexBuffer.ColorKind
  43482. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43483. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43484. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43485. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43486. *
  43487. * Returns the Mesh.
  43488. */
  43489. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  43490. if (this.sourceMesh) {
  43491. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  43492. }
  43493. return this.sourceMesh;
  43494. };
  43495. /**
  43496. * Sets the mesh indices.
  43497. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  43498. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  43499. * This method creates a new index buffer each call.
  43500. * Returns the Mesh.
  43501. */
  43502. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  43503. if (this.sourceMesh) {
  43504. this.sourceMesh.setIndices(indices, totalVertices);
  43505. }
  43506. return this.sourceMesh;
  43507. };
  43508. /**
  43509. * Boolean : True if the mesh owns the requested kind of data.
  43510. */
  43511. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  43512. return this._sourceMesh.isVerticesDataPresent(kind);
  43513. };
  43514. /**
  43515. * Returns an array of indices (IndicesArray).
  43516. */
  43517. InstancedMesh.prototype.getIndices = function () {
  43518. return this._sourceMesh.getIndices();
  43519. };
  43520. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  43521. get: function () {
  43522. return this._sourceMesh._positions;
  43523. },
  43524. enumerable: true,
  43525. configurable: true
  43526. });
  43527. /**
  43528. * Sets a new updated BoundingInfo to the mesh.
  43529. * Returns the mesh.
  43530. */
  43531. InstancedMesh.prototype.refreshBoundingInfo = function () {
  43532. var meshBB = this._sourceMesh.getBoundingInfo();
  43533. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  43534. this._updateBoundingInfo();
  43535. return this;
  43536. };
  43537. InstancedMesh.prototype._preActivate = function () {
  43538. if (this._currentLOD) {
  43539. this._currentLOD._preActivate();
  43540. }
  43541. return this;
  43542. };
  43543. InstancedMesh.prototype._activate = function (renderId) {
  43544. if (this._currentLOD) {
  43545. this._currentLOD._registerInstanceForRenderId(this, renderId);
  43546. }
  43547. return this;
  43548. };
  43549. /**
  43550. * Returns the current associated LOD AbstractMesh.
  43551. */
  43552. InstancedMesh.prototype.getLOD = function (camera) {
  43553. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  43554. if (this._currentLOD === this.sourceMesh) {
  43555. return this;
  43556. }
  43557. return this._currentLOD;
  43558. };
  43559. InstancedMesh.prototype._syncSubMeshes = function () {
  43560. this.releaseSubMeshes();
  43561. if (this._sourceMesh.subMeshes) {
  43562. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  43563. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  43564. }
  43565. }
  43566. return this;
  43567. };
  43568. InstancedMesh.prototype._generatePointsArray = function () {
  43569. return this._sourceMesh._generatePointsArray();
  43570. };
  43571. /**
  43572. * Creates a new InstancedMesh from the current mesh.
  43573. * - name (string) : the cloned mesh name
  43574. * - newParent (optional Node) : the optional Node to parent the clone to.
  43575. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  43576. *
  43577. * Returns the clone.
  43578. */
  43579. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43580. var result = this._sourceMesh.createInstance(name);
  43581. // Deep copy
  43582. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  43583. // Bounding info
  43584. this.refreshBoundingInfo();
  43585. // Parent
  43586. if (newParent) {
  43587. result.parent = newParent;
  43588. }
  43589. if (!doNotCloneChildren) {
  43590. // Children
  43591. for (var index = 0; index < this.getScene().meshes.length; index++) {
  43592. var mesh = this.getScene().meshes[index];
  43593. if (mesh.parent === this) {
  43594. mesh.clone(mesh.name, result);
  43595. }
  43596. }
  43597. }
  43598. result.computeWorldMatrix(true);
  43599. return result;
  43600. };
  43601. /**
  43602. * Disposes the InstancedMesh.
  43603. * Returns nothing.
  43604. */
  43605. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  43606. // Remove from mesh
  43607. var index = this._sourceMesh.instances.indexOf(this);
  43608. this._sourceMesh.instances.splice(index, 1);
  43609. _super.prototype.dispose.call(this, doNotRecurse);
  43610. };
  43611. return InstancedMesh;
  43612. }(BABYLON.AbstractMesh));
  43613. BABYLON.InstancedMesh = InstancedMesh;
  43614. })(BABYLON || (BABYLON = {}));
  43615. //# sourceMappingURL=babylon.instancedMesh.js.map
  43616. /// <reference path="babylon.mesh.ts" />
  43617. var BABYLON;
  43618. (function (BABYLON) {
  43619. var LinesMesh = (function (_super) {
  43620. __extends(LinesMesh, _super);
  43621. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  43622. if (parent === void 0) { parent = null; }
  43623. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  43624. _this.useVertexColor = useVertexColor;
  43625. _this.color = new BABYLON.Color3(1, 1, 1);
  43626. _this.alpha = 1;
  43627. if (source) {
  43628. _this.color = source.color.clone();
  43629. _this.alpha = source.alpha;
  43630. _this.useVertexColor = source.useVertexColor;
  43631. }
  43632. _this._intersectionThreshold = 0.1;
  43633. var options = {
  43634. attributes: [BABYLON.VertexBuffer.PositionKind],
  43635. uniforms: ["world", "viewProjection"],
  43636. needAlphaBlending: false,
  43637. };
  43638. if (!useVertexColor) {
  43639. options.uniforms.push("color");
  43640. options.needAlphaBlending = true;
  43641. }
  43642. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  43643. return _this;
  43644. }
  43645. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  43646. /**
  43647. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43648. * This margin is expressed in world space coordinates, so its value may vary.
  43649. * Default value is 0.1
  43650. * @returns the intersection Threshold value.
  43651. */
  43652. get: function () {
  43653. return this._intersectionThreshold;
  43654. },
  43655. /**
  43656. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43657. * This margin is expressed in world space coordinates, so its value may vary.
  43658. * @param value the new threshold to apply
  43659. */
  43660. set: function (value) {
  43661. if (this._intersectionThreshold === value) {
  43662. return;
  43663. }
  43664. this._intersectionThreshold = value;
  43665. if (this.geometry) {
  43666. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  43667. }
  43668. },
  43669. enumerable: true,
  43670. configurable: true
  43671. });
  43672. /**
  43673. * Returns the string "LineMesh"
  43674. */
  43675. LinesMesh.prototype.getClassName = function () {
  43676. return "LinesMesh";
  43677. };
  43678. Object.defineProperty(LinesMesh.prototype, "material", {
  43679. get: function () {
  43680. return this._colorShader;
  43681. },
  43682. enumerable: true,
  43683. configurable: true
  43684. });
  43685. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  43686. get: function () {
  43687. return false;
  43688. },
  43689. enumerable: true,
  43690. configurable: true
  43691. });
  43692. LinesMesh.prototype.createInstance = function (name) {
  43693. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  43694. return null;
  43695. };
  43696. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  43697. // VBOs
  43698. this._geometry._bind(this._colorShader.getEffect());
  43699. // Color
  43700. if (!this.useVertexColor) {
  43701. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  43702. }
  43703. return this;
  43704. };
  43705. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  43706. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  43707. return this;
  43708. }
  43709. var engine = this.getScene().getEngine();
  43710. // Draw order
  43711. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  43712. return this;
  43713. };
  43714. LinesMesh.prototype.dispose = function (doNotRecurse) {
  43715. this._colorShader.dispose();
  43716. _super.prototype.dispose.call(this, doNotRecurse);
  43717. };
  43718. /**
  43719. * Returns a new LineMesh object cloned from the current one.
  43720. */
  43721. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43722. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  43723. };
  43724. return LinesMesh;
  43725. }(BABYLON.Mesh));
  43726. BABYLON.LinesMesh = LinesMesh;
  43727. })(BABYLON || (BABYLON = {}));
  43728. //# sourceMappingURL=babylon.linesMesh.js.map
  43729. var BABYLON;
  43730. (function (BABYLON) {
  43731. var StandardMaterialDefines = (function (_super) {
  43732. __extends(StandardMaterialDefines, _super);
  43733. function StandardMaterialDefines() {
  43734. var _this = _super.call(this) || this;
  43735. _this.MAINUV1 = false;
  43736. _this.MAINUV2 = false;
  43737. _this.DIFFUSE = false;
  43738. _this.DIFFUSEDIRECTUV = 0;
  43739. _this.AMBIENT = false;
  43740. _this.AMBIENTDIRECTUV = 0;
  43741. _this.OPACITY = false;
  43742. _this.OPACITYDIRECTUV = 0;
  43743. _this.OPACITYRGB = false;
  43744. _this.REFLECTION = false;
  43745. _this.EMISSIVE = false;
  43746. _this.EMISSIVEDIRECTUV = 0;
  43747. _this.SPECULAR = false;
  43748. _this.SPECULARDIRECTUV = 0;
  43749. _this.BUMP = false;
  43750. _this.BUMPDIRECTUV = 0;
  43751. _this.PARALLAX = false;
  43752. _this.PARALLAXOCCLUSION = false;
  43753. _this.SPECULAROVERALPHA = false;
  43754. _this.CLIPPLANE = false;
  43755. _this.ALPHATEST = false;
  43756. _this.ALPHAFROMDIFFUSE = false;
  43757. _this.POINTSIZE = false;
  43758. _this.FOG = false;
  43759. _this.SPECULARTERM = false;
  43760. _this.DIFFUSEFRESNEL = false;
  43761. _this.OPACITYFRESNEL = false;
  43762. _this.REFLECTIONFRESNEL = false;
  43763. _this.REFRACTIONFRESNEL = false;
  43764. _this.EMISSIVEFRESNEL = false;
  43765. _this.FRESNEL = false;
  43766. _this.NORMAL = false;
  43767. _this.UV1 = false;
  43768. _this.UV2 = false;
  43769. _this.VERTEXCOLOR = false;
  43770. _this.VERTEXALPHA = false;
  43771. _this.NUM_BONE_INFLUENCERS = 0;
  43772. _this.BonesPerMesh = 0;
  43773. _this.INSTANCES = false;
  43774. _this.GLOSSINESS = false;
  43775. _this.ROUGHNESS = false;
  43776. _this.EMISSIVEASILLUMINATION = false;
  43777. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43778. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43779. _this.LIGHTMAP = false;
  43780. _this.LIGHTMAPDIRECTUV = 0;
  43781. _this.USELIGHTMAPASSHADOWMAP = false;
  43782. _this.REFLECTIONMAP_3D = false;
  43783. _this.REFLECTIONMAP_SPHERICAL = false;
  43784. _this.REFLECTIONMAP_PLANAR = false;
  43785. _this.REFLECTIONMAP_CUBIC = false;
  43786. _this.REFLECTIONMAP_PROJECTION = false;
  43787. _this.REFLECTIONMAP_SKYBOX = false;
  43788. _this.REFLECTIONMAP_EXPLICIT = false;
  43789. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43790. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43791. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43792. _this.INVERTCUBICMAP = false;
  43793. _this.LOGARITHMICDEPTH = false;
  43794. _this.REFRACTION = false;
  43795. _this.REFRACTIONMAP_3D = false;
  43796. _this.REFLECTIONOVERALPHA = false;
  43797. _this.TWOSIDEDLIGHTING = false;
  43798. _this.SHADOWFLOAT = false;
  43799. _this.MORPHTARGETS = false;
  43800. _this.MORPHTARGETS_NORMAL = false;
  43801. _this.MORPHTARGETS_TANGENT = false;
  43802. _this.NUM_MORPH_INFLUENCERS = 0;
  43803. _this.USERIGHTHANDEDSYSTEM = false;
  43804. _this.IMAGEPROCESSING = false;
  43805. _this.VIGNETTE = false;
  43806. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43807. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43808. _this.TONEMAPPING = false;
  43809. _this.CONTRAST = false;
  43810. _this.COLORCURVES = false;
  43811. _this.COLORGRADING = false;
  43812. _this.SAMPLER3DGREENDEPTH = false;
  43813. _this.SAMPLER3DBGRMAP = false;
  43814. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43815. _this.EXPOSURE = false;
  43816. _this.rebuild();
  43817. return _this;
  43818. }
  43819. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43820. var modes = [
  43821. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43822. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43823. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43824. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43825. ];
  43826. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43827. var mode = modes_1[_i];
  43828. this[mode] = (mode === modeToEnable);
  43829. }
  43830. };
  43831. return StandardMaterialDefines;
  43832. }(BABYLON.MaterialDefines));
  43833. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43834. var StandardMaterial = (function (_super) {
  43835. __extends(StandardMaterial, _super);
  43836. function StandardMaterial(name, scene) {
  43837. var _this = _super.call(this, name, scene) || this;
  43838. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43839. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43840. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43841. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43842. _this.specularPower = 64;
  43843. _this._useAlphaFromDiffuseTexture = false;
  43844. _this._useEmissiveAsIllumination = false;
  43845. _this._linkEmissiveWithDiffuse = false;
  43846. _this._useSpecularOverAlpha = false;
  43847. _this._useReflectionOverAlpha = false;
  43848. _this._disableLighting = false;
  43849. _this._useParallax = false;
  43850. _this._useParallaxOcclusion = false;
  43851. _this.parallaxScaleBias = 0.05;
  43852. _this._roughness = 0;
  43853. _this.indexOfRefraction = 0.98;
  43854. _this.invertRefractionY = true;
  43855. _this._useLightmapAsShadowmap = false;
  43856. _this._useReflectionFresnelFromSpecular = false;
  43857. _this._useGlossinessFromSpecularMapAlpha = false;
  43858. _this._maxSimultaneousLights = 4;
  43859. /**
  43860. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43861. */
  43862. _this._invertNormalMapX = false;
  43863. /**
  43864. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43865. */
  43866. _this._invertNormalMapY = false;
  43867. /**
  43868. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43869. */
  43870. _this._twoSidedLighting = false;
  43871. _this._renderTargets = new BABYLON.SmartArray(16);
  43872. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43873. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43874. // Setup the default processing configuration to the scene.
  43875. _this._attachImageProcessingConfiguration(null);
  43876. _this.getRenderTargetTextures = function () {
  43877. _this._renderTargets.reset();
  43878. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43879. _this._renderTargets.push(_this._reflectionTexture);
  43880. }
  43881. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43882. _this._renderTargets.push(_this._refractionTexture);
  43883. }
  43884. return _this._renderTargets;
  43885. };
  43886. return _this;
  43887. }
  43888. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43889. /**
  43890. * Gets the image processing configuration used either in this material.
  43891. */
  43892. get: function () {
  43893. return this._imageProcessingConfiguration;
  43894. },
  43895. /**
  43896. * Sets the Default image processing configuration used either in the this material.
  43897. *
  43898. * If sets to null, the scene one is in use.
  43899. */
  43900. set: function (value) {
  43901. this._attachImageProcessingConfiguration(value);
  43902. // Ensure the effect will be rebuilt.
  43903. this._markAllSubMeshesAsTexturesDirty();
  43904. },
  43905. enumerable: true,
  43906. configurable: true
  43907. });
  43908. /**
  43909. * Attaches a new image processing configuration to the Standard Material.
  43910. * @param configuration
  43911. */
  43912. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43913. var _this = this;
  43914. if (configuration === this._imageProcessingConfiguration) {
  43915. return;
  43916. }
  43917. // Detaches observer.
  43918. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43919. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43920. }
  43921. // Pick the scene configuration if needed.
  43922. if (!configuration) {
  43923. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43924. }
  43925. else {
  43926. this._imageProcessingConfiguration = configuration;
  43927. }
  43928. // Attaches observer.
  43929. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43930. _this._markAllSubMeshesAsImageProcessingDirty();
  43931. });
  43932. };
  43933. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43934. /**
  43935. * Gets wether the color curves effect is enabled.
  43936. */
  43937. get: function () {
  43938. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43939. },
  43940. /**
  43941. * Sets wether the color curves effect is enabled.
  43942. */
  43943. set: function (value) {
  43944. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43945. },
  43946. enumerable: true,
  43947. configurable: true
  43948. });
  43949. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43950. /**
  43951. * Gets wether the color grading effect is enabled.
  43952. */
  43953. get: function () {
  43954. return this.imageProcessingConfiguration.colorGradingEnabled;
  43955. },
  43956. /**
  43957. * Gets wether the color grading effect is enabled.
  43958. */
  43959. set: function (value) {
  43960. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43961. },
  43962. enumerable: true,
  43963. configurable: true
  43964. });
  43965. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43966. /**
  43967. * Gets wether tonemapping is enabled or not.
  43968. */
  43969. get: function () {
  43970. return this._imageProcessingConfiguration.toneMappingEnabled;
  43971. },
  43972. /**
  43973. * Sets wether tonemapping is enabled or not
  43974. */
  43975. set: function (value) {
  43976. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43977. },
  43978. enumerable: true,
  43979. configurable: true
  43980. });
  43981. ;
  43982. ;
  43983. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43984. /**
  43985. * The camera exposure used on this material.
  43986. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43987. * This corresponds to a photographic exposure.
  43988. */
  43989. get: function () {
  43990. return this._imageProcessingConfiguration.exposure;
  43991. },
  43992. /**
  43993. * The camera exposure used on this material.
  43994. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43995. * This corresponds to a photographic exposure.
  43996. */
  43997. set: function (value) {
  43998. this._imageProcessingConfiguration.exposure = value;
  43999. },
  44000. enumerable: true,
  44001. configurable: true
  44002. });
  44003. ;
  44004. ;
  44005. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  44006. /**
  44007. * Gets The camera contrast used on this material.
  44008. */
  44009. get: function () {
  44010. return this._imageProcessingConfiguration.contrast;
  44011. },
  44012. /**
  44013. * Sets The camera contrast used on this material.
  44014. */
  44015. set: function (value) {
  44016. this._imageProcessingConfiguration.contrast = value;
  44017. },
  44018. enumerable: true,
  44019. configurable: true
  44020. });
  44021. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  44022. /**
  44023. * Gets the Color Grading 2D Lookup Texture.
  44024. */
  44025. get: function () {
  44026. return this._imageProcessingConfiguration.colorGradingTexture;
  44027. },
  44028. /**
  44029. * Sets the Color Grading 2D Lookup Texture.
  44030. */
  44031. set: function (value) {
  44032. this._imageProcessingConfiguration.colorGradingTexture = value;
  44033. },
  44034. enumerable: true,
  44035. configurable: true
  44036. });
  44037. StandardMaterial.prototype.getClassName = function () {
  44038. return "StandardMaterial";
  44039. };
  44040. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  44041. get: function () {
  44042. return this._useLogarithmicDepth;
  44043. },
  44044. set: function (value) {
  44045. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44046. this._markAllSubMeshesAsMiscDirty();
  44047. },
  44048. enumerable: true,
  44049. configurable: true
  44050. });
  44051. StandardMaterial.prototype.needAlphaBlending = function () {
  44052. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  44053. };
  44054. StandardMaterial.prototype.needAlphaTesting = function () {
  44055. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  44056. };
  44057. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  44058. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  44059. };
  44060. StandardMaterial.prototype.getAlphaTestTexture = function () {
  44061. return this._diffuseTexture;
  44062. };
  44063. /**
  44064. * Child classes can use it to update shaders
  44065. */
  44066. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44067. if (this.isFrozen) {
  44068. if (this._wasPreviouslyReady && subMesh.effect) {
  44069. return true;
  44070. }
  44071. }
  44072. if (!subMesh._materialDefines) {
  44073. subMesh._materialDefines = new StandardMaterialDefines();
  44074. }
  44075. var scene = this.getScene();
  44076. var defines = subMesh._materialDefines;
  44077. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44078. if (defines._renderId === scene.getRenderId()) {
  44079. return true;
  44080. }
  44081. }
  44082. var engine = scene.getEngine();
  44083. // Lights
  44084. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44085. // Textures
  44086. if (defines._areTexturesDirty) {
  44087. defines._needUVs = false;
  44088. defines.MAINUV1 = false;
  44089. defines.MAINUV2 = false;
  44090. if (scene.texturesEnabled) {
  44091. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44092. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  44093. return false;
  44094. }
  44095. else {
  44096. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  44097. }
  44098. }
  44099. else {
  44100. defines.DIFFUSE = false;
  44101. }
  44102. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44103. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44104. return false;
  44105. }
  44106. else {
  44107. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44108. }
  44109. }
  44110. else {
  44111. defines.AMBIENT = false;
  44112. }
  44113. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44114. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44115. return false;
  44116. }
  44117. else {
  44118. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44119. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44120. }
  44121. }
  44122. else {
  44123. defines.OPACITY = false;
  44124. }
  44125. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44126. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  44127. return false;
  44128. }
  44129. else {
  44130. defines._needNormals = true;
  44131. defines.REFLECTION = true;
  44132. defines.ROUGHNESS = (this._roughness > 0);
  44133. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  44134. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  44135. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  44136. switch (this._reflectionTexture.coordinatesMode) {
  44137. case BABYLON.Texture.CUBIC_MODE:
  44138. case BABYLON.Texture.INVCUBIC_MODE:
  44139. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  44140. break;
  44141. case BABYLON.Texture.EXPLICIT_MODE:
  44142. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  44143. break;
  44144. case BABYLON.Texture.PLANAR_MODE:
  44145. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  44146. break;
  44147. case BABYLON.Texture.PROJECTION_MODE:
  44148. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  44149. break;
  44150. case BABYLON.Texture.SKYBOX_MODE:
  44151. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  44152. break;
  44153. case BABYLON.Texture.SPHERICAL_MODE:
  44154. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  44155. break;
  44156. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44157. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  44158. break;
  44159. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44160. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  44161. break;
  44162. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44163. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  44164. break;
  44165. }
  44166. }
  44167. }
  44168. else {
  44169. defines.REFLECTION = false;
  44170. }
  44171. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44172. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44173. return false;
  44174. }
  44175. else {
  44176. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44177. }
  44178. }
  44179. else {
  44180. defines.EMISSIVE = false;
  44181. }
  44182. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44183. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44184. return false;
  44185. }
  44186. else {
  44187. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44188. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44189. }
  44190. }
  44191. else {
  44192. defines.LIGHTMAP = false;
  44193. }
  44194. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44195. if (!this._specularTexture.isReadyOrNotBlocking()) {
  44196. return false;
  44197. }
  44198. else {
  44199. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  44200. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  44201. }
  44202. }
  44203. else {
  44204. defines.SPECULAR = false;
  44205. }
  44206. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  44207. // Bump texure can not be not blocking.
  44208. if (!this._bumpTexture.isReady()) {
  44209. return false;
  44210. }
  44211. else {
  44212. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44213. defines.PARALLAX = this._useParallax;
  44214. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  44215. }
  44216. }
  44217. else {
  44218. defines.BUMP = false;
  44219. }
  44220. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44221. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  44222. return false;
  44223. }
  44224. else {
  44225. defines._needUVs = true;
  44226. defines.REFRACTION = true;
  44227. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  44228. }
  44229. }
  44230. else {
  44231. defines.REFRACTION = false;
  44232. }
  44233. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  44234. }
  44235. else {
  44236. defines.DIFFUSE = false;
  44237. defines.AMBIENT = false;
  44238. defines.OPACITY = false;
  44239. defines.REFLECTION = false;
  44240. defines.EMISSIVE = false;
  44241. defines.LIGHTMAP = false;
  44242. defines.BUMP = false;
  44243. defines.REFRACTION = false;
  44244. }
  44245. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  44246. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  44247. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  44248. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44249. }
  44250. if (defines._areImageProcessingDirty) {
  44251. if (!this._imageProcessingConfiguration.isReady()) {
  44252. return false;
  44253. }
  44254. this._imageProcessingConfiguration.prepareDefines(defines);
  44255. }
  44256. if (defines._areFresnelDirty) {
  44257. if (StandardMaterial.FresnelEnabled) {
  44258. // Fresnel
  44259. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  44260. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  44261. this._reflectionFresnelParameters) {
  44262. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  44263. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  44264. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  44265. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  44266. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  44267. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  44268. defines._needNormals = true;
  44269. defines.FRESNEL = true;
  44270. }
  44271. }
  44272. else {
  44273. defines.FRESNEL = false;
  44274. }
  44275. }
  44276. // Misc.
  44277. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  44278. // Attribs
  44279. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  44280. // Values that need to be evaluated on every frame
  44281. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  44282. // Get correct effect
  44283. if (defines.isDirty) {
  44284. defines.markAsProcessed();
  44285. scene.resetCachedMaterial();
  44286. // Fallbacks
  44287. var fallbacks = new BABYLON.EffectFallbacks();
  44288. if (defines.REFLECTION) {
  44289. fallbacks.addFallback(0, "REFLECTION");
  44290. }
  44291. if (defines.SPECULAR) {
  44292. fallbacks.addFallback(0, "SPECULAR");
  44293. }
  44294. if (defines.BUMP) {
  44295. fallbacks.addFallback(0, "BUMP");
  44296. }
  44297. if (defines.PARALLAX) {
  44298. fallbacks.addFallback(1, "PARALLAX");
  44299. }
  44300. if (defines.PARALLAXOCCLUSION) {
  44301. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44302. }
  44303. if (defines.SPECULAROVERALPHA) {
  44304. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44305. }
  44306. if (defines.FOG) {
  44307. fallbacks.addFallback(1, "FOG");
  44308. }
  44309. if (defines.POINTSIZE) {
  44310. fallbacks.addFallback(0, "POINTSIZE");
  44311. }
  44312. if (defines.LOGARITHMICDEPTH) {
  44313. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44314. }
  44315. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  44316. if (defines.SPECULARTERM) {
  44317. fallbacks.addFallback(0, "SPECULARTERM");
  44318. }
  44319. if (defines.DIFFUSEFRESNEL) {
  44320. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44321. }
  44322. if (defines.OPACITYFRESNEL) {
  44323. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44324. }
  44325. if (defines.REFLECTIONFRESNEL) {
  44326. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44327. }
  44328. if (defines.EMISSIVEFRESNEL) {
  44329. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44330. }
  44331. if (defines.FRESNEL) {
  44332. fallbacks.addFallback(4, "FRESNEL");
  44333. }
  44334. //Attributes
  44335. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44336. if (defines.NORMAL) {
  44337. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44338. }
  44339. if (defines.UV1) {
  44340. attribs.push(BABYLON.VertexBuffer.UVKind);
  44341. }
  44342. if (defines.UV2) {
  44343. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44344. }
  44345. if (defines.VERTEXCOLOR) {
  44346. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44347. }
  44348. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44349. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44350. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44351. var shaderName = "default";
  44352. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44353. "vFogInfos", "vFogColor", "pointSize",
  44354. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44355. "mBones",
  44356. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44357. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44358. "logarithmicDepthConstant", "vNormalReoderParams"
  44359. ];
  44360. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  44361. var uniformBuffers = ["Material", "Scene"];
  44362. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44363. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44364. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44365. uniformsNames: uniforms,
  44366. uniformBuffersNames: uniformBuffers,
  44367. samplers: samplers,
  44368. defines: defines,
  44369. maxSimultaneousLights: this._maxSimultaneousLights
  44370. });
  44371. if (this.customShaderNameResolve) {
  44372. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44373. }
  44374. var join = defines.toString();
  44375. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  44376. attributes: attribs,
  44377. uniformsNames: uniforms,
  44378. uniformBuffersNames: uniformBuffers,
  44379. samplers: samplers,
  44380. defines: join,
  44381. fallbacks: fallbacks,
  44382. onCompiled: this.onCompiled,
  44383. onError: this.onError,
  44384. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44385. }, engine), defines);
  44386. this.buildUniformLayout();
  44387. }
  44388. if (!subMesh.effect.isReady()) {
  44389. return false;
  44390. }
  44391. defines._renderId = scene.getRenderId();
  44392. this._wasPreviouslyReady = true;
  44393. return true;
  44394. };
  44395. StandardMaterial.prototype.buildUniformLayout = function () {
  44396. // Order is important !
  44397. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44398. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44399. this._uniformBuffer.addUniform("opacityParts", 4);
  44400. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44401. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44402. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44403. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44404. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44405. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44406. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44407. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44408. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44409. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44410. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44411. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44412. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44413. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44414. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44415. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44416. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44417. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44418. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44419. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44420. this._uniformBuffer.addUniform("specularMatrix", 16);
  44421. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44422. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  44423. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44424. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44425. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44426. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44427. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44428. this._uniformBuffer.addUniform("pointSize", 1);
  44429. this._uniformBuffer.create();
  44430. };
  44431. StandardMaterial.prototype.unbind = function () {
  44432. if (this._activeEffect) {
  44433. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44434. this._activeEffect.setTexture("reflection2DSampler", null);
  44435. }
  44436. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44437. this._activeEffect.setTexture("refraction2DSampler", null);
  44438. }
  44439. }
  44440. _super.prototype.unbind.call(this);
  44441. };
  44442. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44443. var scene = this.getScene();
  44444. var defines = subMesh._materialDefines;
  44445. if (!defines) {
  44446. return;
  44447. }
  44448. var effect = subMesh.effect;
  44449. this._activeEffect = effect;
  44450. // Matrices
  44451. this.bindOnlyWorldMatrix(world);
  44452. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44453. // Bones
  44454. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44455. if (mustRebind) {
  44456. this._uniformBuffer.bindToEffect(effect, "Material");
  44457. this.bindViewProjection(effect);
  44458. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44459. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44460. // Fresnel
  44461. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44462. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44463. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44464. }
  44465. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44466. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44467. }
  44468. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44469. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44470. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44471. }
  44472. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44473. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44474. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44475. }
  44476. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44477. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44478. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44479. }
  44480. }
  44481. // Textures
  44482. if (scene.texturesEnabled) {
  44483. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44484. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44485. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44486. }
  44487. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44488. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44489. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44490. }
  44491. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44492. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44493. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44494. }
  44495. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44496. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44497. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44498. }
  44499. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44500. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44501. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44502. }
  44503. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44504. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44505. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44506. }
  44507. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44508. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44509. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44510. }
  44511. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44512. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44513. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44514. if (scene._mirroredCameraPosition) {
  44515. 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);
  44516. }
  44517. else {
  44518. 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);
  44519. }
  44520. }
  44521. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44522. var depth = 1.0;
  44523. if (!this._refractionTexture.isCube) {
  44524. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44525. if (this._refractionTexture.depth) {
  44526. depth = this._refractionTexture.depth;
  44527. }
  44528. }
  44529. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44530. }
  44531. }
  44532. // Point size
  44533. if (this.pointsCloud) {
  44534. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44535. }
  44536. if (defines.SPECULARTERM) {
  44537. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44538. }
  44539. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44540. // Diffuse
  44541. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44542. }
  44543. // Textures
  44544. if (scene.texturesEnabled) {
  44545. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44546. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44547. }
  44548. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44549. effect.setTexture("ambientSampler", this._ambientTexture);
  44550. }
  44551. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44552. effect.setTexture("opacitySampler", this._opacityTexture);
  44553. }
  44554. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44555. if (this._reflectionTexture.isCube) {
  44556. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44557. }
  44558. else {
  44559. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44560. }
  44561. }
  44562. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44563. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44564. }
  44565. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44566. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44567. }
  44568. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44569. effect.setTexture("specularSampler", this._specularTexture);
  44570. }
  44571. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44572. effect.setTexture("bumpSampler", this._bumpTexture);
  44573. }
  44574. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44575. var depth = 1.0;
  44576. if (this._refractionTexture.isCube) {
  44577. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44578. }
  44579. else {
  44580. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44581. }
  44582. }
  44583. }
  44584. // Clip plane
  44585. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44586. // Colors
  44587. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44588. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44589. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44590. }
  44591. if (mustRebind || !this.isFrozen) {
  44592. // Lights
  44593. if (scene.lightsEnabled && !this._disableLighting) {
  44594. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44595. }
  44596. // View
  44597. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44598. this.bindView(effect);
  44599. }
  44600. // Fog
  44601. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44602. // Morph targets
  44603. if (defines.NUM_MORPH_INFLUENCERS) {
  44604. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44605. }
  44606. // Log. depth
  44607. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44608. // image processing
  44609. this._imageProcessingConfiguration.bind(this._activeEffect);
  44610. }
  44611. this._uniformBuffer.update();
  44612. this._afterBind(mesh, this._activeEffect);
  44613. };
  44614. StandardMaterial.prototype.getAnimatables = function () {
  44615. var results = [];
  44616. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44617. results.push(this._diffuseTexture);
  44618. }
  44619. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44620. results.push(this._ambientTexture);
  44621. }
  44622. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44623. results.push(this._opacityTexture);
  44624. }
  44625. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44626. results.push(this._reflectionTexture);
  44627. }
  44628. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44629. results.push(this._emissiveTexture);
  44630. }
  44631. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44632. results.push(this._specularTexture);
  44633. }
  44634. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44635. results.push(this._bumpTexture);
  44636. }
  44637. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44638. results.push(this._lightmapTexture);
  44639. }
  44640. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44641. results.push(this._refractionTexture);
  44642. }
  44643. return results;
  44644. };
  44645. StandardMaterial.prototype.getActiveTextures = function () {
  44646. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44647. if (this._diffuseTexture) {
  44648. activeTextures.push(this._diffuseTexture);
  44649. }
  44650. if (this._ambientTexture) {
  44651. activeTextures.push(this._ambientTexture);
  44652. }
  44653. if (this._opacityTexture) {
  44654. activeTextures.push(this._opacityTexture);
  44655. }
  44656. if (this._reflectionTexture) {
  44657. activeTextures.push(this._reflectionTexture);
  44658. }
  44659. if (this._emissiveTexture) {
  44660. activeTextures.push(this._emissiveTexture);
  44661. }
  44662. if (this._specularTexture) {
  44663. activeTextures.push(this._specularTexture);
  44664. }
  44665. if (this._bumpTexture) {
  44666. activeTextures.push(this._bumpTexture);
  44667. }
  44668. if (this._lightmapTexture) {
  44669. activeTextures.push(this._lightmapTexture);
  44670. }
  44671. if (this._refractionTexture) {
  44672. activeTextures.push(this._refractionTexture);
  44673. }
  44674. return activeTextures;
  44675. };
  44676. StandardMaterial.prototype.hasTexture = function (texture) {
  44677. if (_super.prototype.hasTexture.call(this, texture)) {
  44678. return true;
  44679. }
  44680. if (this._diffuseTexture === texture) {
  44681. return true;
  44682. }
  44683. if (this._ambientTexture === texture) {
  44684. return true;
  44685. }
  44686. if (this._opacityTexture === texture) {
  44687. return true;
  44688. }
  44689. if (this._reflectionTexture === texture) {
  44690. return true;
  44691. }
  44692. if (this._emissiveTexture === texture) {
  44693. return true;
  44694. }
  44695. if (this._specularTexture === texture) {
  44696. return true;
  44697. }
  44698. if (this._bumpTexture === texture) {
  44699. return true;
  44700. }
  44701. if (this._lightmapTexture === texture) {
  44702. return true;
  44703. }
  44704. if (this._refractionTexture === texture) {
  44705. return true;
  44706. }
  44707. return false;
  44708. };
  44709. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44710. if (forceDisposeTextures) {
  44711. if (this._diffuseTexture) {
  44712. this._diffuseTexture.dispose();
  44713. }
  44714. if (this._ambientTexture) {
  44715. this._ambientTexture.dispose();
  44716. }
  44717. if (this._opacityTexture) {
  44718. this._opacityTexture.dispose();
  44719. }
  44720. if (this._reflectionTexture) {
  44721. this._reflectionTexture.dispose();
  44722. }
  44723. if (this._emissiveTexture) {
  44724. this._emissiveTexture.dispose();
  44725. }
  44726. if (this._specularTexture) {
  44727. this._specularTexture.dispose();
  44728. }
  44729. if (this._bumpTexture) {
  44730. this._bumpTexture.dispose();
  44731. }
  44732. if (this._lightmapTexture) {
  44733. this._lightmapTexture.dispose();
  44734. }
  44735. if (this._refractionTexture) {
  44736. this._refractionTexture.dispose();
  44737. }
  44738. }
  44739. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44740. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44741. }
  44742. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44743. };
  44744. StandardMaterial.prototype.clone = function (name) {
  44745. var _this = this;
  44746. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44747. result.name = name;
  44748. result.id = name;
  44749. return result;
  44750. };
  44751. StandardMaterial.prototype.serialize = function () {
  44752. return BABYLON.SerializationHelper.Serialize(this);
  44753. };
  44754. // Statics
  44755. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44756. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44757. };
  44758. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44759. get: function () {
  44760. return StandardMaterial._DiffuseTextureEnabled;
  44761. },
  44762. set: function (value) {
  44763. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44764. return;
  44765. }
  44766. StandardMaterial._DiffuseTextureEnabled = value;
  44767. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44768. },
  44769. enumerable: true,
  44770. configurable: true
  44771. });
  44772. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44773. get: function () {
  44774. return StandardMaterial._AmbientTextureEnabled;
  44775. },
  44776. set: function (value) {
  44777. if (StandardMaterial._AmbientTextureEnabled === value) {
  44778. return;
  44779. }
  44780. StandardMaterial._AmbientTextureEnabled = value;
  44781. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44782. },
  44783. enumerable: true,
  44784. configurable: true
  44785. });
  44786. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44787. get: function () {
  44788. return StandardMaterial._OpacityTextureEnabled;
  44789. },
  44790. set: function (value) {
  44791. if (StandardMaterial._OpacityTextureEnabled === value) {
  44792. return;
  44793. }
  44794. StandardMaterial._OpacityTextureEnabled = value;
  44795. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44796. },
  44797. enumerable: true,
  44798. configurable: true
  44799. });
  44800. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44801. get: function () {
  44802. return StandardMaterial._ReflectionTextureEnabled;
  44803. },
  44804. set: function (value) {
  44805. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44806. return;
  44807. }
  44808. StandardMaterial._ReflectionTextureEnabled = value;
  44809. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44810. },
  44811. enumerable: true,
  44812. configurable: true
  44813. });
  44814. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44815. get: function () {
  44816. return StandardMaterial._EmissiveTextureEnabled;
  44817. },
  44818. set: function (value) {
  44819. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44820. return;
  44821. }
  44822. StandardMaterial._EmissiveTextureEnabled = value;
  44823. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44824. },
  44825. enumerable: true,
  44826. configurable: true
  44827. });
  44828. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44829. get: function () {
  44830. return StandardMaterial._SpecularTextureEnabled;
  44831. },
  44832. set: function (value) {
  44833. if (StandardMaterial._SpecularTextureEnabled === value) {
  44834. return;
  44835. }
  44836. StandardMaterial._SpecularTextureEnabled = value;
  44837. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44838. },
  44839. enumerable: true,
  44840. configurable: true
  44841. });
  44842. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44843. get: function () {
  44844. return StandardMaterial._BumpTextureEnabled;
  44845. },
  44846. set: function (value) {
  44847. if (StandardMaterial._BumpTextureEnabled === value) {
  44848. return;
  44849. }
  44850. StandardMaterial._BumpTextureEnabled = value;
  44851. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44852. },
  44853. enumerable: true,
  44854. configurable: true
  44855. });
  44856. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44857. get: function () {
  44858. return StandardMaterial._LightmapTextureEnabled;
  44859. },
  44860. set: function (value) {
  44861. if (StandardMaterial._LightmapTextureEnabled === value) {
  44862. return;
  44863. }
  44864. StandardMaterial._LightmapTextureEnabled = value;
  44865. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44866. },
  44867. enumerable: true,
  44868. configurable: true
  44869. });
  44870. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44871. get: function () {
  44872. return StandardMaterial._RefractionTextureEnabled;
  44873. },
  44874. set: function (value) {
  44875. if (StandardMaterial._RefractionTextureEnabled === value) {
  44876. return;
  44877. }
  44878. StandardMaterial._RefractionTextureEnabled = value;
  44879. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44880. },
  44881. enumerable: true,
  44882. configurable: true
  44883. });
  44884. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44885. get: function () {
  44886. return StandardMaterial._ColorGradingTextureEnabled;
  44887. },
  44888. set: function (value) {
  44889. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44890. return;
  44891. }
  44892. StandardMaterial._ColorGradingTextureEnabled = value;
  44893. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44894. },
  44895. enumerable: true,
  44896. configurable: true
  44897. });
  44898. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44899. get: function () {
  44900. return StandardMaterial._FresnelEnabled;
  44901. },
  44902. set: function (value) {
  44903. if (StandardMaterial._FresnelEnabled === value) {
  44904. return;
  44905. }
  44906. StandardMaterial._FresnelEnabled = value;
  44907. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44908. },
  44909. enumerable: true,
  44910. configurable: true
  44911. });
  44912. // Flags used to enable or disable a type of texture for all Standard Materials
  44913. StandardMaterial._DiffuseTextureEnabled = true;
  44914. StandardMaterial._AmbientTextureEnabled = true;
  44915. StandardMaterial._OpacityTextureEnabled = true;
  44916. StandardMaterial._ReflectionTextureEnabled = true;
  44917. StandardMaterial._EmissiveTextureEnabled = true;
  44918. StandardMaterial._SpecularTextureEnabled = true;
  44919. StandardMaterial._BumpTextureEnabled = true;
  44920. StandardMaterial._LightmapTextureEnabled = true;
  44921. StandardMaterial._RefractionTextureEnabled = true;
  44922. StandardMaterial._ColorGradingTextureEnabled = true;
  44923. StandardMaterial._FresnelEnabled = true;
  44924. __decorate([
  44925. BABYLON.serializeAsTexture("diffuseTexture")
  44926. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44927. __decorate([
  44928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44929. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44930. __decorate([
  44931. BABYLON.serializeAsTexture("ambientTexture")
  44932. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44933. __decorate([
  44934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44935. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44936. __decorate([
  44937. BABYLON.serializeAsTexture("opacityTexture")
  44938. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44939. __decorate([
  44940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44941. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44942. __decorate([
  44943. BABYLON.serializeAsTexture("reflectionTexture")
  44944. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44945. __decorate([
  44946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44947. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44948. __decorate([
  44949. BABYLON.serializeAsTexture("emissiveTexture")
  44950. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44951. __decorate([
  44952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44953. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44954. __decorate([
  44955. BABYLON.serializeAsTexture("specularTexture")
  44956. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44957. __decorate([
  44958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44959. ], StandardMaterial.prototype, "specularTexture", void 0);
  44960. __decorate([
  44961. BABYLON.serializeAsTexture("bumpTexture")
  44962. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44963. __decorate([
  44964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44965. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44966. __decorate([
  44967. BABYLON.serializeAsTexture("lightmapTexture")
  44968. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44969. __decorate([
  44970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44971. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44972. __decorate([
  44973. BABYLON.serializeAsTexture("refractionTexture")
  44974. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44975. __decorate([
  44976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44977. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44978. __decorate([
  44979. BABYLON.serializeAsColor3("ambient")
  44980. ], StandardMaterial.prototype, "ambientColor", void 0);
  44981. __decorate([
  44982. BABYLON.serializeAsColor3("diffuse")
  44983. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44984. __decorate([
  44985. BABYLON.serializeAsColor3("specular")
  44986. ], StandardMaterial.prototype, "specularColor", void 0);
  44987. __decorate([
  44988. BABYLON.serializeAsColor3("emissive")
  44989. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44990. __decorate([
  44991. BABYLON.serialize()
  44992. ], StandardMaterial.prototype, "specularPower", void 0);
  44993. __decorate([
  44994. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44995. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44996. __decorate([
  44997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44998. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44999. __decorate([
  45000. BABYLON.serialize("useEmissiveAsIllumination")
  45001. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  45002. __decorate([
  45003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45004. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45005. __decorate([
  45006. BABYLON.serialize("linkEmissiveWithDiffuse")
  45007. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  45008. __decorate([
  45009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45010. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  45011. __decorate([
  45012. BABYLON.serialize("useSpecularOverAlpha")
  45013. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  45014. __decorate([
  45015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45016. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  45017. __decorate([
  45018. BABYLON.serialize("useReflectionOverAlpha")
  45019. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  45020. __decorate([
  45021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45022. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  45023. __decorate([
  45024. BABYLON.serialize("disableLighting")
  45025. ], StandardMaterial.prototype, "_disableLighting", void 0);
  45026. __decorate([
  45027. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45028. ], StandardMaterial.prototype, "disableLighting", void 0);
  45029. __decorate([
  45030. BABYLON.serialize("useParallax")
  45031. ], StandardMaterial.prototype, "_useParallax", void 0);
  45032. __decorate([
  45033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45034. ], StandardMaterial.prototype, "useParallax", void 0);
  45035. __decorate([
  45036. BABYLON.serialize("useParallaxOcclusion")
  45037. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  45038. __decorate([
  45039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45040. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  45041. __decorate([
  45042. BABYLON.serialize()
  45043. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  45044. __decorate([
  45045. BABYLON.serialize("roughness")
  45046. ], StandardMaterial.prototype, "_roughness", void 0);
  45047. __decorate([
  45048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45049. ], StandardMaterial.prototype, "roughness", void 0);
  45050. __decorate([
  45051. BABYLON.serialize()
  45052. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  45053. __decorate([
  45054. BABYLON.serialize()
  45055. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  45056. __decorate([
  45057. BABYLON.serialize("useLightmapAsShadowmap")
  45058. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  45059. __decorate([
  45060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45061. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45062. __decorate([
  45063. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  45064. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  45065. __decorate([
  45066. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45067. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  45068. __decorate([
  45069. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  45070. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  45071. __decorate([
  45072. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45073. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  45074. __decorate([
  45075. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  45076. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  45077. __decorate([
  45078. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45079. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  45080. __decorate([
  45081. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  45082. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  45083. __decorate([
  45084. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45085. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  45086. __decorate([
  45087. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  45088. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  45089. __decorate([
  45090. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45091. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  45092. __decorate([
  45093. BABYLON.serialize("useReflectionFresnelFromSpecular")
  45094. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  45095. __decorate([
  45096. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45097. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  45098. __decorate([
  45099. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  45100. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  45101. __decorate([
  45102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45103. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  45104. __decorate([
  45105. BABYLON.serialize("maxSimultaneousLights")
  45106. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  45107. __decorate([
  45108. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45109. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  45110. __decorate([
  45111. BABYLON.serialize("invertNormalMapX")
  45112. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  45113. __decorate([
  45114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45115. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  45116. __decorate([
  45117. BABYLON.serialize("invertNormalMapY")
  45118. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  45119. __decorate([
  45120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45121. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  45122. __decorate([
  45123. BABYLON.serialize("twoSidedLighting")
  45124. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  45125. __decorate([
  45126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45127. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  45128. __decorate([
  45129. BABYLON.serialize()
  45130. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  45131. return StandardMaterial;
  45132. }(BABYLON.PushMaterial));
  45133. BABYLON.StandardMaterial = StandardMaterial;
  45134. })(BABYLON || (BABYLON = {}));
  45135. //# sourceMappingURL=babylon.standardMaterial.js.map
  45136. var BABYLON;
  45137. (function (BABYLON) {
  45138. /**
  45139. * This class implement a typical dictionary using a string as key and the generic type T as value.
  45140. * The underlying implementation relies on an associative array to ensure the best performances.
  45141. * The value can be anything including 'null' but except 'undefined'
  45142. */
  45143. var StringDictionary = (function () {
  45144. function StringDictionary() {
  45145. this._count = 0;
  45146. this._data = {};
  45147. }
  45148. /**
  45149. * This will clear this dictionary and copy the content from the 'source' one.
  45150. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  45151. * @param source the dictionary to take the content from and copy to this dictionary
  45152. */
  45153. StringDictionary.prototype.copyFrom = function (source) {
  45154. var _this = this;
  45155. this.clear();
  45156. source.forEach(function (t, v) { return _this.add(t, v); });
  45157. };
  45158. /**
  45159. * Get a value based from its key
  45160. * @param key the given key to get the matching value from
  45161. * @return the value if found, otherwise undefined is returned
  45162. */
  45163. StringDictionary.prototype.get = function (key) {
  45164. var val = this._data[key];
  45165. if (val !== undefined) {
  45166. return val;
  45167. }
  45168. return undefined;
  45169. };
  45170. /**
  45171. * Get a value from its key or add it if it doesn't exist.
  45172. * This method will ensure you that a given key/data will be present in the dictionary.
  45173. * @param key the given key to get the matching value from
  45174. * @param factory the factory that will create the value if the key is not present in the dictionary.
  45175. * The factory will only be invoked if there's no data for the given key.
  45176. * @return the value corresponding to the key.
  45177. */
  45178. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  45179. var val = this.get(key);
  45180. if (val !== undefined) {
  45181. return val;
  45182. }
  45183. val = factory(key);
  45184. if (val) {
  45185. this.add(key, val);
  45186. }
  45187. return val;
  45188. };
  45189. /**
  45190. * Get a value from its key if present in the dictionary otherwise add it
  45191. * @param key the key to get the value from
  45192. * @param val if there's no such key/value pair in the dictionary add it with this value
  45193. * @return the value corresponding to the key
  45194. */
  45195. StringDictionary.prototype.getOrAdd = function (key, val) {
  45196. var curVal = this.get(key);
  45197. if (curVal !== undefined) {
  45198. return curVal;
  45199. }
  45200. this.add(key, val);
  45201. return val;
  45202. };
  45203. /**
  45204. * Check if there's a given key in the dictionary
  45205. * @param key the key to check for
  45206. * @return true if the key is present, false otherwise
  45207. */
  45208. StringDictionary.prototype.contains = function (key) {
  45209. return this._data[key] !== undefined;
  45210. };
  45211. /**
  45212. * Add a new key and its corresponding value
  45213. * @param key the key to add
  45214. * @param value the value corresponding to the key
  45215. * @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
  45216. */
  45217. StringDictionary.prototype.add = function (key, value) {
  45218. if (this._data[key] !== undefined) {
  45219. return false;
  45220. }
  45221. this._data[key] = value;
  45222. ++this._count;
  45223. return true;
  45224. };
  45225. StringDictionary.prototype.set = function (key, value) {
  45226. if (this._data[key] === undefined) {
  45227. return false;
  45228. }
  45229. this._data[key] = value;
  45230. return true;
  45231. };
  45232. /**
  45233. * Get the element of the given key and remove it from the dictionary
  45234. * @param key
  45235. */
  45236. StringDictionary.prototype.getAndRemove = function (key) {
  45237. var val = this.get(key);
  45238. if (val !== undefined) {
  45239. delete this._data[key];
  45240. --this._count;
  45241. return val;
  45242. }
  45243. return null;
  45244. };
  45245. /**
  45246. * Remove a key/value from the dictionary.
  45247. * @param key the key to remove
  45248. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  45249. */
  45250. StringDictionary.prototype.remove = function (key) {
  45251. if (this.contains(key)) {
  45252. delete this._data[key];
  45253. --this._count;
  45254. return true;
  45255. }
  45256. return false;
  45257. };
  45258. /**
  45259. * Clear the whole content of the dictionary
  45260. */
  45261. StringDictionary.prototype.clear = function () {
  45262. this._data = {};
  45263. this._count = 0;
  45264. };
  45265. Object.defineProperty(StringDictionary.prototype, "count", {
  45266. get: function () {
  45267. return this._count;
  45268. },
  45269. enumerable: true,
  45270. configurable: true
  45271. });
  45272. /**
  45273. * Execute a callback on each key/val of the dictionary.
  45274. * Note that you can remove any element in this dictionary in the callback implementation
  45275. * @param callback the callback to execute on a given key/value pair
  45276. */
  45277. StringDictionary.prototype.forEach = function (callback) {
  45278. for (var cur in this._data) {
  45279. var val = this._data[cur];
  45280. callback(cur, val);
  45281. }
  45282. };
  45283. /**
  45284. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  45285. * If the callback returns null or undefined the method will iterate to the next key/value pair
  45286. * Note that you can remove any element in this dictionary in the callback implementation
  45287. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  45288. */
  45289. StringDictionary.prototype.first = function (callback) {
  45290. for (var cur in this._data) {
  45291. var val = this._data[cur];
  45292. var res = callback(cur, val);
  45293. if (res) {
  45294. return res;
  45295. }
  45296. }
  45297. return null;
  45298. };
  45299. return StringDictionary;
  45300. }());
  45301. BABYLON.StringDictionary = StringDictionary;
  45302. })(BABYLON || (BABYLON = {}));
  45303. //# sourceMappingURL=babylon.stringDictionary.js.map
  45304. var BABYLON;
  45305. (function (BABYLON) {
  45306. var DynamicFloatArrayElementInfo = (function () {
  45307. function DynamicFloatArrayElementInfo() {
  45308. }
  45309. return DynamicFloatArrayElementInfo;
  45310. }());
  45311. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  45312. /**
  45313. * 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.
  45314. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  45315. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  45316. * 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.
  45317. * 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.
  45318. * 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".
  45319. */
  45320. var DynamicFloatArray = (function () {
  45321. /**
  45322. * Construct an instance of the dynamic float array
  45323. * @param stride size of one element in float (i.e. not bytes!)
  45324. * @param initialElementCount the number of available entries at construction
  45325. */
  45326. function DynamicFloatArray(stride, initialElementCount) {
  45327. this.compareValueOffset = null;
  45328. this.sortingAscending = true;
  45329. this._stride = stride;
  45330. this.buffer = new Float32Array(stride * initialElementCount);
  45331. this._lastUsed = 0;
  45332. this._firstFree = 0;
  45333. this._allEntries = new Array(initialElementCount);
  45334. this._freeEntries = new Array(initialElementCount);
  45335. for (var i = 0; i < initialElementCount; i++) {
  45336. var element = new DynamicFloatArrayElementInfo();
  45337. element.offset = i * stride;
  45338. this._allEntries[i] = element;
  45339. this._freeEntries[initialElementCount - i - 1] = element;
  45340. }
  45341. }
  45342. /**
  45343. * Allocate an element in the array.
  45344. * @return the element info instance that contains the offset into the main buffer of the element's location.
  45345. * Beware, this offset may change when you call pack()
  45346. */
  45347. DynamicFloatArray.prototype.allocElement = function () {
  45348. if (this._freeEntries.length === 0) {
  45349. this._growBuffer();
  45350. }
  45351. var el = this._freeEntries.pop();
  45352. this._lastUsed = Math.max(el.offset, this._lastUsed);
  45353. if (el.offset === this._firstFree) {
  45354. if (this._freeEntries.length > 0) {
  45355. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  45356. }
  45357. else {
  45358. this._firstFree += this._stride;
  45359. }
  45360. }
  45361. return el;
  45362. };
  45363. /**
  45364. * Free the element corresponding to the given element info
  45365. * @param elInfo the element that describe the allocated element
  45366. */
  45367. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  45368. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  45369. this._freeEntries.push(elInfo);
  45370. };
  45371. /**
  45372. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  45373. * 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().
  45374. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  45375. */
  45376. DynamicFloatArray.prototype.pack = function () {
  45377. // no free slot? no need to pack
  45378. if (this._freeEntries.length === 0) {
  45379. return this.buffer;
  45380. }
  45381. // If the buffer is already packed the last used will always be lower than the first free
  45382. // 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.
  45383. if (this._lastUsed < this._firstFree) {
  45384. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  45385. return elementsBuffer_1;
  45386. }
  45387. var s = this._stride;
  45388. // 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
  45389. var lastFree = new DynamicFloatArrayElementInfo();
  45390. lastFree.offset = this.totalElementCount * s;
  45391. this._freeEntries.push(lastFree);
  45392. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  45393. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45394. var firstFreeSlotOffset = sortedFree[0].offset;
  45395. var freeZoneSize = 1;
  45396. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  45397. var prevOffset = sortedFree[0].offset;
  45398. for (var i = 1; i < sortedFree.length; i++) {
  45399. // 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
  45400. if (firstFreeSlotOffset >= occupiedZoneSize) {
  45401. break;
  45402. }
  45403. var curFree = sortedFree[i];
  45404. var curOffset = curFree.offset;
  45405. // Compute the distance between this offset and the previous
  45406. var distance = curOffset - prevOffset;
  45407. // If the distance is the stride size, they are adjacent, it good, move to the next
  45408. if (distance === s) {
  45409. // Free zone is one element bigger
  45410. ++freeZoneSize;
  45411. // as we're about to iterate to the next, the cur becomes the previous...
  45412. prevOffset = curOffset;
  45413. continue;
  45414. }
  45415. // Distance is bigger, which means there's x element between the previous free and this one
  45416. var usedRange = (distance / s) - 1;
  45417. // Two cases the free zone is smaller than the data to move or bigger
  45418. // Copy what can fit in the free zone
  45419. var curMoveOffset = curOffset - s;
  45420. var copyCount = Math.min(freeZoneSize, usedRange);
  45421. for (var j = 0; j < copyCount; j++) {
  45422. var freeI = firstFreeSlotOffset / s;
  45423. var curI = curMoveOffset / s;
  45424. var moveEl = sortedAll[curI];
  45425. this._moveElement(moveEl, firstFreeSlotOffset);
  45426. var replacedEl = sortedAll[freeI];
  45427. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  45428. replacedEl.offset = curMoveOffset;
  45429. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  45430. sortedAll[freeI] = moveEl;
  45431. sortedAll[curI] = replacedEl;
  45432. curMoveOffset -= s;
  45433. firstFreeSlotOffset += s;
  45434. }
  45435. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  45436. if (freeZoneSize <= usedRange) {
  45437. firstFreeSlotOffset = curMoveOffset + s;
  45438. freeZoneSize = 1 + copyCount;
  45439. }
  45440. else {
  45441. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  45442. }
  45443. // as we're about to iterate to the next, the cur becomes the previous...
  45444. prevOffset = curOffset;
  45445. }
  45446. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  45447. this._lastUsed = firstFreeSlotOffset - s;
  45448. this._firstFree = firstFreeSlotOffset;
  45449. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  45450. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  45451. this._allEntries = sortedAll;
  45452. return elementsBuffer;
  45453. };
  45454. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  45455. for (var i = 0; i < this._stride; i++) {
  45456. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  45457. }
  45458. element.offset = destOffset;
  45459. };
  45460. DynamicFloatArray.prototype._growBuffer = function () {
  45461. // Allocate the new buffer with 50% more entries, copy the content of the current one
  45462. var newElCount = Math.floor(this.totalElementCount * 1.5);
  45463. var newBuffer = new Float32Array(newElCount * this._stride);
  45464. newBuffer.set(this.buffer);
  45465. var curCount = this.totalElementCount;
  45466. var addedCount = newElCount - this.totalElementCount;
  45467. for (var i = 0; i < addedCount; i++) {
  45468. var element = new DynamicFloatArrayElementInfo();
  45469. element.offset = (curCount + i) * this.stride;
  45470. this._allEntries.push(element);
  45471. this._freeEntries[addedCount - i - 1] = element;
  45472. }
  45473. this._firstFree = curCount * this.stride;
  45474. this.buffer = newBuffer;
  45475. };
  45476. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  45477. /**
  45478. * Get the total count of entries that can fit in the current buffer
  45479. * @returns the elements count
  45480. */
  45481. get: function () {
  45482. return this._allEntries.length;
  45483. },
  45484. enumerable: true,
  45485. configurable: true
  45486. });
  45487. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  45488. /**
  45489. * Get the count of free entries that can still be allocated without resizing the buffer
  45490. * @returns the free elements count
  45491. */
  45492. get: function () {
  45493. return this._freeEntries.length;
  45494. },
  45495. enumerable: true,
  45496. configurable: true
  45497. });
  45498. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  45499. /**
  45500. * Get the count of allocated elements
  45501. * @returns the allocated elements count
  45502. */
  45503. get: function () {
  45504. return this._allEntries.length - this._freeEntries.length;
  45505. },
  45506. enumerable: true,
  45507. configurable: true
  45508. });
  45509. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  45510. /**
  45511. * Return the size of one element in float
  45512. * @returns the size in float
  45513. */
  45514. get: function () {
  45515. return this._stride;
  45516. },
  45517. enumerable: true,
  45518. configurable: true
  45519. });
  45520. DynamicFloatArray.prototype.sort = function () {
  45521. var _this = this;
  45522. if (!this.compareValueOffset) {
  45523. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  45524. }
  45525. var count = this.usedElementCount;
  45526. // Do we have to (re)create the sort table?
  45527. if (!this._sortTable || this._sortTable.length < count) {
  45528. // 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...
  45529. var newCount = Math.min(this.totalElementCount, count * 2);
  45530. this._sortTable = new Array(newCount);
  45531. }
  45532. if (!this._sortedTable || this._sortedTable.length !== count) {
  45533. this._sortedTable = new Array(count);
  45534. }
  45535. // Because, you know...
  45536. this.pack();
  45537. //let stride = this.stride;
  45538. //for (let i = 0; i < count; i++) {
  45539. // let si = this._sortTable[i];
  45540. // if (!si) {
  45541. // si = new SortInfo();
  45542. // this._sortTable[i] = si;
  45543. // }
  45544. // si.entry = this._allEntries[i];
  45545. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  45546. // si.swapedOffset = null;
  45547. // this._sortedTable[i] = si;
  45548. //}
  45549. var curOffset = 0;
  45550. var stride = this.stride;
  45551. for (var i = 0; i < count; i++, curOffset += stride) {
  45552. var si = this._sortTable[i];
  45553. if (!si) {
  45554. si = new SortInfo();
  45555. this._sortTable[i] = si;
  45556. }
  45557. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  45558. si.offset = curOffset;
  45559. si.swapedOffset = null;
  45560. this._sortedTable[i] = si;
  45561. }
  45562. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  45563. if (this.sortingAscending) {
  45564. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  45565. }
  45566. else {
  45567. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  45568. }
  45569. var swapElements = function (src, dst) {
  45570. for (var i = 0; i < stride; i++) {
  45571. var tps = _this.buffer[dst + i];
  45572. _this.buffer[dst + i] = _this.buffer[src + i];
  45573. _this.buffer[src + i] = tps;
  45574. }
  45575. };
  45576. // 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:
  45577. // 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),
  45578. // and I still want something with a good algorithm complexity.
  45579. // 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,
  45580. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  45581. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  45582. // 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
  45583. // until we find a SortInfo object without a swapedOffset which means we got the right location
  45584. // 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
  45585. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  45586. for (var i = 0; i < count; i++) {
  45587. // Get the element to move
  45588. var sourceSI = this._sortedTable[i];
  45589. var destSI = this._sortTable[i];
  45590. var sourceOff = sourceSI.offset;
  45591. // If the source changed location, find the new one
  45592. if (sourceSI.swapedOffset) {
  45593. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  45594. var curSI = sourceSI;
  45595. while (curSI.swapedOffset) {
  45596. curSI = this._sortTable[curSI.swapedOffset / stride];
  45597. }
  45598. // Finally get the right location
  45599. sourceOff = curSI.offset;
  45600. }
  45601. // Tag the element being replaced with its new location
  45602. destSI.swapedOffset = sourceOff;
  45603. // Swap elements (only if needed)
  45604. if (sourceOff !== destSI.offset) {
  45605. swapElements(sourceOff, destSI.offset);
  45606. }
  45607. // Update the offset in the corresponding DFAE
  45608. //sourceSI.entry.offset = destSI.entry.offset;
  45609. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  45610. }
  45611. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45612. return true;
  45613. };
  45614. return DynamicFloatArray;
  45615. }());
  45616. BABYLON.DynamicFloatArray = DynamicFloatArray;
  45617. var SortInfo = (function () {
  45618. function SortInfo() {
  45619. this.compareData = this.offset = this.swapedOffset = null;
  45620. }
  45621. return SortInfo;
  45622. }());
  45623. })(BABYLON || (BABYLON = {}));
  45624. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  45625. var BABYLON;
  45626. (function (BABYLON) {
  45627. var Condition = (function () {
  45628. function Condition(actionManager) {
  45629. this._actionManager = actionManager;
  45630. }
  45631. Condition.prototype.isValid = function () {
  45632. return true;
  45633. };
  45634. Condition.prototype._getProperty = function (propertyPath) {
  45635. return this._actionManager._getProperty(propertyPath);
  45636. };
  45637. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  45638. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45639. };
  45640. Condition.prototype.serialize = function () {
  45641. };
  45642. Condition.prototype._serialize = function (serializedCondition) {
  45643. return {
  45644. type: 2,
  45645. children: [],
  45646. name: serializedCondition.name,
  45647. properties: serializedCondition.properties
  45648. };
  45649. };
  45650. return Condition;
  45651. }());
  45652. BABYLON.Condition = Condition;
  45653. var ValueCondition = (function (_super) {
  45654. __extends(ValueCondition, _super);
  45655. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  45656. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  45657. var _this = _super.call(this, actionManager) || this;
  45658. _this.propertyPath = propertyPath;
  45659. _this.value = value;
  45660. _this.operator = operator;
  45661. _this._target = target;
  45662. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  45663. _this._property = _this._getProperty(_this.propertyPath);
  45664. return _this;
  45665. }
  45666. Object.defineProperty(ValueCondition, "IsEqual", {
  45667. get: function () {
  45668. return ValueCondition._IsEqual;
  45669. },
  45670. enumerable: true,
  45671. configurable: true
  45672. });
  45673. Object.defineProperty(ValueCondition, "IsDifferent", {
  45674. get: function () {
  45675. return ValueCondition._IsDifferent;
  45676. },
  45677. enumerable: true,
  45678. configurable: true
  45679. });
  45680. Object.defineProperty(ValueCondition, "IsGreater", {
  45681. get: function () {
  45682. return ValueCondition._IsGreater;
  45683. },
  45684. enumerable: true,
  45685. configurable: true
  45686. });
  45687. Object.defineProperty(ValueCondition, "IsLesser", {
  45688. get: function () {
  45689. return ValueCondition._IsLesser;
  45690. },
  45691. enumerable: true,
  45692. configurable: true
  45693. });
  45694. // Methods
  45695. ValueCondition.prototype.isValid = function () {
  45696. switch (this.operator) {
  45697. case ValueCondition.IsGreater:
  45698. return this._effectiveTarget[this._property] > this.value;
  45699. case ValueCondition.IsLesser:
  45700. return this._effectiveTarget[this._property] < this.value;
  45701. case ValueCondition.IsEqual:
  45702. case ValueCondition.IsDifferent:
  45703. var check;
  45704. if (this.value.equals) {
  45705. check = this.value.equals(this._effectiveTarget[this._property]);
  45706. }
  45707. else {
  45708. check = this.value === this._effectiveTarget[this._property];
  45709. }
  45710. return this.operator === ValueCondition.IsEqual ? check : !check;
  45711. }
  45712. return false;
  45713. };
  45714. ValueCondition.prototype.serialize = function () {
  45715. return this._serialize({
  45716. name: "ValueCondition",
  45717. properties: [
  45718. BABYLON.Action._GetTargetProperty(this._target),
  45719. { name: "propertyPath", value: this.propertyPath },
  45720. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45721. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  45722. ]
  45723. });
  45724. };
  45725. ValueCondition.GetOperatorName = function (operator) {
  45726. switch (operator) {
  45727. case ValueCondition._IsEqual: return "IsEqual";
  45728. case ValueCondition._IsDifferent: return "IsDifferent";
  45729. case ValueCondition._IsGreater: return "IsGreater";
  45730. case ValueCondition._IsLesser: return "IsLesser";
  45731. default: return "";
  45732. }
  45733. };
  45734. // Statics
  45735. ValueCondition._IsEqual = 0;
  45736. ValueCondition._IsDifferent = 1;
  45737. ValueCondition._IsGreater = 2;
  45738. ValueCondition._IsLesser = 3;
  45739. return ValueCondition;
  45740. }(Condition));
  45741. BABYLON.ValueCondition = ValueCondition;
  45742. var PredicateCondition = (function (_super) {
  45743. __extends(PredicateCondition, _super);
  45744. function PredicateCondition(actionManager, predicate) {
  45745. var _this = _super.call(this, actionManager) || this;
  45746. _this.predicate = predicate;
  45747. return _this;
  45748. }
  45749. PredicateCondition.prototype.isValid = function () {
  45750. return this.predicate();
  45751. };
  45752. return PredicateCondition;
  45753. }(Condition));
  45754. BABYLON.PredicateCondition = PredicateCondition;
  45755. var StateCondition = (function (_super) {
  45756. __extends(StateCondition, _super);
  45757. function StateCondition(actionManager, target, value) {
  45758. var _this = _super.call(this, actionManager) || this;
  45759. _this.value = value;
  45760. _this._target = target;
  45761. return _this;
  45762. }
  45763. // Methods
  45764. StateCondition.prototype.isValid = function () {
  45765. return this._target.state === this.value;
  45766. };
  45767. StateCondition.prototype.serialize = function () {
  45768. return this._serialize({
  45769. name: "StateCondition",
  45770. properties: [
  45771. BABYLON.Action._GetTargetProperty(this._target),
  45772. { name: "value", value: this.value }
  45773. ]
  45774. });
  45775. };
  45776. return StateCondition;
  45777. }(Condition));
  45778. BABYLON.StateCondition = StateCondition;
  45779. })(BABYLON || (BABYLON = {}));
  45780. //# sourceMappingURL=babylon.condition.js.map
  45781. var BABYLON;
  45782. (function (BABYLON) {
  45783. var Action = (function () {
  45784. function Action(triggerOptions, condition) {
  45785. this.triggerOptions = triggerOptions;
  45786. if (triggerOptions.parameter) {
  45787. this.trigger = triggerOptions.trigger;
  45788. this._triggerParameter = triggerOptions.parameter;
  45789. }
  45790. else {
  45791. this.trigger = triggerOptions;
  45792. }
  45793. this._nextActiveAction = this;
  45794. this._condition = condition;
  45795. }
  45796. // Methods
  45797. Action.prototype._prepare = function () {
  45798. };
  45799. Action.prototype.getTriggerParameter = function () {
  45800. return this._triggerParameter;
  45801. };
  45802. Action.prototype._executeCurrent = function (evt) {
  45803. if (this._nextActiveAction._condition) {
  45804. var condition = this._nextActiveAction._condition;
  45805. var currentRenderId = this._actionManager.getScene().getRenderId();
  45806. // We cache the current evaluation for the current frame
  45807. if (condition._evaluationId === currentRenderId) {
  45808. if (!condition._currentResult) {
  45809. return;
  45810. }
  45811. }
  45812. else {
  45813. condition._evaluationId = currentRenderId;
  45814. if (!condition.isValid()) {
  45815. condition._currentResult = false;
  45816. return;
  45817. }
  45818. condition._currentResult = true;
  45819. }
  45820. }
  45821. this._nextActiveAction.execute(evt);
  45822. this.skipToNextActiveAction();
  45823. };
  45824. Action.prototype.execute = function (evt) {
  45825. };
  45826. Action.prototype.skipToNextActiveAction = function () {
  45827. if (this._nextActiveAction._child) {
  45828. if (!this._nextActiveAction._child._actionManager) {
  45829. this._nextActiveAction._child._actionManager = this._actionManager;
  45830. }
  45831. this._nextActiveAction = this._nextActiveAction._child;
  45832. }
  45833. else {
  45834. this._nextActiveAction = this;
  45835. }
  45836. };
  45837. Action.prototype.then = function (action) {
  45838. this._child = action;
  45839. action._actionManager = this._actionManager;
  45840. action._prepare();
  45841. return action;
  45842. };
  45843. Action.prototype._getProperty = function (propertyPath) {
  45844. return this._actionManager._getProperty(propertyPath);
  45845. };
  45846. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  45847. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45848. };
  45849. Action.prototype.serialize = function (parent) {
  45850. };
  45851. // Called by BABYLON.Action objects in serialize(...). Internal use
  45852. Action.prototype._serialize = function (serializedAction, parent) {
  45853. var serializationObject = {
  45854. type: 1,
  45855. children: [],
  45856. name: serializedAction.name,
  45857. properties: serializedAction.properties || []
  45858. };
  45859. // Serialize child
  45860. if (this._child) {
  45861. this._child.serialize(serializationObject);
  45862. }
  45863. // Check if "this" has a condition
  45864. if (this._condition) {
  45865. var serializedCondition = this._condition.serialize();
  45866. serializedCondition.children.push(serializationObject);
  45867. if (parent) {
  45868. parent.children.push(serializedCondition);
  45869. }
  45870. return serializedCondition;
  45871. }
  45872. if (parent) {
  45873. parent.children.push(serializationObject);
  45874. }
  45875. return serializationObject;
  45876. };
  45877. Action._SerializeValueAsString = function (value) {
  45878. if (typeof value === "number") {
  45879. return value.toString();
  45880. }
  45881. if (typeof value === "boolean") {
  45882. return value ? "true" : "false";
  45883. }
  45884. if (value instanceof BABYLON.Vector2) {
  45885. return value.x + ", " + value.y;
  45886. }
  45887. if (value instanceof BABYLON.Vector3) {
  45888. return value.x + ", " + value.y + ", " + value.z;
  45889. }
  45890. if (value instanceof BABYLON.Color3) {
  45891. return value.r + ", " + value.g + ", " + value.b;
  45892. }
  45893. if (value instanceof BABYLON.Color4) {
  45894. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  45895. }
  45896. return value; // string
  45897. };
  45898. Action._GetTargetProperty = function (target) {
  45899. return {
  45900. name: "target",
  45901. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  45902. : target instanceof BABYLON.Light ? "LightProperties"
  45903. : target instanceof BABYLON.Camera ? "CameraProperties"
  45904. : "SceneProperties",
  45905. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  45906. };
  45907. };
  45908. return Action;
  45909. }());
  45910. BABYLON.Action = Action;
  45911. })(BABYLON || (BABYLON = {}));
  45912. //# sourceMappingURL=babylon.action.js.map
  45913. var BABYLON;
  45914. (function (BABYLON) {
  45915. /**
  45916. * ActionEvent is the event beint sent when an action is triggered.
  45917. */
  45918. var ActionEvent = (function () {
  45919. /**
  45920. * @param source The mesh or sprite that triggered the action.
  45921. * @param pointerX The X mouse cursor position at the time of the event
  45922. * @param pointerY The Y mouse cursor position at the time of the event
  45923. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  45924. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  45925. */
  45926. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  45927. this.source = source;
  45928. this.pointerX = pointerX;
  45929. this.pointerY = pointerY;
  45930. this.meshUnderPointer = meshUnderPointer;
  45931. this.sourceEvent = sourceEvent;
  45932. this.additionalData = additionalData;
  45933. }
  45934. /**
  45935. * Helper function to auto-create an ActionEvent from a source mesh.
  45936. * @param source The source mesh that triggered the event
  45937. * @param evt {Event} The original (browser) event
  45938. */
  45939. ActionEvent.CreateNew = function (source, evt, additionalData) {
  45940. var scene = source.getScene();
  45941. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45942. };
  45943. /**
  45944. * Helper function to auto-create an ActionEvent from a source mesh.
  45945. * @param source The source sprite that triggered the event
  45946. * @param scene Scene associated with the sprite
  45947. * @param evt {Event} The original (browser) event
  45948. */
  45949. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  45950. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45951. };
  45952. /**
  45953. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  45954. * @param scene the scene where the event occurred
  45955. * @param evt {Event} The original (browser) event
  45956. */
  45957. ActionEvent.CreateNewFromScene = function (scene, evt) {
  45958. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  45959. };
  45960. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  45961. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  45962. };
  45963. return ActionEvent;
  45964. }());
  45965. BABYLON.ActionEvent = ActionEvent;
  45966. /**
  45967. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  45968. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  45969. */
  45970. var ActionManager = (function () {
  45971. function ActionManager(scene) {
  45972. // Members
  45973. this.actions = new Array();
  45974. this.hoverCursor = '';
  45975. this._scene = scene;
  45976. scene._actionManagers.push(this);
  45977. }
  45978. Object.defineProperty(ActionManager, "NothingTrigger", {
  45979. get: function () {
  45980. return ActionManager._NothingTrigger;
  45981. },
  45982. enumerable: true,
  45983. configurable: true
  45984. });
  45985. Object.defineProperty(ActionManager, "OnPickTrigger", {
  45986. get: function () {
  45987. return ActionManager._OnPickTrigger;
  45988. },
  45989. enumerable: true,
  45990. configurable: true
  45991. });
  45992. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  45993. get: function () {
  45994. return ActionManager._OnLeftPickTrigger;
  45995. },
  45996. enumerable: true,
  45997. configurable: true
  45998. });
  45999. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  46000. get: function () {
  46001. return ActionManager._OnRightPickTrigger;
  46002. },
  46003. enumerable: true,
  46004. configurable: true
  46005. });
  46006. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  46007. get: function () {
  46008. return ActionManager._OnCenterPickTrigger;
  46009. },
  46010. enumerable: true,
  46011. configurable: true
  46012. });
  46013. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  46014. get: function () {
  46015. return ActionManager._OnPickDownTrigger;
  46016. },
  46017. enumerable: true,
  46018. configurable: true
  46019. });
  46020. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  46021. get: function () {
  46022. return ActionManager._OnDoublePickTrigger;
  46023. },
  46024. enumerable: true,
  46025. configurable: true
  46026. });
  46027. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  46028. get: function () {
  46029. return ActionManager._OnPickUpTrigger;
  46030. },
  46031. enumerable: true,
  46032. configurable: true
  46033. });
  46034. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  46035. /// This trigger will only be raised if you also declared a OnPickDown
  46036. get: function () {
  46037. return ActionManager._OnPickOutTrigger;
  46038. },
  46039. enumerable: true,
  46040. configurable: true
  46041. });
  46042. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  46043. get: function () {
  46044. return ActionManager._OnLongPressTrigger;
  46045. },
  46046. enumerable: true,
  46047. configurable: true
  46048. });
  46049. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  46050. get: function () {
  46051. return ActionManager._OnPointerOverTrigger;
  46052. },
  46053. enumerable: true,
  46054. configurable: true
  46055. });
  46056. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  46057. get: function () {
  46058. return ActionManager._OnPointerOutTrigger;
  46059. },
  46060. enumerable: true,
  46061. configurable: true
  46062. });
  46063. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  46064. get: function () {
  46065. return ActionManager._OnEveryFrameTrigger;
  46066. },
  46067. enumerable: true,
  46068. configurable: true
  46069. });
  46070. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  46071. get: function () {
  46072. return ActionManager._OnIntersectionEnterTrigger;
  46073. },
  46074. enumerable: true,
  46075. configurable: true
  46076. });
  46077. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  46078. get: function () {
  46079. return ActionManager._OnIntersectionExitTrigger;
  46080. },
  46081. enumerable: true,
  46082. configurable: true
  46083. });
  46084. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  46085. get: function () {
  46086. return ActionManager._OnKeyDownTrigger;
  46087. },
  46088. enumerable: true,
  46089. configurable: true
  46090. });
  46091. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  46092. get: function () {
  46093. return ActionManager._OnKeyUpTrigger;
  46094. },
  46095. enumerable: true,
  46096. configurable: true
  46097. });
  46098. // Methods
  46099. ActionManager.prototype.dispose = function () {
  46100. var index = this._scene._actionManagers.indexOf(this);
  46101. for (var i = 0; i < this.actions.length; i++) {
  46102. var action = this.actions[i];
  46103. ActionManager.Triggers[action.trigger]--;
  46104. if (ActionManager.Triggers[action.trigger] === 0) {
  46105. delete ActionManager.Triggers[action.trigger];
  46106. }
  46107. }
  46108. if (index > -1) {
  46109. this._scene._actionManagers.splice(index, 1);
  46110. }
  46111. };
  46112. ActionManager.prototype.getScene = function () {
  46113. return this._scene;
  46114. };
  46115. /**
  46116. * Does this action manager handles actions of any of the given triggers
  46117. * @param {number[]} triggers - the triggers to be tested
  46118. * @return {boolean} whether one (or more) of the triggers is handeled
  46119. */
  46120. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  46121. for (var index = 0; index < this.actions.length; index++) {
  46122. var action = this.actions[index];
  46123. if (triggers.indexOf(action.trigger) > -1) {
  46124. return true;
  46125. }
  46126. }
  46127. return false;
  46128. };
  46129. /**
  46130. * Does this action manager handles actions of a given trigger
  46131. * @param {number} trigger - the trigger to be tested
  46132. * @return {boolean} whether the trigger is handeled
  46133. */
  46134. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  46135. for (var index = 0; index < this.actions.length; index++) {
  46136. var action = this.actions[index];
  46137. if (action.trigger === trigger) {
  46138. return true;
  46139. }
  46140. }
  46141. return false;
  46142. };
  46143. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  46144. /**
  46145. * Does this action manager has pointer triggers
  46146. * @return {boolean} whether or not it has pointer triggers
  46147. */
  46148. get: function () {
  46149. for (var index = 0; index < this.actions.length; index++) {
  46150. var action = this.actions[index];
  46151. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  46152. return true;
  46153. }
  46154. }
  46155. return false;
  46156. },
  46157. enumerable: true,
  46158. configurable: true
  46159. });
  46160. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  46161. /**
  46162. * Does this action manager has pick triggers
  46163. * @return {boolean} whether or not it has pick triggers
  46164. */
  46165. get: function () {
  46166. for (var index = 0; index < this.actions.length; index++) {
  46167. var action = this.actions[index];
  46168. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  46169. return true;
  46170. }
  46171. }
  46172. return false;
  46173. },
  46174. enumerable: true,
  46175. configurable: true
  46176. });
  46177. Object.defineProperty(ActionManager, "HasTriggers", {
  46178. /**
  46179. * Does exist one action manager with at least one trigger
  46180. * @return {boolean} whether or not it exists one action manager with one trigger
  46181. **/
  46182. get: function () {
  46183. for (var t in ActionManager.Triggers) {
  46184. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46185. return true;
  46186. }
  46187. }
  46188. return false;
  46189. },
  46190. enumerable: true,
  46191. configurable: true
  46192. });
  46193. Object.defineProperty(ActionManager, "HasPickTriggers", {
  46194. /**
  46195. * Does exist one action manager with at least one pick trigger
  46196. * @return {boolean} whether or not it exists one action manager with one pick trigger
  46197. **/
  46198. get: function () {
  46199. for (var t in ActionManager.Triggers) {
  46200. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46201. var t_int = parseInt(t);
  46202. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  46203. return true;
  46204. }
  46205. }
  46206. }
  46207. return false;
  46208. },
  46209. enumerable: true,
  46210. configurable: true
  46211. });
  46212. /**
  46213. * Does exist one action manager that handles actions of a given trigger
  46214. * @param {number} trigger - the trigger to be tested
  46215. * @return {boolean} whether the trigger is handeled by at least one action manager
  46216. **/
  46217. ActionManager.HasSpecificTrigger = function (trigger) {
  46218. for (var t in ActionManager.Triggers) {
  46219. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46220. var t_int = parseInt(t);
  46221. if (t_int === trigger) {
  46222. return true;
  46223. }
  46224. }
  46225. }
  46226. return false;
  46227. };
  46228. /**
  46229. * Registers an action to this action manager
  46230. * @param {BABYLON.Action} action - the action to be registered
  46231. * @return {BABYLON.Action} the action amended (prepared) after registration
  46232. */
  46233. ActionManager.prototype.registerAction = function (action) {
  46234. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46235. if (this.getScene().actionManager !== this) {
  46236. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46237. return null;
  46238. }
  46239. }
  46240. this.actions.push(action);
  46241. if (ActionManager.Triggers[action.trigger]) {
  46242. ActionManager.Triggers[action.trigger]++;
  46243. }
  46244. else {
  46245. ActionManager.Triggers[action.trigger] = 1;
  46246. }
  46247. action._actionManager = this;
  46248. action._prepare();
  46249. return action;
  46250. };
  46251. /**
  46252. * Process a specific trigger
  46253. * @param {number} trigger - the trigger to process
  46254. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46255. */
  46256. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46257. for (var index = 0; index < this.actions.length; index++) {
  46258. var action = this.actions[index];
  46259. if (action.trigger === trigger) {
  46260. if (trigger === ActionManager.OnKeyUpTrigger
  46261. || trigger === ActionManager.OnKeyDownTrigger) {
  46262. var parameter = action.getTriggerParameter();
  46263. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46264. if (!parameter.toLowerCase) {
  46265. continue;
  46266. }
  46267. var lowerCase = parameter.toLowerCase();
  46268. if (lowerCase !== evt.sourceEvent.key) {
  46269. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46270. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46271. if (actualkey !== lowerCase) {
  46272. continue;
  46273. }
  46274. }
  46275. }
  46276. }
  46277. action._executeCurrent(evt);
  46278. }
  46279. }
  46280. };
  46281. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46282. var properties = propertyPath.split(".");
  46283. for (var index = 0; index < properties.length - 1; index++) {
  46284. target = target[properties[index]];
  46285. }
  46286. return target;
  46287. };
  46288. ActionManager.prototype._getProperty = function (propertyPath) {
  46289. var properties = propertyPath.split(".");
  46290. return properties[properties.length - 1];
  46291. };
  46292. ActionManager.prototype.serialize = function (name) {
  46293. var root = {
  46294. children: [],
  46295. name: name,
  46296. type: 3,
  46297. properties: [] // Empty for root but required
  46298. };
  46299. for (var i = 0; i < this.actions.length; i++) {
  46300. var triggerObject = {
  46301. type: 0,
  46302. children: [],
  46303. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46304. properties: []
  46305. };
  46306. var triggerOptions = this.actions[i].triggerOptions;
  46307. if (triggerOptions && typeof triggerOptions !== "number") {
  46308. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46309. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46310. }
  46311. else {
  46312. var parameter = {};
  46313. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46314. if (triggerOptions.parameter.mesh) {
  46315. parameter._meshId = triggerOptions.parameter.mesh.id;
  46316. }
  46317. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46318. }
  46319. }
  46320. // Serialize child action, recursively
  46321. this.actions[i].serialize(triggerObject);
  46322. // Add serialized trigger
  46323. root.children.push(triggerObject);
  46324. }
  46325. return root;
  46326. };
  46327. ActionManager.Parse = function (parsedActions, object, scene) {
  46328. var actionManager = new BABYLON.ActionManager(scene);
  46329. if (object === null)
  46330. scene.actionManager = actionManager;
  46331. else
  46332. object.actionManager = actionManager;
  46333. // instanciate a new object
  46334. var instanciate = function (name, params) {
  46335. var newInstance = Object.create(BABYLON[name].prototype);
  46336. newInstance.constructor.apply(newInstance, params);
  46337. return newInstance;
  46338. };
  46339. var parseParameter = function (name, value, target, propertyPath) {
  46340. if (propertyPath === null) {
  46341. // String, boolean or float
  46342. var floatValue = parseFloat(value);
  46343. if (value === "true" || value === "false")
  46344. return value === "true";
  46345. else
  46346. return isNaN(floatValue) ? value : floatValue;
  46347. }
  46348. var effectiveTarget = propertyPath.split(".");
  46349. var values = value.split(",");
  46350. // Get effective Target
  46351. for (var i = 0; i < effectiveTarget.length; i++) {
  46352. target = target[effectiveTarget[i]];
  46353. }
  46354. // Return appropriate value with its type
  46355. if (typeof (target) === "boolean")
  46356. return values[0] === "true";
  46357. if (typeof (target) === "string")
  46358. return values[0];
  46359. // Parameters with multiple values such as Vector3 etc.
  46360. var split = new Array();
  46361. for (var i = 0; i < values.length; i++)
  46362. split.push(parseFloat(values[i]));
  46363. if (target instanceof BABYLON.Vector3)
  46364. return BABYLON.Vector3.FromArray(split);
  46365. if (target instanceof BABYLON.Vector4)
  46366. return BABYLON.Vector4.FromArray(split);
  46367. if (target instanceof BABYLON.Color3)
  46368. return BABYLON.Color3.FromArray(split);
  46369. if (target instanceof BABYLON.Color4)
  46370. return BABYLON.Color4.FromArray(split);
  46371. return parseFloat(values[0]);
  46372. };
  46373. // traverse graph per trigger
  46374. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46375. if (combineArray === void 0) { combineArray = null; }
  46376. if (parsedAction.detached)
  46377. return;
  46378. var parameters = new Array();
  46379. var target = null;
  46380. var propertyPath = null;
  46381. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46382. // Parameters
  46383. if (parsedAction.type === 2)
  46384. parameters.push(actionManager);
  46385. else
  46386. parameters.push(trigger);
  46387. if (combine) {
  46388. var actions = new Array();
  46389. for (var j = 0; j < parsedAction.combine.length; j++) {
  46390. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46391. }
  46392. parameters.push(actions);
  46393. }
  46394. else {
  46395. for (var i = 0; i < parsedAction.properties.length; i++) {
  46396. var value = parsedAction.properties[i].value;
  46397. var name = parsedAction.properties[i].name;
  46398. var targetType = parsedAction.properties[i].targetType;
  46399. if (name === "target")
  46400. if (targetType !== null && targetType === "SceneProperties")
  46401. value = target = scene;
  46402. else
  46403. value = target = scene.getNodeByName(value);
  46404. else if (name === "parent")
  46405. value = scene.getNodeByName(value);
  46406. else if (name === "sound")
  46407. value = scene.getSoundByName(value);
  46408. else if (name !== "propertyPath") {
  46409. if (parsedAction.type === 2 && name === "operator")
  46410. value = BABYLON.ValueCondition[value];
  46411. else
  46412. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46413. }
  46414. else {
  46415. propertyPath = value;
  46416. }
  46417. parameters.push(value);
  46418. }
  46419. }
  46420. if (combineArray === null) {
  46421. parameters.push(condition);
  46422. }
  46423. else {
  46424. parameters.push(null);
  46425. }
  46426. // If interpolate value action
  46427. if (parsedAction.name === "InterpolateValueAction") {
  46428. var param = parameters[parameters.length - 2];
  46429. parameters[parameters.length - 1] = param;
  46430. parameters[parameters.length - 2] = condition;
  46431. }
  46432. // Action or condition(s) and not CombineAction
  46433. var newAction = instanciate(parsedAction.name, parameters);
  46434. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46435. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46436. if (action)
  46437. action.then(nothing);
  46438. else
  46439. actionManager.registerAction(nothing);
  46440. action = nothing;
  46441. }
  46442. if (combineArray === null) {
  46443. if (newAction instanceof BABYLON.Condition) {
  46444. condition = newAction;
  46445. newAction = action;
  46446. }
  46447. else {
  46448. condition = null;
  46449. if (action)
  46450. action.then(newAction);
  46451. else
  46452. actionManager.registerAction(newAction);
  46453. }
  46454. }
  46455. else {
  46456. combineArray.push(newAction);
  46457. }
  46458. for (var i = 0; i < parsedAction.children.length; i++)
  46459. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46460. };
  46461. // triggers
  46462. for (var i = 0; i < parsedActions.children.length; i++) {
  46463. var triggerParams;
  46464. var trigger = parsedActions.children[i];
  46465. if (trigger.properties.length > 0) {
  46466. var param = trigger.properties[0].value;
  46467. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46468. if (value._meshId) {
  46469. value.mesh = scene.getMeshByID(value._meshId);
  46470. }
  46471. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  46472. }
  46473. else
  46474. triggerParams = BABYLON.ActionManager[trigger.name];
  46475. for (var j = 0; j < trigger.children.length; j++) {
  46476. if (!trigger.detached)
  46477. traverse(trigger.children[j], triggerParams, null, null);
  46478. }
  46479. }
  46480. };
  46481. ActionManager.GetTriggerName = function (trigger) {
  46482. switch (trigger) {
  46483. case 0: return "NothingTrigger";
  46484. case 1: return "OnPickTrigger";
  46485. case 2: return "OnLeftPickTrigger";
  46486. case 3: return "OnRightPickTrigger";
  46487. case 4: return "OnCenterPickTrigger";
  46488. case 5: return "OnPickDownTrigger";
  46489. case 6: return "OnPickUpTrigger";
  46490. case 7: return "OnLongPressTrigger";
  46491. case 8: return "OnPointerOverTrigger";
  46492. case 9: return "OnPointerOutTrigger";
  46493. case 10: return "OnEveryFrameTrigger";
  46494. case 11: return "OnIntersectionEnterTrigger";
  46495. case 12: return "OnIntersectionExitTrigger";
  46496. case 13: return "OnKeyDownTrigger";
  46497. case 14: return "OnKeyUpTrigger";
  46498. case 15: return "OnPickOutTrigger";
  46499. default: return "";
  46500. }
  46501. };
  46502. // Statics
  46503. ActionManager._NothingTrigger = 0;
  46504. ActionManager._OnPickTrigger = 1;
  46505. ActionManager._OnLeftPickTrigger = 2;
  46506. ActionManager._OnRightPickTrigger = 3;
  46507. ActionManager._OnCenterPickTrigger = 4;
  46508. ActionManager._OnPickDownTrigger = 5;
  46509. ActionManager._OnDoublePickTrigger = 6;
  46510. ActionManager._OnPickUpTrigger = 7;
  46511. ActionManager._OnLongPressTrigger = 8;
  46512. ActionManager._OnPointerOverTrigger = 9;
  46513. ActionManager._OnPointerOutTrigger = 10;
  46514. ActionManager._OnEveryFrameTrigger = 11;
  46515. ActionManager._OnIntersectionEnterTrigger = 12;
  46516. ActionManager._OnIntersectionExitTrigger = 13;
  46517. ActionManager._OnKeyDownTrigger = 14;
  46518. ActionManager._OnKeyUpTrigger = 15;
  46519. ActionManager._OnPickOutTrigger = 16;
  46520. ActionManager.Triggers = {};
  46521. return ActionManager;
  46522. }());
  46523. BABYLON.ActionManager = ActionManager;
  46524. })(BABYLON || (BABYLON = {}));
  46525. //# sourceMappingURL=babylon.actionManager.js.map
  46526. var BABYLON;
  46527. (function (BABYLON) {
  46528. var InterpolateValueAction = (function (_super) {
  46529. __extends(InterpolateValueAction, _super);
  46530. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46531. if (duration === void 0) { duration = 1000; }
  46532. var _this = _super.call(this, triggerOptions, condition) || this;
  46533. _this.propertyPath = propertyPath;
  46534. _this.value = value;
  46535. _this.duration = duration;
  46536. _this.stopOtherAnimations = stopOtherAnimations;
  46537. _this.onInterpolationDone = onInterpolationDone;
  46538. _this._target = _this._effectiveTarget = target;
  46539. return _this;
  46540. }
  46541. InterpolateValueAction.prototype._prepare = function () {
  46542. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46543. this._property = this._getProperty(this.propertyPath);
  46544. };
  46545. InterpolateValueAction.prototype.execute = function () {
  46546. var scene = this._actionManager.getScene();
  46547. var keys = [
  46548. {
  46549. frame: 0,
  46550. value: this._effectiveTarget[this._property]
  46551. }, {
  46552. frame: 100,
  46553. value: this.value
  46554. }
  46555. ];
  46556. var dataType;
  46557. if (typeof this.value === "number") {
  46558. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46559. }
  46560. else if (this.value instanceof BABYLON.Color3) {
  46561. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46562. }
  46563. else if (this.value instanceof BABYLON.Vector3) {
  46564. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46565. }
  46566. else if (this.value instanceof BABYLON.Matrix) {
  46567. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46568. }
  46569. else if (this.value instanceof BABYLON.Quaternion) {
  46570. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  46571. }
  46572. else {
  46573. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  46574. return;
  46575. }
  46576. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  46577. animation.setKeys(keys);
  46578. if (this.stopOtherAnimations) {
  46579. scene.stopAnimation(this._effectiveTarget);
  46580. }
  46581. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  46582. };
  46583. InterpolateValueAction.prototype.serialize = function (parent) {
  46584. return _super.prototype._serialize.call(this, {
  46585. name: "InterpolateValueAction",
  46586. properties: [
  46587. BABYLON.Action._GetTargetProperty(this._target),
  46588. { name: "propertyPath", value: this.propertyPath },
  46589. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46590. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  46591. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  46592. ]
  46593. }, parent);
  46594. };
  46595. return InterpolateValueAction;
  46596. }(BABYLON.Action));
  46597. BABYLON.InterpolateValueAction = InterpolateValueAction;
  46598. })(BABYLON || (BABYLON = {}));
  46599. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  46600. var BABYLON;
  46601. (function (BABYLON) {
  46602. var SwitchBooleanAction = (function (_super) {
  46603. __extends(SwitchBooleanAction, _super);
  46604. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  46605. var _this = _super.call(this, triggerOptions, condition) || this;
  46606. _this.propertyPath = propertyPath;
  46607. _this._target = _this._effectiveTarget = target;
  46608. return _this;
  46609. }
  46610. SwitchBooleanAction.prototype._prepare = function () {
  46611. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46612. this._property = this._getProperty(this.propertyPath);
  46613. };
  46614. SwitchBooleanAction.prototype.execute = function () {
  46615. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  46616. };
  46617. SwitchBooleanAction.prototype.serialize = function (parent) {
  46618. return _super.prototype._serialize.call(this, {
  46619. name: "SwitchBooleanAction",
  46620. properties: [
  46621. BABYLON.Action._GetTargetProperty(this._target),
  46622. { name: "propertyPath", value: this.propertyPath }
  46623. ]
  46624. }, parent);
  46625. };
  46626. return SwitchBooleanAction;
  46627. }(BABYLON.Action));
  46628. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  46629. var SetStateAction = (function (_super) {
  46630. __extends(SetStateAction, _super);
  46631. function SetStateAction(triggerOptions, target, value, condition) {
  46632. var _this = _super.call(this, triggerOptions, condition) || this;
  46633. _this.value = value;
  46634. _this._target = target;
  46635. return _this;
  46636. }
  46637. SetStateAction.prototype.execute = function () {
  46638. this._target.state = this.value;
  46639. };
  46640. SetStateAction.prototype.serialize = function (parent) {
  46641. return _super.prototype._serialize.call(this, {
  46642. name: "SetStateAction",
  46643. properties: [
  46644. BABYLON.Action._GetTargetProperty(this._target),
  46645. { name: "value", value: this.value }
  46646. ]
  46647. }, parent);
  46648. };
  46649. return SetStateAction;
  46650. }(BABYLON.Action));
  46651. BABYLON.SetStateAction = SetStateAction;
  46652. var SetValueAction = (function (_super) {
  46653. __extends(SetValueAction, _super);
  46654. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  46655. var _this = _super.call(this, triggerOptions, condition) || this;
  46656. _this.propertyPath = propertyPath;
  46657. _this.value = value;
  46658. _this._target = _this._effectiveTarget = target;
  46659. return _this;
  46660. }
  46661. SetValueAction.prototype._prepare = function () {
  46662. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46663. this._property = this._getProperty(this.propertyPath);
  46664. };
  46665. SetValueAction.prototype.execute = function () {
  46666. this._effectiveTarget[this._property] = this.value;
  46667. if (this._target.markAsDirty) {
  46668. this._target.markAsDirty(this._property);
  46669. }
  46670. };
  46671. SetValueAction.prototype.serialize = function (parent) {
  46672. return _super.prototype._serialize.call(this, {
  46673. name: "SetValueAction",
  46674. properties: [
  46675. BABYLON.Action._GetTargetProperty(this._target),
  46676. { name: "propertyPath", value: this.propertyPath },
  46677. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46678. ]
  46679. }, parent);
  46680. };
  46681. return SetValueAction;
  46682. }(BABYLON.Action));
  46683. BABYLON.SetValueAction = SetValueAction;
  46684. var IncrementValueAction = (function (_super) {
  46685. __extends(IncrementValueAction, _super);
  46686. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  46687. var _this = _super.call(this, triggerOptions, condition) || this;
  46688. _this.propertyPath = propertyPath;
  46689. _this.value = value;
  46690. _this._target = _this._effectiveTarget = target;
  46691. return _this;
  46692. }
  46693. IncrementValueAction.prototype._prepare = function () {
  46694. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46695. this._property = this._getProperty(this.propertyPath);
  46696. if (typeof this._effectiveTarget[this._property] !== "number") {
  46697. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  46698. }
  46699. };
  46700. IncrementValueAction.prototype.execute = function () {
  46701. this._effectiveTarget[this._property] += this.value;
  46702. if (this._target.markAsDirty) {
  46703. this._target.markAsDirty(this._property);
  46704. }
  46705. };
  46706. IncrementValueAction.prototype.serialize = function (parent) {
  46707. return _super.prototype._serialize.call(this, {
  46708. name: "IncrementValueAction",
  46709. properties: [
  46710. BABYLON.Action._GetTargetProperty(this._target),
  46711. { name: "propertyPath", value: this.propertyPath },
  46712. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46713. ]
  46714. }, parent);
  46715. };
  46716. return IncrementValueAction;
  46717. }(BABYLON.Action));
  46718. BABYLON.IncrementValueAction = IncrementValueAction;
  46719. var PlayAnimationAction = (function (_super) {
  46720. __extends(PlayAnimationAction, _super);
  46721. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  46722. var _this = _super.call(this, triggerOptions, condition) || this;
  46723. _this.from = from;
  46724. _this.to = to;
  46725. _this.loop = loop;
  46726. _this._target = target;
  46727. return _this;
  46728. }
  46729. PlayAnimationAction.prototype._prepare = function () {
  46730. };
  46731. PlayAnimationAction.prototype.execute = function () {
  46732. var scene = this._actionManager.getScene();
  46733. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  46734. };
  46735. PlayAnimationAction.prototype.serialize = function (parent) {
  46736. return _super.prototype._serialize.call(this, {
  46737. name: "PlayAnimationAction",
  46738. properties: [
  46739. BABYLON.Action._GetTargetProperty(this._target),
  46740. { name: "from", value: String(this.from) },
  46741. { name: "to", value: String(this.to) },
  46742. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  46743. ]
  46744. }, parent);
  46745. };
  46746. return PlayAnimationAction;
  46747. }(BABYLON.Action));
  46748. BABYLON.PlayAnimationAction = PlayAnimationAction;
  46749. var StopAnimationAction = (function (_super) {
  46750. __extends(StopAnimationAction, _super);
  46751. function StopAnimationAction(triggerOptions, target, condition) {
  46752. var _this = _super.call(this, triggerOptions, condition) || this;
  46753. _this._target = target;
  46754. return _this;
  46755. }
  46756. StopAnimationAction.prototype._prepare = function () {
  46757. };
  46758. StopAnimationAction.prototype.execute = function () {
  46759. var scene = this._actionManager.getScene();
  46760. scene.stopAnimation(this._target);
  46761. };
  46762. StopAnimationAction.prototype.serialize = function (parent) {
  46763. return _super.prototype._serialize.call(this, {
  46764. name: "StopAnimationAction",
  46765. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  46766. }, parent);
  46767. };
  46768. return StopAnimationAction;
  46769. }(BABYLON.Action));
  46770. BABYLON.StopAnimationAction = StopAnimationAction;
  46771. var DoNothingAction = (function (_super) {
  46772. __extends(DoNothingAction, _super);
  46773. function DoNothingAction(triggerOptions, condition) {
  46774. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  46775. return _super.call(this, triggerOptions, condition) || this;
  46776. }
  46777. DoNothingAction.prototype.execute = function () {
  46778. };
  46779. DoNothingAction.prototype.serialize = function (parent) {
  46780. return _super.prototype._serialize.call(this, {
  46781. name: "DoNothingAction",
  46782. properties: []
  46783. }, parent);
  46784. };
  46785. return DoNothingAction;
  46786. }(BABYLON.Action));
  46787. BABYLON.DoNothingAction = DoNothingAction;
  46788. var CombineAction = (function (_super) {
  46789. __extends(CombineAction, _super);
  46790. function CombineAction(triggerOptions, children, condition) {
  46791. var _this = _super.call(this, triggerOptions, condition) || this;
  46792. _this.children = children;
  46793. return _this;
  46794. }
  46795. CombineAction.prototype._prepare = function () {
  46796. for (var index = 0; index < this.children.length; index++) {
  46797. this.children[index]._actionManager = this._actionManager;
  46798. this.children[index]._prepare();
  46799. }
  46800. };
  46801. CombineAction.prototype.execute = function (evt) {
  46802. for (var index = 0; index < this.children.length; index++) {
  46803. this.children[index].execute(evt);
  46804. }
  46805. };
  46806. CombineAction.prototype.serialize = function (parent) {
  46807. var serializationObject = _super.prototype._serialize.call(this, {
  46808. name: "CombineAction",
  46809. properties: [],
  46810. combine: []
  46811. }, parent);
  46812. for (var i = 0; i < this.children.length; i++) {
  46813. serializationObject.combine.push(this.children[i].serialize(null));
  46814. }
  46815. return serializationObject;
  46816. };
  46817. return CombineAction;
  46818. }(BABYLON.Action));
  46819. BABYLON.CombineAction = CombineAction;
  46820. var ExecuteCodeAction = (function (_super) {
  46821. __extends(ExecuteCodeAction, _super);
  46822. function ExecuteCodeAction(triggerOptions, func, condition) {
  46823. var _this = _super.call(this, triggerOptions, condition) || this;
  46824. _this.func = func;
  46825. return _this;
  46826. }
  46827. ExecuteCodeAction.prototype.execute = function (evt) {
  46828. this.func(evt);
  46829. };
  46830. return ExecuteCodeAction;
  46831. }(BABYLON.Action));
  46832. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  46833. var SetParentAction = (function (_super) {
  46834. __extends(SetParentAction, _super);
  46835. function SetParentAction(triggerOptions, target, parent, condition) {
  46836. var _this = _super.call(this, triggerOptions, condition) || this;
  46837. _this._target = target;
  46838. _this._parent = parent;
  46839. return _this;
  46840. }
  46841. SetParentAction.prototype._prepare = function () {
  46842. };
  46843. SetParentAction.prototype.execute = function () {
  46844. if (this._target.parent === this._parent) {
  46845. return;
  46846. }
  46847. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  46848. invertParentWorldMatrix.invert();
  46849. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  46850. this._target.parent = this._parent;
  46851. };
  46852. SetParentAction.prototype.serialize = function (parent) {
  46853. return _super.prototype._serialize.call(this, {
  46854. name: "SetParentAction",
  46855. properties: [
  46856. BABYLON.Action._GetTargetProperty(this._target),
  46857. BABYLON.Action._GetTargetProperty(this._parent),
  46858. ]
  46859. }, parent);
  46860. };
  46861. return SetParentAction;
  46862. }(BABYLON.Action));
  46863. BABYLON.SetParentAction = SetParentAction;
  46864. var PlaySoundAction = (function (_super) {
  46865. __extends(PlaySoundAction, _super);
  46866. function PlaySoundAction(triggerOptions, sound, condition) {
  46867. var _this = _super.call(this, triggerOptions, condition) || this;
  46868. _this._sound = sound;
  46869. return _this;
  46870. }
  46871. PlaySoundAction.prototype._prepare = function () {
  46872. };
  46873. PlaySoundAction.prototype.execute = function () {
  46874. if (this._sound !== undefined)
  46875. this._sound.play();
  46876. };
  46877. PlaySoundAction.prototype.serialize = function (parent) {
  46878. return _super.prototype._serialize.call(this, {
  46879. name: "PlaySoundAction",
  46880. properties: [{ name: "sound", value: this._sound.name }]
  46881. }, parent);
  46882. };
  46883. return PlaySoundAction;
  46884. }(BABYLON.Action));
  46885. BABYLON.PlaySoundAction = PlaySoundAction;
  46886. var StopSoundAction = (function (_super) {
  46887. __extends(StopSoundAction, _super);
  46888. function StopSoundAction(triggerOptions, sound, condition) {
  46889. var _this = _super.call(this, triggerOptions, condition) || this;
  46890. _this._sound = sound;
  46891. return _this;
  46892. }
  46893. StopSoundAction.prototype._prepare = function () {
  46894. };
  46895. StopSoundAction.prototype.execute = function () {
  46896. if (this._sound !== undefined)
  46897. this._sound.stop();
  46898. };
  46899. StopSoundAction.prototype.serialize = function (parent) {
  46900. return _super.prototype._serialize.call(this, {
  46901. name: "StopSoundAction",
  46902. properties: [{ name: "sound", value: this._sound.name }]
  46903. }, parent);
  46904. };
  46905. return StopSoundAction;
  46906. }(BABYLON.Action));
  46907. BABYLON.StopSoundAction = StopSoundAction;
  46908. })(BABYLON || (BABYLON = {}));
  46909. //# sourceMappingURL=babylon.directActions.js.map
  46910. var BABYLON;
  46911. (function (BABYLON) {
  46912. var Debug;
  46913. (function (Debug) {
  46914. /**
  46915. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  46916. */
  46917. var SkeletonViewer = (function () {
  46918. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  46919. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  46920. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  46921. this.skeleton = skeleton;
  46922. this.mesh = mesh;
  46923. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  46924. this.renderingGroupId = renderingGroupId;
  46925. this.color = BABYLON.Color3.White();
  46926. this._debugLines = [];
  46927. this._isEnabled = false;
  46928. this._scene = scene;
  46929. this.update();
  46930. this._renderFunction = this.update.bind(this);
  46931. }
  46932. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  46933. get: function () {
  46934. return this._isEnabled;
  46935. },
  46936. set: function (value) {
  46937. if (this._isEnabled === value) {
  46938. return;
  46939. }
  46940. this._isEnabled = value;
  46941. if (value) {
  46942. this._scene.registerBeforeRender(this._renderFunction);
  46943. }
  46944. else {
  46945. this._scene.unregisterBeforeRender(this._renderFunction);
  46946. }
  46947. },
  46948. enumerable: true,
  46949. configurable: true
  46950. });
  46951. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  46952. if (x === void 0) { x = 0; }
  46953. if (y === void 0) { y = 0; }
  46954. if (z === void 0) { z = 0; }
  46955. var tmat = BABYLON.Tmp.Matrix[0];
  46956. var parentBone = bone.getParent();
  46957. tmat.copyFrom(bone.getLocalMatrix());
  46958. if (x !== 0 || y !== 0 || z !== 0) {
  46959. var tmat2 = BABYLON.Tmp.Matrix[1];
  46960. BABYLON.Matrix.IdentityToRef(tmat2);
  46961. tmat2.m[12] = x;
  46962. tmat2.m[13] = y;
  46963. tmat2.m[14] = z;
  46964. tmat2.multiplyToRef(tmat, tmat);
  46965. }
  46966. if (parentBone) {
  46967. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  46968. }
  46969. tmat.multiplyToRef(meshMat, tmat);
  46970. position.x = tmat.m[12];
  46971. position.y = tmat.m[13];
  46972. position.z = tmat.m[14];
  46973. };
  46974. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  46975. var len = bones.length;
  46976. var meshPos = this.mesh.position;
  46977. for (var i = 0; i < len; i++) {
  46978. var bone = bones[i];
  46979. var points = this._debugLines[i];
  46980. if (!points) {
  46981. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  46982. this._debugLines[i] = points;
  46983. }
  46984. this._getBonePosition(points[0], bone, meshMat);
  46985. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  46986. points[0].subtractInPlace(meshPos);
  46987. points[1].subtractInPlace(meshPos);
  46988. }
  46989. };
  46990. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  46991. var len = bones.length;
  46992. var boneNum = 0;
  46993. var meshPos = this.mesh.position;
  46994. for (var i = len - 1; i >= 0; i--) {
  46995. var childBone = bones[i];
  46996. var parentBone = childBone.getParent();
  46997. if (!parentBone) {
  46998. continue;
  46999. }
  47000. var points = this._debugLines[boneNum];
  47001. if (!points) {
  47002. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47003. this._debugLines[boneNum] = points;
  47004. }
  47005. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  47006. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  47007. points[0].subtractInPlace(meshPos);
  47008. points[1].subtractInPlace(meshPos);
  47009. boneNum++;
  47010. }
  47011. };
  47012. SkeletonViewer.prototype.update = function () {
  47013. if (this.autoUpdateBonesMatrices) {
  47014. this.skeleton.computeAbsoluteTransforms();
  47015. }
  47016. if (this.skeleton.bones[0].length === undefined) {
  47017. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47018. }
  47019. else {
  47020. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47021. }
  47022. if (!this._debugMesh) {
  47023. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  47024. this._debugMesh.renderingGroupId = this.renderingGroupId;
  47025. }
  47026. else {
  47027. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  47028. }
  47029. this._debugMesh.position.copyFrom(this.mesh.position);
  47030. this._debugMesh.color = this.color;
  47031. };
  47032. SkeletonViewer.prototype.dispose = function () {
  47033. if (this._debugMesh) {
  47034. this.isEnabled = false;
  47035. this._debugMesh.dispose();
  47036. this._debugMesh = null;
  47037. }
  47038. };
  47039. return SkeletonViewer;
  47040. }());
  47041. Debug.SkeletonViewer = SkeletonViewer;
  47042. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47043. })(BABYLON || (BABYLON = {}));
  47044. //# sourceMappingURL=babylon.skeletonViewer.js.map
  47045. var BABYLON;
  47046. (function (BABYLON) {
  47047. var Debug;
  47048. (function (Debug) {
  47049. var AxesViewer = (function () {
  47050. function AxesViewer(scene, scaleLines) {
  47051. if (scaleLines === void 0) { scaleLines = 1; }
  47052. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47053. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47054. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47055. this.scaleLines = 1;
  47056. this.scaleLines = scaleLines;
  47057. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  47058. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  47059. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  47060. this._xmesh.renderingGroupId = 2;
  47061. this._ymesh.renderingGroupId = 2;
  47062. this._zmesh.renderingGroupId = 2;
  47063. this._xmesh.material.checkReadyOnlyOnce = true;
  47064. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  47065. this._ymesh.material.checkReadyOnlyOnce = true;
  47066. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  47067. this._zmesh.material.checkReadyOnlyOnce = true;
  47068. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  47069. this.scene = scene;
  47070. }
  47071. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  47072. var scaleLines = this.scaleLines;
  47073. this._xmesh.position.copyFrom(position);
  47074. this._ymesh.position.copyFrom(position);
  47075. this._zmesh.position.copyFrom(position);
  47076. var point2 = this._xline[1];
  47077. point2.x = xaxis.x * scaleLines;
  47078. point2.y = xaxis.y * scaleLines;
  47079. point2.z = xaxis.z * scaleLines;
  47080. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  47081. point2 = this._yline[1];
  47082. point2.x = yaxis.x * scaleLines;
  47083. point2.y = yaxis.y * scaleLines;
  47084. point2.z = yaxis.z * scaleLines;
  47085. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  47086. point2 = this._zline[1];
  47087. point2.x = zaxis.x * scaleLines;
  47088. point2.y = zaxis.y * scaleLines;
  47089. point2.z = zaxis.z * scaleLines;
  47090. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  47091. };
  47092. AxesViewer.prototype.dispose = function () {
  47093. if (this._xmesh) {
  47094. this._xmesh.dispose();
  47095. this._ymesh.dispose();
  47096. this._zmesh.dispose();
  47097. this._xmesh = null;
  47098. this._ymesh = null;
  47099. this._zmesh = null;
  47100. this._xline = null;
  47101. this._yline = null;
  47102. this._zline = null;
  47103. this.scene = null;
  47104. }
  47105. };
  47106. return AxesViewer;
  47107. }());
  47108. Debug.AxesViewer = AxesViewer;
  47109. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47110. })(BABYLON || (BABYLON = {}));
  47111. //# sourceMappingURL=babylon.axesViewer.js.map
  47112. var BABYLON;
  47113. (function (BABYLON) {
  47114. var Debug;
  47115. (function (Debug) {
  47116. var BoneAxesViewer = (function (_super) {
  47117. __extends(BoneAxesViewer, _super);
  47118. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  47119. if (scaleLines === void 0) { scaleLines = 1; }
  47120. var _this = _super.call(this, scene, scaleLines) || this;
  47121. _this.pos = BABYLON.Vector3.Zero();
  47122. _this.xaxis = BABYLON.Vector3.Zero();
  47123. _this.yaxis = BABYLON.Vector3.Zero();
  47124. _this.zaxis = BABYLON.Vector3.Zero();
  47125. _this.mesh = mesh;
  47126. _this.bone = bone;
  47127. return _this;
  47128. }
  47129. BoneAxesViewer.prototype.update = function () {
  47130. var bone = this.bone;
  47131. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  47132. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  47133. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  47134. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  47135. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  47136. };
  47137. BoneAxesViewer.prototype.dispose = function () {
  47138. if (this.pos) {
  47139. this.pos = null;
  47140. this.xaxis = null;
  47141. this.yaxis = null;
  47142. this.zaxis = null;
  47143. this.mesh = null;
  47144. this.bone = null;
  47145. _super.prototype.dispose.call(this);
  47146. }
  47147. };
  47148. return BoneAxesViewer;
  47149. }(Debug.AxesViewer));
  47150. Debug.BoneAxesViewer = BoneAxesViewer;
  47151. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47152. })(BABYLON || (BABYLON = {}));
  47153. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  47154. var BABYLON;
  47155. (function (BABYLON) {
  47156. var RayHelper = (function () {
  47157. function RayHelper(ray) {
  47158. this.ray = ray;
  47159. }
  47160. RayHelper.CreateAndShow = function (ray, scene, color) {
  47161. var helper = new RayHelper(ray);
  47162. helper.show(scene, color);
  47163. return helper;
  47164. };
  47165. RayHelper.prototype.show = function (scene, color) {
  47166. if (!this._renderFunction) {
  47167. var ray = this.ray;
  47168. this._renderFunction = this._render.bind(this);
  47169. this._scene = scene;
  47170. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  47171. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  47172. this._scene.registerBeforeRender(this._renderFunction);
  47173. }
  47174. if (color) {
  47175. this._renderLine.color.copyFrom(color);
  47176. }
  47177. };
  47178. RayHelper.prototype.hide = function () {
  47179. if (this._renderFunction) {
  47180. this._scene.unregisterBeforeRender(this._renderFunction);
  47181. this._scene = null;
  47182. this._renderFunction = null;
  47183. this._renderLine.dispose();
  47184. this._renderLine = null;
  47185. this._renderPoints = null;
  47186. }
  47187. };
  47188. RayHelper.prototype._render = function () {
  47189. var ray = this.ray;
  47190. var point = this._renderPoints[1];
  47191. var len = Math.min(ray.length, 1000000);
  47192. point.copyFrom(ray.direction);
  47193. point.scaleInPlace(len);
  47194. point.addInPlace(ray.origin);
  47195. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  47196. };
  47197. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  47198. this._attachedToMesh = mesh;
  47199. var ray = this.ray;
  47200. if (!ray.direction) {
  47201. ray.direction = BABYLON.Vector3.Zero();
  47202. }
  47203. if (!ray.origin) {
  47204. ray.origin = BABYLON.Vector3.Zero();
  47205. }
  47206. if (length) {
  47207. ray.length = length;
  47208. }
  47209. if (!meshSpaceOrigin) {
  47210. meshSpaceOrigin = BABYLON.Vector3.Zero();
  47211. }
  47212. if (!meshSpaceDirection) {
  47213. // -1 so that this will work with Mesh.lookAt
  47214. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  47215. }
  47216. if (!this._meshSpaceDirection) {
  47217. this._meshSpaceDirection = meshSpaceDirection.clone();
  47218. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  47219. }
  47220. else {
  47221. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  47222. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  47223. }
  47224. if (!this._updateToMeshFunction) {
  47225. this._updateToMeshFunction = this._updateToMesh.bind(this);
  47226. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  47227. }
  47228. this._updateToMesh();
  47229. };
  47230. RayHelper.prototype.detachFromMesh = function () {
  47231. if (this._attachedToMesh) {
  47232. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  47233. this._attachedToMesh = null;
  47234. this._updateToMeshFunction = null;
  47235. }
  47236. };
  47237. RayHelper.prototype._updateToMesh = function () {
  47238. var ray = this.ray;
  47239. if (this._attachedToMesh._isDisposed) {
  47240. this.detachFromMesh();
  47241. return;
  47242. }
  47243. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  47244. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  47245. };
  47246. RayHelper.prototype.dispose = function () {
  47247. this.hide();
  47248. this.detachFromMesh();
  47249. this.ray = null;
  47250. };
  47251. return RayHelper;
  47252. }());
  47253. BABYLON.RayHelper = RayHelper;
  47254. })(BABYLON || (BABYLON = {}));
  47255. //# sourceMappingURL=babylon.rayHelper.js.map
  47256. var BABYLON;
  47257. (function (BABYLON) {
  47258. var DebugLayer = (function () {
  47259. function DebugLayer(scene) {
  47260. this._scene = scene;
  47261. }
  47262. /** Creates the inspector window. */
  47263. DebugLayer.prototype._createInspector = function (config) {
  47264. if (config === void 0) { config = {}; }
  47265. var popup = config.popup || false;
  47266. var initialTab = config.initialTab || 0;
  47267. var parentElement = config.parentElement || null;
  47268. if (!this._inspector) {
  47269. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  47270. } // else nothing to do,; instance is already existing
  47271. };
  47272. DebugLayer.prototype.isVisible = function () {
  47273. if (!this._inspector) {
  47274. return false;
  47275. }
  47276. return true;
  47277. };
  47278. DebugLayer.prototype.hide = function () {
  47279. if (this._inspector) {
  47280. try {
  47281. this._inspector.dispose();
  47282. }
  47283. catch (e) {
  47284. // If the inspector has been removed directly from the inspector tool
  47285. }
  47286. this._inspector = null;
  47287. }
  47288. };
  47289. DebugLayer.prototype.show = function (config) {
  47290. if (config === void 0) { config = {}; }
  47291. if (typeof INSPECTOR == 'undefined') {
  47292. // Load inspector and add it to the DOM
  47293. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  47294. }
  47295. else {
  47296. // Otherwise creates the inspector
  47297. this._createInspector(config);
  47298. }
  47299. };
  47300. // Get protocol used - http or https
  47301. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  47302. return DebugLayer;
  47303. }());
  47304. BABYLON.DebugLayer = DebugLayer;
  47305. })(BABYLON || (BABYLON = {}));
  47306. //# sourceMappingURL=babylon.debugLayer.js.map
  47307. var BABYLON;
  47308. (function (BABYLON) {
  47309. var Debug;
  47310. (function (Debug) {
  47311. var PhysicsViewer = (function () {
  47312. function PhysicsViewer(scene) {
  47313. this._impostors = [];
  47314. this._meshes = [];
  47315. this._numMeshes = 0;
  47316. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47317. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  47318. }
  47319. PhysicsViewer.prototype._updateDebugMeshes = function () {
  47320. var plugin = this._physicsEnginePlugin;
  47321. for (var i = 0; i < this._numMeshes; i++) {
  47322. if (this._impostors[i].isDisposed) {
  47323. this.hideImpostor(this._impostors[i--]);
  47324. }
  47325. else {
  47326. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  47327. }
  47328. }
  47329. };
  47330. PhysicsViewer.prototype.showImpostor = function (impostor) {
  47331. for (var i = 0; i < this._numMeshes; i++) {
  47332. if (this._impostors[i] == impostor) {
  47333. return;
  47334. }
  47335. }
  47336. var debugMesh = this._getDebugMesh(impostor, this._scene);
  47337. if (debugMesh) {
  47338. this._impostors[this._numMeshes] = impostor;
  47339. this._meshes[this._numMeshes] = debugMesh;
  47340. if (this._numMeshes === 0) {
  47341. this._renderFunction = this._updateDebugMeshes.bind(this);
  47342. this._scene.registerBeforeRender(this._renderFunction);
  47343. }
  47344. this._numMeshes++;
  47345. }
  47346. };
  47347. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  47348. var removed = false;
  47349. for (var i = 0; i < this._numMeshes; i++) {
  47350. if (this._impostors[i] == impostor) {
  47351. this._scene.removeMesh(this._meshes[i]);
  47352. this._meshes[i].dispose();
  47353. this._numMeshes--;
  47354. if (this._numMeshes > 0) {
  47355. this._meshes[i] = this._meshes[this._numMeshes];
  47356. this._impostors[i] = this._impostors[this._numMeshes];
  47357. this._meshes[this._numMeshes] = null;
  47358. this._impostors[this._numMeshes] = null;
  47359. }
  47360. else {
  47361. this._meshes[0] = null;
  47362. this._impostors[0] = null;
  47363. }
  47364. removed = true;
  47365. break;
  47366. }
  47367. }
  47368. if (removed && this._numMeshes === 0) {
  47369. this._scene.unregisterBeforeRender(this._renderFunction);
  47370. }
  47371. };
  47372. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  47373. if (!this._debugMaterial) {
  47374. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  47375. this._debugMaterial.wireframe = true;
  47376. }
  47377. return this._debugMaterial;
  47378. };
  47379. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  47380. if (!this._debugBoxMesh) {
  47381. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  47382. this._debugBoxMesh.renderingGroupId = 1;
  47383. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47384. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  47385. scene.removeMesh(this._debugBoxMesh);
  47386. }
  47387. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  47388. };
  47389. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  47390. if (!this._debugSphereMesh) {
  47391. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  47392. this._debugSphereMesh.renderingGroupId = 1;
  47393. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47394. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  47395. scene.removeMesh(this._debugSphereMesh);
  47396. }
  47397. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  47398. };
  47399. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  47400. var body = impostor.physicsBody;
  47401. var shape = body.shapes[0];
  47402. var mesh;
  47403. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  47404. mesh = this._getDebugBoxMesh(scene);
  47405. impostor.getBoxSizeToRef(mesh.scaling);
  47406. }
  47407. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  47408. mesh = this._getDebugSphereMesh(scene);
  47409. var radius = impostor.getRadius();
  47410. mesh.scaling.x = radius * 2;
  47411. mesh.scaling.y = radius * 2;
  47412. mesh.scaling.z = radius * 2;
  47413. }
  47414. return mesh;
  47415. };
  47416. PhysicsViewer.prototype.dispose = function () {
  47417. for (var i = 0; i < this._numMeshes; i++) {
  47418. this.hideImpostor(this._impostors[i]);
  47419. }
  47420. if (this._debugBoxMesh) {
  47421. this._debugBoxMesh.dispose();
  47422. }
  47423. if (this._debugSphereMesh) {
  47424. this._debugSphereMesh.dispose();
  47425. }
  47426. if (this._debugMaterial) {
  47427. this._debugMaterial.dispose();
  47428. }
  47429. this._impostors.length = 0;
  47430. this._scene = null;
  47431. this._physicsEnginePlugin = null;
  47432. };
  47433. return PhysicsViewer;
  47434. }());
  47435. Debug.PhysicsViewer = PhysicsViewer;
  47436. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47437. })(BABYLON || (BABYLON = {}));
  47438. //# sourceMappingURL=babylon.physicsViewer.js.map
  47439. var BABYLON;
  47440. (function (BABYLON) {
  47441. var BoundingBoxRenderer = (function () {
  47442. function BoundingBoxRenderer(scene) {
  47443. this.frontColor = new BABYLON.Color3(1, 1, 1);
  47444. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  47445. this.showBackLines = true;
  47446. this.renderList = new BABYLON.SmartArray(32);
  47447. this._vertexBuffers = {};
  47448. this._scene = scene;
  47449. }
  47450. BoundingBoxRenderer.prototype._prepareRessources = function () {
  47451. if (this._colorShader) {
  47452. return;
  47453. }
  47454. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  47455. attributes: [BABYLON.VertexBuffer.PositionKind],
  47456. uniforms: ["world", "viewProjection", "color"]
  47457. });
  47458. var engine = this._scene.getEngine();
  47459. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  47460. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  47461. 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]);
  47462. };
  47463. BoundingBoxRenderer.prototype.reset = function () {
  47464. this.renderList.reset();
  47465. };
  47466. BoundingBoxRenderer.prototype.render = function () {
  47467. if (this.renderList.length === 0) {
  47468. return;
  47469. }
  47470. this._prepareRessources();
  47471. if (!this._colorShader.isReady()) {
  47472. return;
  47473. }
  47474. var engine = this._scene.getEngine();
  47475. engine.setDepthWrite(false);
  47476. this._colorShader._preBind();
  47477. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  47478. var boundingBox = this.renderList.data[boundingBoxIndex];
  47479. var min = boundingBox.minimum;
  47480. var max = boundingBox.maximum;
  47481. var diff = max.subtract(min);
  47482. var median = min.add(diff.scale(0.5));
  47483. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47484. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47485. .multiply(boundingBox.getWorldMatrix());
  47486. // VBOs
  47487. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47488. if (this.showBackLines) {
  47489. // Back
  47490. engine.setDepthFunctionToGreaterOrEqual();
  47491. this._scene.resetCachedMaterial();
  47492. this._colorShader.setColor4("color", this.backColor.toColor4());
  47493. this._colorShader.bind(worldMatrix);
  47494. // Draw order
  47495. engine.draw(false, 0, 24);
  47496. }
  47497. // Front
  47498. engine.setDepthFunctionToLess();
  47499. this._scene.resetCachedMaterial();
  47500. this._colorShader.setColor4("color", this.frontColor.toColor4());
  47501. this._colorShader.bind(worldMatrix);
  47502. // Draw order
  47503. engine.draw(false, 0, 24);
  47504. }
  47505. this._colorShader.unbind();
  47506. engine.setDepthFunctionToLessOrEqual();
  47507. engine.setDepthWrite(true);
  47508. };
  47509. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  47510. this._prepareRessources();
  47511. if (!this._colorShader.isReady()) {
  47512. return;
  47513. }
  47514. var engine = this._scene.getEngine();
  47515. engine.setDepthWrite(false);
  47516. engine.setColorWrite(false);
  47517. this._colorShader._preBind();
  47518. var boundingBox = mesh._boundingInfo.boundingBox;
  47519. var min = boundingBox.minimum;
  47520. var max = boundingBox.maximum;
  47521. var diff = max.subtract(min);
  47522. var median = min.add(diff.scale(0.5));
  47523. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47524. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47525. .multiply(boundingBox.getWorldMatrix());
  47526. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47527. engine.setDepthFunctionToLess();
  47528. this._scene.resetCachedMaterial();
  47529. this._colorShader.bind(worldMatrix);
  47530. engine.draw(false, 0, 24);
  47531. this._colorShader.unbind();
  47532. engine.setDepthFunctionToLessOrEqual();
  47533. engine.setDepthWrite(true);
  47534. engine.setColorWrite(true);
  47535. };
  47536. BoundingBoxRenderer.prototype.dispose = function () {
  47537. if (!this._colorShader) {
  47538. return;
  47539. }
  47540. this.renderList.dispose();
  47541. this._colorShader.dispose();
  47542. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47543. if (buffer) {
  47544. buffer.dispose();
  47545. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47546. }
  47547. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47548. };
  47549. return BoundingBoxRenderer;
  47550. }());
  47551. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  47552. })(BABYLON || (BABYLON = {}));
  47553. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  47554. var BABYLON;
  47555. (function (BABYLON) {
  47556. var TextureTools = (function () {
  47557. function TextureTools() {
  47558. }
  47559. /**
  47560. * Uses the GPU to create a copy texture rescaled at a given size
  47561. * @param texture Texture to copy from
  47562. * @param width Desired width
  47563. * @param height Desired height
  47564. * @return Generated texture
  47565. */
  47566. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  47567. if (useBilinearMode === void 0) { useBilinearMode = true; }
  47568. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  47569. var scene = texture.getScene();
  47570. var engine = scene.getEngine();
  47571. rtt.wrapU = texture.wrapU;
  47572. rtt.wrapV = texture.wrapV;
  47573. rtt.uOffset = texture.uOffset;
  47574. rtt.vOffset = texture.vOffset;
  47575. rtt.uScale = texture.uScale;
  47576. rtt.vScale = texture.vScale;
  47577. rtt.uAng = texture.uAng;
  47578. rtt.vAng = texture.vAng;
  47579. rtt.wAng = texture.wAng;
  47580. rtt.coordinatesIndex = texture.coordinatesIndex;
  47581. rtt.level = texture.level;
  47582. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  47583. rtt._texture.isReady = false;
  47584. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47585. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47586. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47587. passPostProcess.getEffect().executeWhenCompiled(function () {
  47588. passPostProcess.onApply = function (effect) {
  47589. effect.setTexture("textureSampler", texture);
  47590. };
  47591. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  47592. engine.unBindFramebuffer(rtt.getInternalTexture());
  47593. rtt.disposeFramebufferObjects();
  47594. passPostProcess.dispose();
  47595. rtt._texture.isReady = true;
  47596. });
  47597. return rtt;
  47598. };
  47599. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  47600. if (!scene._environmentBRDFTexture) {
  47601. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47602. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47603. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47604. scene._environmentBRDFTexture = texture;
  47605. }
  47606. return scene._environmentBRDFTexture;
  47607. };
  47608. 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=";
  47609. return TextureTools;
  47610. }());
  47611. BABYLON.TextureTools = TextureTools;
  47612. })(BABYLON || (BABYLON = {}));
  47613. //# sourceMappingURL=babylon.textureTools.js.map
  47614. var BABYLON;
  47615. (function (BABYLON) {
  47616. var SphericalPolynomial = (function () {
  47617. function SphericalPolynomial() {
  47618. this.x = BABYLON.Vector3.Zero();
  47619. this.y = BABYLON.Vector3.Zero();
  47620. this.z = BABYLON.Vector3.Zero();
  47621. this.xx = BABYLON.Vector3.Zero();
  47622. this.yy = BABYLON.Vector3.Zero();
  47623. this.zz = BABYLON.Vector3.Zero();
  47624. this.xy = BABYLON.Vector3.Zero();
  47625. this.yz = BABYLON.Vector3.Zero();
  47626. this.zx = BABYLON.Vector3.Zero();
  47627. }
  47628. SphericalPolynomial.prototype.addAmbient = function (color) {
  47629. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  47630. this.xx = this.xx.add(colorVector);
  47631. this.yy = this.yy.add(colorVector);
  47632. this.zz = this.zz.add(colorVector);
  47633. };
  47634. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  47635. var result = new SphericalPolynomial();
  47636. result.x = harmonics.L11.scale(1.02333);
  47637. result.y = harmonics.L1_1.scale(1.02333);
  47638. result.z = harmonics.L10.scale(1.02333);
  47639. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  47640. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  47641. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  47642. result.yz = harmonics.L2_1.scale(0.858086);
  47643. result.zx = harmonics.L21.scale(0.858086);
  47644. result.xy = harmonics.L2_2.scale(0.858086);
  47645. result.scale(1.0 / Math.PI);
  47646. return result;
  47647. };
  47648. SphericalPolynomial.prototype.scale = function (scale) {
  47649. this.x = this.x.scale(scale);
  47650. this.y = this.y.scale(scale);
  47651. this.z = this.z.scale(scale);
  47652. this.xx = this.xx.scale(scale);
  47653. this.yy = this.yy.scale(scale);
  47654. this.zz = this.zz.scale(scale);
  47655. this.yz = this.yz.scale(scale);
  47656. this.zx = this.zx.scale(scale);
  47657. this.xy = this.xy.scale(scale);
  47658. };
  47659. return SphericalPolynomial;
  47660. }());
  47661. BABYLON.SphericalPolynomial = SphericalPolynomial;
  47662. var SphericalHarmonics = (function () {
  47663. function SphericalHarmonics() {
  47664. this.L00 = BABYLON.Vector3.Zero();
  47665. this.L1_1 = BABYLON.Vector3.Zero();
  47666. this.L10 = BABYLON.Vector3.Zero();
  47667. this.L11 = BABYLON.Vector3.Zero();
  47668. this.L2_2 = BABYLON.Vector3.Zero();
  47669. this.L2_1 = BABYLON.Vector3.Zero();
  47670. this.L20 = BABYLON.Vector3.Zero();
  47671. this.L21 = BABYLON.Vector3.Zero();
  47672. this.L22 = BABYLON.Vector3.Zero();
  47673. }
  47674. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  47675. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  47676. var c = colorVector.scale(deltaSolidAngle);
  47677. this.L00 = this.L00.add(c.scale(0.282095));
  47678. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  47679. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  47680. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  47681. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  47682. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  47683. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  47684. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  47685. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  47686. };
  47687. SphericalHarmonics.prototype.scale = function (scale) {
  47688. this.L00 = this.L00.scale(scale);
  47689. this.L1_1 = this.L1_1.scale(scale);
  47690. this.L10 = this.L10.scale(scale);
  47691. this.L11 = this.L11.scale(scale);
  47692. this.L2_2 = this.L2_2.scale(scale);
  47693. this.L2_1 = this.L2_1.scale(scale);
  47694. this.L20 = this.L20.scale(scale);
  47695. this.L21 = this.L21.scale(scale);
  47696. this.L22 = this.L22.scale(scale);
  47697. };
  47698. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  47699. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  47700. //
  47701. // E_lm = A_l * L_lm
  47702. //
  47703. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  47704. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  47705. // the scaling factors are given in equation 9.
  47706. // Constant (Band 0)
  47707. this.L00 = this.L00.scale(3.141593);
  47708. // Linear (Band 1)
  47709. this.L1_1 = this.L1_1.scale(2.094395);
  47710. this.L10 = this.L10.scale(2.094395);
  47711. this.L11 = this.L11.scale(2.094395);
  47712. // Quadratic (Band 2)
  47713. this.L2_2 = this.L2_2.scale(0.785398);
  47714. this.L2_1 = this.L2_1.scale(0.785398);
  47715. this.L20 = this.L20.scale(0.785398);
  47716. this.L21 = this.L21.scale(0.785398);
  47717. this.L22 = this.L22.scale(0.785398);
  47718. };
  47719. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  47720. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  47721. // L = (1/pi) * E * rho
  47722. //
  47723. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  47724. this.scale(1.0 / Math.PI);
  47725. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  47726. // (The pixel shader must apply albedo after texture fetches, etc).
  47727. };
  47728. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  47729. var result = new SphericalHarmonics();
  47730. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  47731. result.L1_1 = polynomial.y.scale(0.977204);
  47732. result.L10 = polynomial.z.scale(0.977204);
  47733. result.L11 = polynomial.x.scale(0.977204);
  47734. result.L2_2 = polynomial.xy.scale(1.16538);
  47735. result.L2_1 = polynomial.yz.scale(1.16538);
  47736. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  47737. result.L21 = polynomial.zx.scale(1.16538);
  47738. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  47739. result.scale(Math.PI);
  47740. return result;
  47741. };
  47742. return SphericalHarmonics;
  47743. }());
  47744. BABYLON.SphericalHarmonics = SphericalHarmonics;
  47745. })(BABYLON || (BABYLON = {}));
  47746. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  47747. var BABYLON;
  47748. (function (BABYLON) {
  47749. var Internals;
  47750. (function (Internals) {
  47751. var FileFaceOrientation = (function () {
  47752. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  47753. this.name = name;
  47754. this.worldAxisForNormal = worldAxisForNormal;
  47755. this.worldAxisForFileX = worldAxisForFileX;
  47756. this.worldAxisForFileY = worldAxisForFileY;
  47757. }
  47758. return FileFaceOrientation;
  47759. }());
  47760. ;
  47761. /**
  47762. * Helper class dealing with the extraction of spherical polynomial dataArray
  47763. * from a cube map.
  47764. */
  47765. var CubeMapToSphericalPolynomialTools = (function () {
  47766. function CubeMapToSphericalPolynomialTools() {
  47767. }
  47768. /**
  47769. * Converts a texture to the according Spherical Polynomial data.
  47770. * This extracts the first 3 orders only as they are the only one used in the lighting.
  47771. *
  47772. * @param texture The texture to extract the information from.
  47773. * @return The Spherical Polynomial data.
  47774. */
  47775. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  47776. if (!texture.isCube) {
  47777. // Only supports cube Textures currently.
  47778. return null;
  47779. }
  47780. var size = texture.getSize().width;
  47781. var right = texture.readPixels(0);
  47782. var left = texture.readPixels(1);
  47783. var up;
  47784. var down;
  47785. if (texture.isRenderTarget) {
  47786. up = texture.readPixels(3);
  47787. down = texture.readPixels(2);
  47788. }
  47789. else {
  47790. up = texture.readPixels(2);
  47791. down = texture.readPixels(3);
  47792. }
  47793. var front = texture.readPixels(4);
  47794. var back = texture.readPixels(5);
  47795. var gammaSpace = texture.gammaSpace;
  47796. // Always read as RGBA.
  47797. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  47798. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47799. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47800. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47801. }
  47802. var cubeInfo = {
  47803. size: size,
  47804. right: right,
  47805. left: left,
  47806. up: up,
  47807. down: down,
  47808. front: front,
  47809. back: back,
  47810. format: format,
  47811. type: type,
  47812. gammaSpace: gammaSpace,
  47813. };
  47814. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  47815. };
  47816. /**
  47817. * Converts a cubemap to the according Spherical Polynomial data.
  47818. * This extracts the first 3 orders only as they are the only one used in the lighting.
  47819. *
  47820. * @param cubeInfo The Cube map to extract the information from.
  47821. * @return The Spherical Polynomial data.
  47822. */
  47823. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  47824. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  47825. var totalSolidAngle = 0.0;
  47826. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  47827. var du = 2.0 / cubeInfo.size;
  47828. var dv = du;
  47829. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  47830. var minUV = du * 0.5 - 1.0;
  47831. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  47832. var fileFace = this.FileFaces[faceIndex];
  47833. var dataArray = cubeInfo[fileFace.name];
  47834. var v = minUV;
  47835. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  47836. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  47837. // Because SP is still linear, so summation is fine in that basis.
  47838. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  47839. for (var y = 0; y < cubeInfo.size; y++) {
  47840. var u = minUV;
  47841. for (var x = 0; x < cubeInfo.size; x++) {
  47842. // World direction (not normalised)
  47843. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  47844. worldDirection.normalize();
  47845. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  47846. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  47847. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  47848. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  47849. // Handle Integer types.
  47850. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47851. r /= 255;
  47852. g /= 255;
  47853. b /= 255;
  47854. }
  47855. // Handle Gamma space textures.
  47856. if (cubeInfo.gammaSpace) {
  47857. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  47858. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  47859. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  47860. }
  47861. var color = new BABYLON.Color3(r, g, b);
  47862. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  47863. totalSolidAngle += deltaSolidAngle;
  47864. u += du;
  47865. }
  47866. v += dv;
  47867. }
  47868. }
  47869. // Solid angle for entire sphere is 4*pi
  47870. var sphereSolidAngle = 4.0 * Math.PI;
  47871. // Adjust the solid angle to allow for how many faces we processed.
  47872. var facesProcessed = 6.0;
  47873. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  47874. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  47875. // This is needed because the numerical integration over the cube uses a
  47876. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  47877. // and also to compensate for accumulative error due to float precision in the summation.
  47878. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  47879. sphericalHarmonics.scale(correctionFactor);
  47880. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  47881. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  47882. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  47883. };
  47884. CubeMapToSphericalPolynomialTools.FileFaces = [
  47885. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  47886. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  47887. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  47888. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  47889. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  47890. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  47891. ];
  47892. return CubeMapToSphericalPolynomialTools;
  47893. }());
  47894. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  47895. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47896. })(BABYLON || (BABYLON = {}));
  47897. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  47898. var BABYLON;
  47899. (function (BABYLON) {
  47900. var Internals;
  47901. (function (Internals) {
  47902. /**
  47903. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  47904. */
  47905. var PanoramaToCubeMapTools = (function () {
  47906. function PanoramaToCubeMapTools() {
  47907. }
  47908. /**
  47909. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  47910. *
  47911. * @param float32Array The source data.
  47912. * @param inputWidth The width of the input panorama.
  47913. * @param inputhHeight The height of the input panorama.
  47914. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  47915. * @return The cubemap data
  47916. */
  47917. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  47918. if (!float32Array) {
  47919. throw "ConvertPanoramaToCubemap: input cannot be null";
  47920. }
  47921. if (float32Array.length != inputWidth * inputHeight * 3) {
  47922. throw "ConvertPanoramaToCubemap: input size is wrong";
  47923. }
  47924. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  47925. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  47926. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  47927. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  47928. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  47929. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  47930. return {
  47931. front: textureFront,
  47932. back: textureBack,
  47933. left: textureLeft,
  47934. right: textureRight,
  47935. up: textureUp,
  47936. down: textureDown,
  47937. size: size,
  47938. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  47939. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  47940. gammaSpace: false,
  47941. };
  47942. };
  47943. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  47944. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  47945. var textureArray = new Float32Array(buffer);
  47946. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  47947. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  47948. var dy = 1 / texSize;
  47949. var fy = 0;
  47950. for (var y = 0; y < texSize; y++) {
  47951. var xv1 = faceData[0];
  47952. var xv2 = faceData[2];
  47953. for (var x = 0; x < texSize; x++) {
  47954. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  47955. v.normalize();
  47956. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  47957. // 3 channels per pixels
  47958. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  47959. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  47960. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  47961. xv1 = xv1.add(rotDX1);
  47962. xv2 = xv2.add(rotDX2);
  47963. }
  47964. fy += dy;
  47965. }
  47966. return textureArray;
  47967. };
  47968. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  47969. var theta = Math.atan2(vDir.z, vDir.x);
  47970. var phi = Math.acos(vDir.y);
  47971. while (theta < -Math.PI)
  47972. theta += 2 * Math.PI;
  47973. while (theta > Math.PI)
  47974. theta -= 2 * Math.PI;
  47975. var dx = theta / Math.PI;
  47976. var dy = phi / Math.PI;
  47977. // recenter.
  47978. dx = dx * 0.5 + 0.5;
  47979. var px = Math.round(dx * inputWidth);
  47980. if (px < 0)
  47981. px = 0;
  47982. else if (px >= inputWidth)
  47983. px = inputWidth - 1;
  47984. var py = Math.round(dy * inputHeight);
  47985. if (py < 0)
  47986. py = 0;
  47987. else if (py >= inputHeight)
  47988. py = inputHeight - 1;
  47989. var inputY = (inputHeight - py - 1);
  47990. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  47991. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  47992. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  47993. return {
  47994. r: r,
  47995. g: g,
  47996. b: b
  47997. };
  47998. };
  47999. PanoramaToCubeMapTools.FACE_FRONT = [
  48000. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48001. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48002. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48003. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48004. ];
  48005. PanoramaToCubeMapTools.FACE_BACK = [
  48006. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48007. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48008. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48009. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48010. ];
  48011. PanoramaToCubeMapTools.FACE_RIGHT = [
  48012. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48013. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48014. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48015. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48016. ];
  48017. PanoramaToCubeMapTools.FACE_LEFT = [
  48018. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48019. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48020. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48021. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48022. ];
  48023. PanoramaToCubeMapTools.FACE_DOWN = [
  48024. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48025. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48026. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48027. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48028. ];
  48029. PanoramaToCubeMapTools.FACE_UP = [
  48030. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48031. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48032. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48033. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48034. ];
  48035. return PanoramaToCubeMapTools;
  48036. }());
  48037. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48038. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48039. })(BABYLON || (BABYLON = {}));
  48040. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  48041. var BABYLON;
  48042. (function (BABYLON) {
  48043. var Internals;
  48044. (function (Internals) {
  48045. ;
  48046. /**
  48047. * This groups tools to convert HDR texture to native colors array.
  48048. */
  48049. var HDRTools = (function () {
  48050. function HDRTools() {
  48051. }
  48052. HDRTools.Ldexp = function (mantissa, exponent) {
  48053. if (exponent > 1023) {
  48054. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48055. }
  48056. if (exponent < -1074) {
  48057. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48058. }
  48059. return mantissa * Math.pow(2, exponent);
  48060. };
  48061. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48062. if (exponent > 0) {
  48063. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48064. float32array[index + 0] = red * exponent;
  48065. float32array[index + 1] = green * exponent;
  48066. float32array[index + 2] = blue * exponent;
  48067. }
  48068. else {
  48069. float32array[index + 0] = 0;
  48070. float32array[index + 1] = 0;
  48071. float32array[index + 2] = 0;
  48072. }
  48073. };
  48074. HDRTools.readStringLine = function (uint8array, startIndex) {
  48075. var line = "";
  48076. var character = "";
  48077. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48078. character = String.fromCharCode(uint8array[i]);
  48079. if (character == "\n") {
  48080. break;
  48081. }
  48082. line += character;
  48083. }
  48084. return line;
  48085. };
  48086. /**
  48087. * Reads header information from an RGBE texture stored in a native array.
  48088. * More information on this format are available here:
  48089. * https://en.wikipedia.org/wiki/RGBE_image_format
  48090. *
  48091. * @param uint8array The binary file stored in native array.
  48092. * @return The header information.
  48093. */
  48094. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48095. var height = 0;
  48096. var width = 0;
  48097. var line = this.readStringLine(uint8array, 0);
  48098. if (line[0] != '#' || line[1] != '?') {
  48099. throw "Bad HDR Format.";
  48100. }
  48101. var endOfHeader = false;
  48102. var findFormat = false;
  48103. var lineIndex = 0;
  48104. do {
  48105. lineIndex += (line.length + 1);
  48106. line = this.readStringLine(uint8array, lineIndex);
  48107. if (line == "FORMAT=32-bit_rle_rgbe") {
  48108. findFormat = true;
  48109. }
  48110. else if (line.length == 0) {
  48111. endOfHeader = true;
  48112. }
  48113. } while (!endOfHeader);
  48114. if (!findFormat) {
  48115. throw "HDR Bad header format, unsupported FORMAT";
  48116. }
  48117. lineIndex += (line.length + 1);
  48118. line = this.readStringLine(uint8array, lineIndex);
  48119. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48120. var match = sizeRegexp.exec(line);
  48121. // TODO. Support +Y and -X if needed.
  48122. if (match.length < 3) {
  48123. throw "HDR Bad header format, no size";
  48124. }
  48125. width = parseInt(match[2]);
  48126. height = parseInt(match[1]);
  48127. if (width < 8 || width > 0x7fff) {
  48128. throw "HDR Bad header format, unsupported size";
  48129. }
  48130. lineIndex += (line.length + 1);
  48131. return {
  48132. height: height,
  48133. width: width,
  48134. dataPosition: lineIndex
  48135. };
  48136. };
  48137. /**
  48138. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48139. * This RGBE texture needs to store the information as a panorama.
  48140. *
  48141. * More information on this format are available here:
  48142. * https://en.wikipedia.org/wiki/RGBE_image_format
  48143. *
  48144. * @param buffer The binary file stored in an array buffer.
  48145. * @param size The expected size of the extracted cubemap.
  48146. * @return The Cube Map information.
  48147. */
  48148. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48149. var uint8array = new Uint8Array(buffer);
  48150. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48151. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48152. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48153. return cubeMapData;
  48154. };
  48155. /**
  48156. * Returns the pixels data extracted from an RGBE texture.
  48157. * This pixels will be stored left to right up to down in the R G B order in one array.
  48158. *
  48159. * More information on this format are available here:
  48160. * https://en.wikipedia.org/wiki/RGBE_image_format
  48161. *
  48162. * @param uint8array The binary file stored in an array buffer.
  48163. * @param hdrInfo The header information of the file.
  48164. * @return The pixels data in RGB right to left up to down order.
  48165. */
  48166. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48167. // Keep for multi format supports.
  48168. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48169. };
  48170. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48171. var num_scanlines = hdrInfo.height;
  48172. var scanline_width = hdrInfo.width;
  48173. var a, b, c, d, count;
  48174. var dataIndex = hdrInfo.dataPosition;
  48175. var index = 0, endIndex = 0, i = 0;
  48176. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48177. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48178. // 3 channels of 4 bytes per pixel in float.
  48179. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48180. var resultArray = new Float32Array(resultBuffer);
  48181. // read in each successive scanline
  48182. while (num_scanlines > 0) {
  48183. a = uint8array[dataIndex++];
  48184. b = uint8array[dataIndex++];
  48185. c = uint8array[dataIndex++];
  48186. d = uint8array[dataIndex++];
  48187. if (a != 2 || b != 2 || (c & 0x80)) {
  48188. // this file is not run length encoded
  48189. throw "HDR Bad header format, not RLE";
  48190. }
  48191. if (((c << 8) | d) != scanline_width) {
  48192. throw "HDR Bad header format, wrong scan line width";
  48193. }
  48194. index = 0;
  48195. // read each of the four channels for the scanline into the buffer
  48196. for (i = 0; i < 4; i++) {
  48197. endIndex = (i + 1) * scanline_width;
  48198. while (index < endIndex) {
  48199. a = uint8array[dataIndex++];
  48200. b = uint8array[dataIndex++];
  48201. if (a > 128) {
  48202. // a run of the same value
  48203. count = a - 128;
  48204. if ((count == 0) || (count > endIndex - index)) {
  48205. throw "HDR Bad Format, bad scanline data (run)";
  48206. }
  48207. while (count-- > 0) {
  48208. scanLineArray[index++] = b;
  48209. }
  48210. }
  48211. else {
  48212. // a non-run
  48213. count = a;
  48214. if ((count == 0) || (count > endIndex - index)) {
  48215. throw "HDR Bad Format, bad scanline data (non-run)";
  48216. }
  48217. scanLineArray[index++] = b;
  48218. if (--count > 0) {
  48219. for (var j = 0; j < count; j++) {
  48220. scanLineArray[index++] = uint8array[dataIndex++];
  48221. }
  48222. }
  48223. }
  48224. }
  48225. }
  48226. // now convert data from buffer into floats
  48227. for (i = 0; i < scanline_width; i++) {
  48228. a = scanLineArray[i];
  48229. b = scanLineArray[i + scanline_width];
  48230. c = scanLineArray[i + 2 * scanline_width];
  48231. d = scanLineArray[i + 3 * scanline_width];
  48232. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  48233. }
  48234. num_scanlines--;
  48235. }
  48236. return resultArray;
  48237. };
  48238. return HDRTools;
  48239. }());
  48240. Internals.HDRTools = HDRTools;
  48241. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48242. })(BABYLON || (BABYLON = {}));
  48243. //# sourceMappingURL=babylon.hdr.js.map
  48244. var BABYLON;
  48245. (function (BABYLON) {
  48246. /**
  48247. * This represents a texture coming from an HDR input.
  48248. *
  48249. * The only supported format is currently panorama picture stored in RGBE format.
  48250. * Example of such files can be found on HDRLib: http://hdrlib.com/
  48251. */
  48252. var HDRCubeTexture = (function (_super) {
  48253. __extends(HDRCubeTexture, _super);
  48254. /**
  48255. * Instantiates an HDRTexture from the following parameters.
  48256. *
  48257. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  48258. * @param scene The scene the texture will be used in
  48259. * @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.
  48260. * @param noMipmap Forces to not generate the mipmap if true
  48261. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  48262. * @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)
  48263. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  48264. */
  48265. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  48266. if (noMipmap === void 0) { noMipmap = false; }
  48267. if (generateHarmonics === void 0) { generateHarmonics = true; }
  48268. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  48269. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  48270. if (onLoad === void 0) { onLoad = null; }
  48271. if (onError === void 0) { onError = null; }
  48272. var _this = _super.call(this, scene) || this;
  48273. _this._useInGammaSpace = false;
  48274. _this._generateHarmonics = true;
  48275. _this._isBABYLONPreprocessed = false;
  48276. _this._onLoad = null;
  48277. _this._onError = null;
  48278. /**
  48279. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  48280. */
  48281. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  48282. /**
  48283. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  48284. * This is usefull at run time to apply the good shader.
  48285. */
  48286. _this.isPMREM = false;
  48287. _this._isBlocking = true;
  48288. if (!url) {
  48289. return _this;
  48290. }
  48291. _this.name = url;
  48292. _this.url = url;
  48293. _this.hasAlpha = false;
  48294. _this.isCube = true;
  48295. _this._textureMatrix = BABYLON.Matrix.Identity();
  48296. _this._onLoad = onLoad;
  48297. _this._onError = onError;
  48298. _this.gammaSpace = false;
  48299. if (size) {
  48300. _this._isBABYLONPreprocessed = false;
  48301. _this._noMipmap = noMipmap;
  48302. _this._size = size;
  48303. _this._useInGammaSpace = useInGammaSpace;
  48304. _this._usePMREMGenerator = usePMREMGenerator &&
  48305. scene.getEngine().getCaps().textureLOD &&
  48306. _this.getScene().getEngine().getCaps().textureFloat &&
  48307. !_this._useInGammaSpace;
  48308. }
  48309. else {
  48310. _this._isBABYLONPreprocessed = true;
  48311. _this._noMipmap = false;
  48312. _this._useInGammaSpace = false;
  48313. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  48314. _this.getScene().getEngine().getCaps().textureFloat &&
  48315. !_this._useInGammaSpace;
  48316. }
  48317. _this.isPMREM = _this._usePMREMGenerator;
  48318. _this._texture = _this._getFromCache(url, _this._noMipmap);
  48319. if (!_this._texture) {
  48320. if (!scene.useDelayedTextureLoading) {
  48321. _this.loadTexture();
  48322. }
  48323. else {
  48324. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  48325. }
  48326. }
  48327. return _this;
  48328. }
  48329. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  48330. /**
  48331. * Gets wether or not the texture is blocking during loading.
  48332. */
  48333. get: function () {
  48334. return this._isBlocking;
  48335. },
  48336. /**
  48337. * Sets wether or not the texture is blocking during loading.
  48338. */
  48339. set: function (value) {
  48340. this._isBlocking = value;
  48341. },
  48342. enumerable: true,
  48343. configurable: true
  48344. });
  48345. /**
  48346. * Occurs when the file is a preprocessed .babylon.hdr file.
  48347. */
  48348. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  48349. var _this = this;
  48350. var mipLevels = 0;
  48351. var floatArrayView = null;
  48352. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  48353. var mips = [];
  48354. var startIndex = 30;
  48355. for (var level = 0; level < mipLevels; level++) {
  48356. mips.push([]);
  48357. // Fill each pixel of the mip level.
  48358. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  48359. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48360. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  48361. mips[level].push(faceData);
  48362. startIndex += faceSize;
  48363. }
  48364. }
  48365. return mips;
  48366. } : null;
  48367. var callback = function (buffer) {
  48368. // Create Native Array Views
  48369. var intArrayView = new Int32Array(buffer);
  48370. floatArrayView = new Float32Array(buffer);
  48371. // Fill header.
  48372. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  48373. _this._size = intArrayView[1]; // CubeMap max mip face size.
  48374. // Update Texture Information.
  48375. _this._texture.updateSize(_this._size, _this._size);
  48376. // Fill polynomial information.
  48377. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  48378. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  48379. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  48380. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  48381. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  48382. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  48383. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  48384. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  48385. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  48386. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  48387. _this.sphericalPolynomial = sphericalPolynomial;
  48388. // Fill pixel data.
  48389. mipLevels = intArrayView[29]; // Number of mip levels.
  48390. var startIndex = 30;
  48391. var data = [];
  48392. var faceSize = Math.pow(_this._size, 2) * 3;
  48393. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48394. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  48395. startIndex += faceSize;
  48396. }
  48397. var results = [];
  48398. var byteArray = null;
  48399. // Push each faces.
  48400. for (var k = 0; k < 6; k++) {
  48401. var dataFace = null;
  48402. // To be deprecated.
  48403. if (version === 1) {
  48404. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  48405. dataFace = data[j];
  48406. }
  48407. // If special cases.
  48408. if (!mipmapGenerator) {
  48409. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48410. // 3 channels of 1 bytes per pixel in bytes.
  48411. var byteBuffer = new ArrayBuffer(faceSize);
  48412. byteArray = new Uint8Array(byteBuffer);
  48413. }
  48414. for (var i = 0; i < _this._size * _this._size; i++) {
  48415. // Put in gamma space if requested.
  48416. if (_this._useInGammaSpace) {
  48417. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48418. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48419. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48420. }
  48421. // Convert to int texture for fallback.
  48422. if (byteArray) {
  48423. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48424. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48425. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48426. // May use luminance instead if the result is not accurate.
  48427. var max = Math.max(Math.max(r, g), b);
  48428. if (max > 255) {
  48429. var scale = 255 / max;
  48430. r *= scale;
  48431. g *= scale;
  48432. b *= scale;
  48433. }
  48434. byteArray[(i * 3) + 0] = r;
  48435. byteArray[(i * 3) + 1] = g;
  48436. byteArray[(i * 3) + 2] = b;
  48437. }
  48438. }
  48439. }
  48440. // Fill the array accordingly.
  48441. if (byteArray) {
  48442. results.push(byteArray);
  48443. }
  48444. else {
  48445. results.push(dataFace);
  48446. }
  48447. }
  48448. return results;
  48449. };
  48450. 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);
  48451. };
  48452. /**
  48453. * Occurs when the file is raw .hdr file.
  48454. */
  48455. HDRCubeTexture.prototype.loadHDRTexture = function () {
  48456. var _this = this;
  48457. var callback = function (buffer) {
  48458. // Extract the raw linear data.
  48459. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  48460. // Generate harmonics if needed.
  48461. if (_this._generateHarmonics) {
  48462. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  48463. _this.sphericalPolynomial = sphericalPolynomial;
  48464. }
  48465. var results = [];
  48466. var byteArray = null;
  48467. // Push each faces.
  48468. for (var j = 0; j < 6; j++) {
  48469. // Create uintarray fallback.
  48470. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48471. // 3 channels of 1 bytes per pixel in bytes.
  48472. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  48473. byteArray = new Uint8Array(byteBuffer);
  48474. }
  48475. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  48476. // If special cases.
  48477. if (_this._useInGammaSpace || byteArray) {
  48478. for (var i = 0; i < _this._size * _this._size; i++) {
  48479. // Put in gamma space if requested.
  48480. if (_this._useInGammaSpace) {
  48481. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48482. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48483. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48484. }
  48485. // Convert to int texture for fallback.
  48486. if (byteArray) {
  48487. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48488. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48489. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48490. // May use luminance instead if the result is not accurate.
  48491. var max = Math.max(Math.max(r, g), b);
  48492. if (max > 255) {
  48493. var scale = 255 / max;
  48494. r *= scale;
  48495. g *= scale;
  48496. b *= scale;
  48497. }
  48498. byteArray[(i * 3) + 0] = r;
  48499. byteArray[(i * 3) + 1] = g;
  48500. byteArray[(i * 3) + 2] = b;
  48501. }
  48502. }
  48503. }
  48504. if (byteArray) {
  48505. results.push(byteArray);
  48506. }
  48507. else {
  48508. results.push(dataFace);
  48509. }
  48510. }
  48511. return results;
  48512. };
  48513. var mipmapGenerator = null;
  48514. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  48515. // if (!this._noMipmap &&
  48516. // this._usePMREMGenerator) {
  48517. // mipmapGenerator = (data: ArrayBufferView[]) => {
  48518. // // Custom setup of the generator matching with the PBR shader values.
  48519. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  48520. // this._size,
  48521. // this._size,
  48522. // 0,
  48523. // 3,
  48524. // this.getScene().getEngine().getCaps().textureFloat,
  48525. // 2048,
  48526. // 0.25,
  48527. // false,
  48528. // true);
  48529. // return generator.filterCubeMap();
  48530. // };
  48531. // }
  48532. 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);
  48533. };
  48534. /**
  48535. * Starts the loading process of the texture.
  48536. */
  48537. HDRCubeTexture.prototype.loadTexture = function () {
  48538. if (this._isBABYLONPreprocessed) {
  48539. this.loadBabylonTexture();
  48540. }
  48541. else {
  48542. this.loadHDRTexture();
  48543. }
  48544. };
  48545. HDRCubeTexture.prototype.clone = function () {
  48546. var size = this._isBABYLONPreprocessed ? null : this._size;
  48547. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  48548. // Base texture
  48549. newTexture.level = this.level;
  48550. newTexture.wrapU = this.wrapU;
  48551. newTexture.wrapV = this.wrapV;
  48552. newTexture.coordinatesIndex = this.coordinatesIndex;
  48553. newTexture.coordinatesMode = this.coordinatesMode;
  48554. return newTexture;
  48555. };
  48556. // Methods
  48557. HDRCubeTexture.prototype.delayLoad = function () {
  48558. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  48559. return;
  48560. }
  48561. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  48562. this._texture = this._getFromCache(this.url, this._noMipmap);
  48563. if (!this._texture) {
  48564. this.loadTexture();
  48565. }
  48566. };
  48567. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  48568. return this._textureMatrix;
  48569. };
  48570. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  48571. this._textureMatrix = value;
  48572. };
  48573. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  48574. var texture = null;
  48575. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  48576. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  48577. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  48578. texture.name = parsedTexture.name;
  48579. texture.hasAlpha = parsedTexture.hasAlpha;
  48580. texture.level = parsedTexture.level;
  48581. texture.coordinatesMode = parsedTexture.coordinatesMode;
  48582. texture.isBlocking = parsedTexture.isBlocking;
  48583. }
  48584. return texture;
  48585. };
  48586. HDRCubeTexture.prototype.serialize = function () {
  48587. if (!this.name) {
  48588. return null;
  48589. }
  48590. var serializationObject = {};
  48591. serializationObject.name = this.name;
  48592. serializationObject.hasAlpha = this.hasAlpha;
  48593. serializationObject.isCube = true;
  48594. serializationObject.level = this.level;
  48595. serializationObject.size = this._size;
  48596. serializationObject.coordinatesMode = this.coordinatesMode;
  48597. serializationObject.useInGammaSpace = this._useInGammaSpace;
  48598. serializationObject.generateHarmonics = this._generateHarmonics;
  48599. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  48600. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  48601. serializationObject.customType = "BABYLON.HDRCubeTexture";
  48602. serializationObject.noMipmap = this._noMipmap;
  48603. serializationObject.isBlocking = this._isBlocking;
  48604. return serializationObject;
  48605. };
  48606. /**
  48607. * Saves as a file the data contained in the texture in a binary format.
  48608. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  48609. * as the spherical used in the lighting.
  48610. * @param url The HDR file url.
  48611. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  48612. * @param onError Method called if any error happens during download.
  48613. * @return The packed binary data.
  48614. */
  48615. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  48616. if (onError === void 0) { onError = null; }
  48617. var callback = function (buffer) {
  48618. var data = new Blob([buffer], { type: 'application/octet-stream' });
  48619. // Returns a URL you can use as a href.
  48620. var objUrl = window.URL.createObjectURL(data);
  48621. // Simulates a link to it and click to dowload.
  48622. var a = document.createElement("a");
  48623. document.body.appendChild(a);
  48624. a.style.display = "none";
  48625. a.href = objUrl;
  48626. a.download = "envmap.babylon.hdr";
  48627. a.click();
  48628. };
  48629. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  48630. };
  48631. /**
  48632. * Serializes the data contained in the texture in a binary format.
  48633. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  48634. * as the spherical used in the lighting.
  48635. * @param url The HDR file url.
  48636. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  48637. * @param onError Method called if any error happens during download.
  48638. * @return The packed binary data.
  48639. */
  48640. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  48641. if (onError === void 0) { onError = null; }
  48642. // Needs the url tho create the texture.
  48643. if (!url) {
  48644. return null;
  48645. }
  48646. // Check Power of two size.
  48647. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  48648. return null;
  48649. }
  48650. // Coming Back in 3.1.
  48651. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  48652. return null;
  48653. };
  48654. HDRCubeTexture._facesMapping = [
  48655. "right",
  48656. "left",
  48657. "up",
  48658. "down",
  48659. "front",
  48660. "back"
  48661. ];
  48662. return HDRCubeTexture;
  48663. }(BABYLON.BaseTexture));
  48664. BABYLON.HDRCubeTexture = HDRCubeTexture;
  48665. })(BABYLON || (BABYLON = {}));
  48666. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  48667. var BABYLON;
  48668. (function (BABYLON) {
  48669. var DefaultLoadingScreen = (function () {
  48670. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  48671. if (_loadingText === void 0) { _loadingText = ""; }
  48672. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  48673. var _this = this;
  48674. this._renderingCanvas = _renderingCanvas;
  48675. this._loadingText = _loadingText;
  48676. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  48677. // Resize
  48678. this._resizeLoadingUI = function () {
  48679. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  48680. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  48681. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  48682. _this._loadingDiv.style.left = canvasRect.left + "px";
  48683. _this._loadingDiv.style.top = canvasRect.top + "px";
  48684. _this._loadingDiv.style.width = canvasRect.width + "px";
  48685. _this._loadingDiv.style.height = canvasRect.height + "px";
  48686. };
  48687. }
  48688. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  48689. if (this._loadingDiv) {
  48690. // Do not add a loading screen if there is already one
  48691. return;
  48692. }
  48693. this._loadingDiv = document.createElement("div");
  48694. this._loadingDiv.id = "babylonjsLoadingDiv";
  48695. this._loadingDiv.style.opacity = "0";
  48696. this._loadingDiv.style.transition = "opacity 1.5s ease";
  48697. // Loading text
  48698. this._loadingTextDiv = document.createElement("div");
  48699. this._loadingTextDiv.style.position = "absolute";
  48700. this._loadingTextDiv.style.left = "0";
  48701. this._loadingTextDiv.style.top = "50%";
  48702. this._loadingTextDiv.style.marginTop = "80px";
  48703. this._loadingTextDiv.style.width = "100%";
  48704. this._loadingTextDiv.style.height = "20px";
  48705. this._loadingTextDiv.style.fontFamily = "Arial";
  48706. this._loadingTextDiv.style.fontSize = "14px";
  48707. this._loadingTextDiv.style.color = "white";
  48708. this._loadingTextDiv.style.textAlign = "center";
  48709. this._loadingTextDiv.innerHTML = "Loading";
  48710. this._loadingDiv.appendChild(this._loadingTextDiv);
  48711. //set the predefined text
  48712. this._loadingTextDiv.innerHTML = this._loadingText;
  48713. // Generating keyframes
  48714. var style = document.createElement('style');
  48715. style.type = 'text/css';
  48716. 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 }";
  48717. style.innerHTML = keyFrames;
  48718. document.getElementsByTagName('head')[0].appendChild(style);
  48719. // Loading img
  48720. var imgBack = new Image();
  48721. 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";
  48722. imgBack.style.position = "absolute";
  48723. imgBack.style.left = "50%";
  48724. imgBack.style.top = "50%";
  48725. imgBack.style.marginLeft = "-60px";
  48726. imgBack.style.marginTop = "-60px";
  48727. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  48728. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  48729. imgBack.style.transformOrigin = "50% 50%";
  48730. imgBack.style.webkitTransformOrigin = "50% 50%";
  48731. this._loadingDiv.appendChild(imgBack);
  48732. this._resizeLoadingUI();
  48733. window.addEventListener("resize", this._resizeLoadingUI);
  48734. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48735. document.body.appendChild(this._loadingDiv);
  48736. this._loadingDiv.style.opacity = "1";
  48737. };
  48738. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  48739. var _this = this;
  48740. if (!this._loadingDiv) {
  48741. return;
  48742. }
  48743. var onTransitionEnd = function () {
  48744. if (!_this._loadingDiv) {
  48745. return;
  48746. }
  48747. document.body.removeChild(_this._loadingDiv);
  48748. window.removeEventListener("resize", _this._resizeLoadingUI);
  48749. _this._loadingDiv = null;
  48750. };
  48751. this._loadingDiv.style.opacity = "0";
  48752. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  48753. };
  48754. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  48755. set: function (text) {
  48756. this._loadingText = text;
  48757. if (this._loadingTextDiv) {
  48758. this._loadingTextDiv.innerHTML = this._loadingText;
  48759. }
  48760. },
  48761. enumerable: true,
  48762. configurable: true
  48763. });
  48764. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  48765. get: function () {
  48766. return this._loadingDivBackgroundColor;
  48767. },
  48768. set: function (color) {
  48769. this._loadingDivBackgroundColor = color;
  48770. if (!this._loadingDiv) {
  48771. return;
  48772. }
  48773. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48774. },
  48775. enumerable: true,
  48776. configurable: true
  48777. });
  48778. return DefaultLoadingScreen;
  48779. }());
  48780. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  48781. })(BABYLON || (BABYLON = {}));
  48782. //# sourceMappingURL=babylon.loadingScreen.js.map
  48783. var BABYLON;
  48784. (function (BABYLON) {
  48785. var SceneLoader = (function () {
  48786. function SceneLoader() {
  48787. }
  48788. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  48789. get: function () {
  48790. return 0;
  48791. },
  48792. enumerable: true,
  48793. configurable: true
  48794. });
  48795. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  48796. get: function () {
  48797. return 1;
  48798. },
  48799. enumerable: true,
  48800. configurable: true
  48801. });
  48802. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  48803. get: function () {
  48804. return 2;
  48805. },
  48806. enumerable: true,
  48807. configurable: true
  48808. });
  48809. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  48810. get: function () {
  48811. return 3;
  48812. },
  48813. enumerable: true,
  48814. configurable: true
  48815. });
  48816. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  48817. get: function () {
  48818. return SceneLoader._ForceFullSceneLoadingForIncremental;
  48819. },
  48820. set: function (value) {
  48821. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  48822. },
  48823. enumerable: true,
  48824. configurable: true
  48825. });
  48826. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  48827. get: function () {
  48828. return SceneLoader._ShowLoadingScreen;
  48829. },
  48830. set: function (value) {
  48831. SceneLoader._ShowLoadingScreen = value;
  48832. },
  48833. enumerable: true,
  48834. configurable: true
  48835. });
  48836. Object.defineProperty(SceneLoader, "loggingLevel", {
  48837. get: function () {
  48838. return SceneLoader._loggingLevel;
  48839. },
  48840. set: function (value) {
  48841. SceneLoader._loggingLevel = value;
  48842. },
  48843. enumerable: true,
  48844. configurable: true
  48845. });
  48846. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  48847. get: function () {
  48848. return SceneLoader._CleanBoneMatrixWeights;
  48849. },
  48850. set: function (value) {
  48851. SceneLoader._CleanBoneMatrixWeights = value;
  48852. },
  48853. enumerable: true,
  48854. configurable: true
  48855. });
  48856. SceneLoader._getDefaultPlugin = function () {
  48857. return SceneLoader._registeredPlugins[".babylon"];
  48858. };
  48859. SceneLoader._getPluginForExtension = function (extension) {
  48860. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  48861. if (registeredPlugin) {
  48862. return registeredPlugin;
  48863. }
  48864. return SceneLoader._getDefaultPlugin();
  48865. };
  48866. SceneLoader._getPluginForDirectLoad = function (data) {
  48867. for (var extension in SceneLoader._registeredPlugins) {
  48868. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  48869. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  48870. return SceneLoader._registeredPlugins[extension];
  48871. }
  48872. }
  48873. return SceneLoader._getDefaultPlugin();
  48874. };
  48875. SceneLoader._getPluginForFilename = function (sceneFilename) {
  48876. if (sceneFilename.name) {
  48877. sceneFilename = sceneFilename.name;
  48878. }
  48879. var dotPosition = sceneFilename.lastIndexOf(".");
  48880. var queryStringPosition = sceneFilename.indexOf("?");
  48881. if (queryStringPosition === -1) {
  48882. queryStringPosition = sceneFilename.length;
  48883. }
  48884. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  48885. return SceneLoader._getPluginForExtension(extension);
  48886. };
  48887. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  48888. SceneLoader._getDirectLoad = function (sceneFilename) {
  48889. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  48890. return sceneFilename.substr(5);
  48891. }
  48892. return null;
  48893. };
  48894. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48895. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  48896. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  48897. var plugin = registeredPlugin.plugin;
  48898. var useArrayBuffer = registeredPlugin.isBinary;
  48899. var database;
  48900. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  48901. var dataCallback = function (data) {
  48902. if (scene.isDisposed) {
  48903. onError("Scene has been disposed");
  48904. return;
  48905. }
  48906. scene.database = database;
  48907. try {
  48908. onSuccess(plugin, data);
  48909. }
  48910. catch (e) {
  48911. onError(null, e);
  48912. }
  48913. };
  48914. var manifestChecked = function (success) {
  48915. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  48916. onError(request.status + " " + request.statusText);
  48917. });
  48918. };
  48919. if (directLoad) {
  48920. dataCallback(directLoad);
  48921. return;
  48922. }
  48923. if (rootUrl.indexOf("file:") === -1) {
  48924. if (scene.getEngine().enableOfflineSupport) {
  48925. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  48926. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  48927. }
  48928. else {
  48929. manifestChecked(true);
  48930. }
  48931. }
  48932. else {
  48933. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  48934. }
  48935. };
  48936. // Public functions
  48937. SceneLoader.GetPluginForExtension = function (extension) {
  48938. return SceneLoader._getPluginForExtension(extension).plugin;
  48939. };
  48940. SceneLoader.RegisterPlugin = function (plugin) {
  48941. if (typeof plugin.extensions === "string") {
  48942. var extension = plugin.extensions;
  48943. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48944. plugin: plugin,
  48945. isBinary: false
  48946. };
  48947. }
  48948. else {
  48949. var extensions = plugin.extensions;
  48950. Object.keys(extensions).forEach(function (extension) {
  48951. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48952. plugin: plugin,
  48953. isBinary: extensions[extension].isBinary
  48954. };
  48955. });
  48956. }
  48957. };
  48958. /**
  48959. * Import meshes into a scene
  48960. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  48961. * @param rootUrl a string that defines the root url for scene and resources
  48962. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48963. * @param scene the instance of BABYLON.Scene to append to
  48964. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  48965. * @param onProgress a callback with a progress event for each file being loaded
  48966. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48967. */
  48968. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48969. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48970. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48971. return;
  48972. }
  48973. var loadingToken = {};
  48974. scene._addPendingData(loadingToken);
  48975. var errorHandler = function (message, exception) {
  48976. if (onError) {
  48977. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48978. }
  48979. scene._removePendingData(loadingToken);
  48980. };
  48981. var progressHandler = function (event) {
  48982. if (onProgress) {
  48983. onProgress(event);
  48984. }
  48985. };
  48986. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48987. if (plugin.importMesh) {
  48988. var syncedPlugin = plugin;
  48989. var meshes = [];
  48990. var particleSystems = [];
  48991. var skeletons = [];
  48992. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  48993. return;
  48994. }
  48995. if (onSuccess) {
  48996. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48997. onSuccess(meshes, particleSystems, skeletons);
  48998. scene._removePendingData(loadingToken);
  48999. }
  49000. }
  49001. else {
  49002. var asyncedPlugin = plugin;
  49003. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  49004. if (onSuccess) {
  49005. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49006. onSuccess(meshes, particleSystems, skeletons);
  49007. scene._removePendingData(loadingToken);
  49008. }
  49009. }, progressHandler, errorHandler);
  49010. }
  49011. }, progressHandler, errorHandler);
  49012. };
  49013. /**
  49014. * Load a scene
  49015. * @param rootUrl a string that defines the root url for scene and resources
  49016. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49017. * @param engine is the instance of BABYLON.Engine to use to create the scene
  49018. * @param onSuccess a callback with the scene when import succeeds
  49019. * @param onProgress a callback with a progress event for each file being loaded
  49020. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49021. */
  49022. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  49023. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  49024. };
  49025. /**
  49026. * Append a scene
  49027. * @param rootUrl a string that defines the root url for scene and resources
  49028. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49029. * @param scene is the instance of BABYLON.Scene to append to
  49030. * @param onSuccess a callback with the scene when import succeeds
  49031. * @param onProgress a callback with a progress event for each file being loaded
  49032. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49033. */
  49034. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49035. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49036. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49037. return;
  49038. }
  49039. if (SceneLoader.ShowLoadingScreen) {
  49040. scene.getEngine().displayLoadingUI();
  49041. }
  49042. var loadingToken = {};
  49043. scene._addPendingData(loadingToken);
  49044. var errorHandler = function (message, exception) {
  49045. if (onError) {
  49046. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49047. }
  49048. scene._removePendingData(loadingToken);
  49049. scene.getEngine().hideLoadingUI();
  49050. };
  49051. var progressHandler = function (event) {
  49052. if (onProgress) {
  49053. onProgress(event);
  49054. }
  49055. };
  49056. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49057. if (plugin.load) {
  49058. var syncedPlugin = plugin;
  49059. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  49060. return;
  49061. }
  49062. if (onSuccess) {
  49063. onSuccess(scene);
  49064. }
  49065. scene.loadingPluginName = plugin.name;
  49066. scene._removePendingData(loadingToken);
  49067. }
  49068. else {
  49069. var asyncedPlugin = plugin;
  49070. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  49071. if (onSuccess) {
  49072. onSuccess(scene);
  49073. }
  49074. scene.loadingPluginName = plugin.name;
  49075. scene._removePendingData(loadingToken);
  49076. }, progressHandler, errorHandler);
  49077. }
  49078. if (SceneLoader.ShowLoadingScreen) {
  49079. scene.executeWhenReady(function () {
  49080. scene.getEngine().hideLoadingUI();
  49081. });
  49082. }
  49083. }, progressHandler, errorHandler);
  49084. };
  49085. // Flags
  49086. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  49087. SceneLoader._ShowLoadingScreen = true;
  49088. SceneLoader._CleanBoneMatrixWeights = false;
  49089. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  49090. // Members
  49091. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  49092. SceneLoader._registeredPlugins = {};
  49093. return SceneLoader;
  49094. }());
  49095. BABYLON.SceneLoader = SceneLoader;
  49096. ;
  49097. })(BABYLON || (BABYLON = {}));
  49098. //# sourceMappingURL=babylon.sceneLoader.js.map
  49099. var BABYLON;
  49100. (function (BABYLON) {
  49101. var Internals;
  49102. (function (Internals) {
  49103. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  49104. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49105. var parsedMaterial = parsedData.materials[index];
  49106. if (parsedMaterial.id === id) {
  49107. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49108. }
  49109. }
  49110. return null;
  49111. };
  49112. var isDescendantOf = function (mesh, names, hierarchyIds) {
  49113. for (var i in names) {
  49114. if (mesh.name === names[i]) {
  49115. hierarchyIds.push(mesh.id);
  49116. return true;
  49117. }
  49118. }
  49119. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  49120. hierarchyIds.push(mesh.id);
  49121. return true;
  49122. }
  49123. return false;
  49124. };
  49125. var logOperation = function (operation, producer) {
  49126. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  49127. };
  49128. BABYLON.SceneLoader.RegisterPlugin({
  49129. name: "babylon.js",
  49130. extensions: ".babylon",
  49131. canDirectLoad: function (data) {
  49132. if (data.indexOf("babylon") !== -1) {
  49133. return true;
  49134. }
  49135. return false;
  49136. },
  49137. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  49138. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49139. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49140. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49141. // and avoid problems with multiple concurrent .babylon loads.
  49142. var log = "importMesh has failed JSON parse";
  49143. try {
  49144. var parsedData = JSON.parse(data);
  49145. log = "";
  49146. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49147. if (!meshesNames) {
  49148. meshesNames = null;
  49149. }
  49150. else if (!Array.isArray(meshesNames)) {
  49151. meshesNames = [meshesNames];
  49152. }
  49153. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49154. var loadedSkeletonsIds = [];
  49155. var loadedMaterialsIds = [];
  49156. var hierarchyIds = [];
  49157. var index;
  49158. var cache;
  49159. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49160. var parsedMesh = parsedData.meshes[index];
  49161. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  49162. if (meshesNames !== null) {
  49163. // Remove found mesh name from list.
  49164. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  49165. }
  49166. //Geometry?
  49167. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  49168. //does the file contain geometries?
  49169. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  49170. //find the correct geometry and add it to the scene
  49171. var found = false;
  49172. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  49173. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  49174. return;
  49175. }
  49176. else {
  49177. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  49178. if (parsedGeometryData.id === parsedMesh.geometryId) {
  49179. switch (geometryType) {
  49180. case "boxes":
  49181. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  49182. break;
  49183. case "spheres":
  49184. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  49185. break;
  49186. case "cylinders":
  49187. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  49188. break;
  49189. case "toruses":
  49190. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  49191. break;
  49192. case "grounds":
  49193. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  49194. break;
  49195. case "planes":
  49196. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  49197. break;
  49198. case "torusKnots":
  49199. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  49200. break;
  49201. case "vertexData":
  49202. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  49203. break;
  49204. }
  49205. found = true;
  49206. }
  49207. });
  49208. }
  49209. });
  49210. if (found === false) {
  49211. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  49212. }
  49213. }
  49214. }
  49215. // Material ?
  49216. if (parsedMesh.materialId) {
  49217. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  49218. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49219. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  49220. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  49221. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  49222. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  49223. var subMatId = parsedMultiMaterial.materials[matIndex];
  49224. loadedMaterialsIds.push(subMatId);
  49225. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  49226. log += "\n\tMaterial " + mat.toString(fullDetails);
  49227. }
  49228. loadedMaterialsIds.push(parsedMultiMaterial.id);
  49229. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49230. materialFound = true;
  49231. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  49232. break;
  49233. }
  49234. }
  49235. }
  49236. if (materialFound === false) {
  49237. loadedMaterialsIds.push(parsedMesh.materialId);
  49238. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  49239. if (!mat) {
  49240. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  49241. }
  49242. else {
  49243. log += "\n\tMaterial " + mat.toString(fullDetails);
  49244. }
  49245. }
  49246. }
  49247. // Skeleton ?
  49248. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49249. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  49250. if (skeletonAlreadyLoaded === false) {
  49251. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  49252. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  49253. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  49254. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49255. skeletons.push(skeleton);
  49256. loadedSkeletonsIds.push(parsedSkeleton.id);
  49257. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  49258. }
  49259. }
  49260. }
  49261. }
  49262. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49263. meshes.push(mesh);
  49264. log += "\n\tMesh " + mesh.toString(fullDetails);
  49265. }
  49266. }
  49267. // Connecting parents
  49268. var currentMesh;
  49269. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49270. currentMesh = scene.meshes[index];
  49271. if (currentMesh._waitingParentId) {
  49272. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  49273. currentMesh._waitingParentId = undefined;
  49274. }
  49275. }
  49276. // freeze and compute world matrix application
  49277. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49278. currentMesh = scene.meshes[index];
  49279. if (currentMesh._waitingFreezeWorldMatrix) {
  49280. currentMesh.freezeWorldMatrix();
  49281. currentMesh._waitingFreezeWorldMatrix = undefined;
  49282. }
  49283. else {
  49284. currentMesh.computeWorldMatrix(true);
  49285. }
  49286. }
  49287. }
  49288. // Particles
  49289. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49290. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49291. var parsedParticleSystem = parsedData.particleSystems[index];
  49292. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  49293. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  49294. }
  49295. }
  49296. }
  49297. return true;
  49298. }
  49299. catch (err) {
  49300. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  49301. log = null;
  49302. throw err;
  49303. }
  49304. finally {
  49305. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49306. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49307. }
  49308. }
  49309. },
  49310. load: function (scene, data, rootUrl) {
  49311. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49312. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49313. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49314. // and avoid problems with multiple concurrent .babylon loads.
  49315. var log = "importScene has failed JSON parse";
  49316. try {
  49317. var parsedData = JSON.parse(data);
  49318. log = "";
  49319. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49320. // Scene
  49321. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  49322. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  49323. }
  49324. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  49325. scene.autoClear = parsedData.autoClear;
  49326. }
  49327. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  49328. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  49329. }
  49330. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  49331. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  49332. }
  49333. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  49334. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  49335. }
  49336. // Fog
  49337. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  49338. scene.fogMode = parsedData.fogMode;
  49339. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  49340. scene.fogStart = parsedData.fogStart;
  49341. scene.fogEnd = parsedData.fogEnd;
  49342. scene.fogDensity = parsedData.fogDensity;
  49343. log += "\tFog mode for scene: ";
  49344. switch (scene.fogMode) {
  49345. // getters not compiling, so using hardcoded
  49346. case 1:
  49347. log += "exp\n";
  49348. break;
  49349. case 2:
  49350. log += "exp2\n";
  49351. break;
  49352. case 3:
  49353. log += "linear\n";
  49354. break;
  49355. }
  49356. }
  49357. //Physics
  49358. if (parsedData.physicsEnabled) {
  49359. var physicsPlugin;
  49360. if (parsedData.physicsEngine === "cannon") {
  49361. physicsPlugin = new BABYLON.CannonJSPlugin();
  49362. }
  49363. else if (parsedData.physicsEngine === "oimo") {
  49364. physicsPlugin = new BABYLON.OimoJSPlugin();
  49365. }
  49366. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  49367. //else - default engine, which is currently oimo
  49368. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  49369. scene.enablePhysics(physicsGravity, physicsPlugin);
  49370. }
  49371. // Metadata
  49372. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  49373. scene.metadata = parsedData.metadata;
  49374. }
  49375. //collisions, if defined. otherwise, default is true
  49376. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  49377. scene.collisionsEnabled = parsedData.collisionsEnabled;
  49378. }
  49379. scene.workerCollisions = !!parsedData.workerCollisions;
  49380. var index;
  49381. var cache;
  49382. // Lights
  49383. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  49384. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  49385. var parsedLight = parsedData.lights[index];
  49386. var light = BABYLON.Light.Parse(parsedLight, scene);
  49387. log += (index === 0 ? "\n\tLights:" : "");
  49388. log += "\n\t\t" + light.toString(fullDetails);
  49389. }
  49390. }
  49391. // Animations
  49392. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  49393. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  49394. var parsedAnimation = parsedData.animations[index];
  49395. var animation = BABYLON.Animation.Parse(parsedAnimation);
  49396. scene.animations.push(animation);
  49397. log += (index === 0 ? "\n\tAnimations:" : "");
  49398. log += "\n\t\t" + animation.toString(fullDetails);
  49399. }
  49400. }
  49401. if (parsedData.autoAnimate) {
  49402. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  49403. }
  49404. // Materials
  49405. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  49406. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49407. var parsedMaterial = parsedData.materials[index];
  49408. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49409. log += (index === 0 ? "\n\tMaterials:" : "");
  49410. log += "\n\t\t" + mat.toString(fullDetails);
  49411. }
  49412. }
  49413. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49414. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  49415. var parsedMultiMaterial = parsedData.multiMaterials[index];
  49416. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49417. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  49418. log += "\n\t\t" + mmat.toString(fullDetails);
  49419. }
  49420. }
  49421. // Morph targets
  49422. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  49423. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  49424. var managerData = _a[_i];
  49425. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  49426. }
  49427. }
  49428. // Skeletons
  49429. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49430. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  49431. var parsedSkeleton = parsedData.skeletons[index];
  49432. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49433. log += (index === 0 ? "\n\tSkeletons:" : "");
  49434. log += "\n\t\t" + skeleton.toString(fullDetails);
  49435. }
  49436. }
  49437. // Geometries
  49438. var geometries = parsedData.geometries;
  49439. if (geometries !== undefined && geometries !== null) {
  49440. // Boxes
  49441. var boxes = geometries.boxes;
  49442. if (boxes !== undefined && boxes !== null) {
  49443. for (index = 0, cache = boxes.length; index < cache; index++) {
  49444. var parsedBox = boxes[index];
  49445. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  49446. }
  49447. }
  49448. // Spheres
  49449. var spheres = geometries.spheres;
  49450. if (spheres !== undefined && spheres !== null) {
  49451. for (index = 0, cache = spheres.length; index < cache; index++) {
  49452. var parsedSphere = spheres[index];
  49453. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  49454. }
  49455. }
  49456. // Cylinders
  49457. var cylinders = geometries.cylinders;
  49458. if (cylinders !== undefined && cylinders !== null) {
  49459. for (index = 0, cache = cylinders.length; index < cache; index++) {
  49460. var parsedCylinder = cylinders[index];
  49461. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  49462. }
  49463. }
  49464. // Toruses
  49465. var toruses = geometries.toruses;
  49466. if (toruses !== undefined && toruses !== null) {
  49467. for (index = 0, cache = toruses.length; index < cache; index++) {
  49468. var parsedTorus = toruses[index];
  49469. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  49470. }
  49471. }
  49472. // Grounds
  49473. var grounds = geometries.grounds;
  49474. if (grounds !== undefined && grounds !== null) {
  49475. for (index = 0, cache = grounds.length; index < cache; index++) {
  49476. var parsedGround = grounds[index];
  49477. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  49478. }
  49479. }
  49480. // Planes
  49481. var planes = geometries.planes;
  49482. if (planes !== undefined && planes !== null) {
  49483. for (index = 0, cache = planes.length; index < cache; index++) {
  49484. var parsedPlane = planes[index];
  49485. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  49486. }
  49487. }
  49488. // TorusKnots
  49489. var torusKnots = geometries.torusKnots;
  49490. if (torusKnots !== undefined && torusKnots !== null) {
  49491. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  49492. var parsedTorusKnot = torusKnots[index];
  49493. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  49494. }
  49495. }
  49496. // VertexData
  49497. var vertexData = geometries.vertexData;
  49498. if (vertexData !== undefined && vertexData !== null) {
  49499. for (index = 0, cache = vertexData.length; index < cache; index++) {
  49500. var parsedVertexData = vertexData[index];
  49501. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  49502. }
  49503. }
  49504. }
  49505. // Meshes
  49506. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49507. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49508. var parsedMesh = parsedData.meshes[index];
  49509. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49510. log += (index === 0 ? "\n\tMeshes:" : "");
  49511. log += "\n\t\t" + mesh.toString(fullDetails);
  49512. }
  49513. }
  49514. // Cameras
  49515. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  49516. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  49517. var parsedCamera = parsedData.cameras[index];
  49518. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  49519. log += (index === 0 ? "\n\tCameras:" : "");
  49520. log += "\n\t\t" + camera.toString(fullDetails);
  49521. }
  49522. }
  49523. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  49524. scene.setActiveCameraByID(parsedData.activeCameraID);
  49525. }
  49526. // Browsing all the graph to connect the dots
  49527. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  49528. var camera = scene.cameras[index];
  49529. if (camera._waitingParentId) {
  49530. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  49531. camera._waitingParentId = undefined;
  49532. }
  49533. }
  49534. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49535. var light = scene.lights[index];
  49536. if (light._waitingParentId) {
  49537. light.parent = scene.getLastEntryByID(light._waitingParentId);
  49538. light._waitingParentId = undefined;
  49539. }
  49540. }
  49541. // Sounds
  49542. var loadedSounds = [];
  49543. var loadedSound;
  49544. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  49545. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  49546. var parsedSound = parsedData.sounds[index];
  49547. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49548. if (!parsedSound.url)
  49549. parsedSound.url = parsedSound.name;
  49550. if (!loadedSounds[parsedSound.url]) {
  49551. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  49552. loadedSounds[parsedSound.url] = loadedSound;
  49553. }
  49554. else {
  49555. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  49556. }
  49557. }
  49558. else {
  49559. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  49560. }
  49561. }
  49562. }
  49563. loadedSounds = [];
  49564. // Connect parents & children and parse actions
  49565. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49566. var mesh = scene.meshes[index];
  49567. if (mesh._waitingParentId) {
  49568. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  49569. mesh._waitingParentId = undefined;
  49570. }
  49571. if (mesh._waitingActions) {
  49572. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  49573. mesh._waitingActions = undefined;
  49574. }
  49575. }
  49576. // freeze world matrix application
  49577. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49578. var currentMesh = scene.meshes[index];
  49579. if (currentMesh._waitingFreezeWorldMatrix) {
  49580. currentMesh.freezeWorldMatrix();
  49581. currentMesh._waitingFreezeWorldMatrix = undefined;
  49582. }
  49583. else {
  49584. currentMesh.computeWorldMatrix(true);
  49585. }
  49586. }
  49587. // Particles Systems
  49588. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49589. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49590. var parsedParticleSystem = parsedData.particleSystems[index];
  49591. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  49592. }
  49593. }
  49594. // Lens flares
  49595. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  49596. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  49597. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  49598. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  49599. }
  49600. }
  49601. // Shadows
  49602. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  49603. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  49604. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  49605. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  49606. }
  49607. }
  49608. // Lights exclusions / inclusions
  49609. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49610. var light = scene.lights[index];
  49611. // Excluded check
  49612. if (light._excludedMeshesIds.length > 0) {
  49613. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  49614. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  49615. if (excludedMesh) {
  49616. light.excludedMeshes.push(excludedMesh);
  49617. }
  49618. }
  49619. light._excludedMeshesIds = [];
  49620. }
  49621. // Included check
  49622. if (light._includedOnlyMeshesIds.length > 0) {
  49623. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  49624. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  49625. if (includedOnlyMesh) {
  49626. light.includedOnlyMeshes.push(includedOnlyMesh);
  49627. }
  49628. }
  49629. light._includedOnlyMeshesIds = [];
  49630. }
  49631. }
  49632. // Actions (scene)
  49633. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  49634. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  49635. }
  49636. // Finish
  49637. return true;
  49638. }
  49639. catch (err) {
  49640. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  49641. log = null;
  49642. throw err;
  49643. }
  49644. finally {
  49645. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49646. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49647. }
  49648. }
  49649. }
  49650. });
  49651. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49652. })(BABYLON || (BABYLON = {}));
  49653. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  49654. var BABYLON;
  49655. (function (BABYLON) {
  49656. var FilesInput = (function () {
  49657. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  49658. this._engine = engine;
  49659. this._currentScene = scene;
  49660. this._sceneLoadedCallback = sceneLoadedCallback;
  49661. this._progressCallback = progressCallback;
  49662. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  49663. this._textureLoadingCallback = textureLoadingCallback;
  49664. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  49665. this._onReloadCallback = onReloadCallback;
  49666. }
  49667. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  49668. var _this = this;
  49669. if (elementToMonitor) {
  49670. this._elementToMonitor = elementToMonitor;
  49671. this._dragEnterHandler = function (e) { _this.drag(e); };
  49672. this._dragOverHandler = function (e) { _this.drag(e); };
  49673. this._dropHandler = function (e) { _this.drop(e); };
  49674. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  49675. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  49676. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  49677. }
  49678. };
  49679. FilesInput.prototype.dispose = function () {
  49680. if (!this._elementToMonitor) {
  49681. return;
  49682. }
  49683. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  49684. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  49685. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  49686. };
  49687. FilesInput.prototype.renderFunction = function () {
  49688. if (this._additionalRenderLoopLogicCallback) {
  49689. this._additionalRenderLoopLogicCallback();
  49690. }
  49691. if (this._currentScene) {
  49692. if (this._textureLoadingCallback) {
  49693. var remaining = this._currentScene.getWaitingItemsCount();
  49694. if (remaining > 0) {
  49695. this._textureLoadingCallback(remaining);
  49696. }
  49697. }
  49698. this._currentScene.render();
  49699. }
  49700. };
  49701. FilesInput.prototype.drag = function (e) {
  49702. e.stopPropagation();
  49703. e.preventDefault();
  49704. };
  49705. FilesInput.prototype.drop = function (eventDrop) {
  49706. eventDrop.stopPropagation();
  49707. eventDrop.preventDefault();
  49708. this.loadFiles(eventDrop);
  49709. };
  49710. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  49711. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  49712. reader.readEntries(function (fileEntries) {
  49713. var remaining = fileEntries.length;
  49714. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  49715. var fileEntry = fileEntries_1[_i];
  49716. if (fileEntry.isFile) {
  49717. fileEntry.file(function (file) {
  49718. file.correctName = relativePath + file.name;
  49719. files.push(file);
  49720. remaining--;
  49721. if (remaining === 0) {
  49722. callback();
  49723. }
  49724. });
  49725. }
  49726. else {
  49727. remaining--;
  49728. if (remaining === 0) {
  49729. callback();
  49730. }
  49731. }
  49732. }
  49733. });
  49734. };
  49735. FilesInput.prototype._processFiles = function (files) {
  49736. for (var i = 0; i < files.length; i++) {
  49737. var name = files[i].correctName.toLowerCase();
  49738. var extension = name.split('.').pop();
  49739. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  49740. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  49741. this._sceneFileToLoad = files[i];
  49742. }
  49743. else {
  49744. FilesInput.FilesToLoad[name] = files[i];
  49745. }
  49746. }
  49747. if (this._onReloadCallback) {
  49748. this._onReloadCallback(this._sceneFileToLoad);
  49749. }
  49750. else {
  49751. this.reload();
  49752. }
  49753. };
  49754. FilesInput.prototype.loadFiles = function (event) {
  49755. var _this = this;
  49756. if (this._startingProcessingFilesCallback)
  49757. this._startingProcessingFilesCallback();
  49758. // Handling data transfer via drag'n'drop
  49759. if (event && event.dataTransfer && event.dataTransfer.files) {
  49760. this._filesToLoad = event.dataTransfer.files;
  49761. }
  49762. // Handling files from input files
  49763. if (event && event.target && event.target.files) {
  49764. this._filesToLoad = event.target.files;
  49765. }
  49766. if (this._filesToLoad && this._filesToLoad.length > 0) {
  49767. var files_1 = [];
  49768. var folders = [];
  49769. var items = event.dataTransfer ? event.dataTransfer.items : null;
  49770. for (var i = 0; i < this._filesToLoad.length; i++) {
  49771. var fileToLoad = this._filesToLoad[i];
  49772. var name_1 = fileToLoad.name.toLowerCase();
  49773. var type = fileToLoad.type;
  49774. var entry = void 0;
  49775. fileToLoad.correctName = name_1;
  49776. if (items) {
  49777. var item = items[i];
  49778. if (item.getAsEntry) {
  49779. entry = item.getAsEntry();
  49780. }
  49781. else if (item.webkitGetAsEntry) {
  49782. entry = item.webkitGetAsEntry();
  49783. }
  49784. }
  49785. if (!entry) {
  49786. files_1.push(fileToLoad);
  49787. }
  49788. else {
  49789. if (entry.isDirectory) {
  49790. folders.push(entry);
  49791. }
  49792. else {
  49793. files_1.push(fileToLoad);
  49794. }
  49795. }
  49796. }
  49797. if (folders.length === 0) {
  49798. this._processFiles(files_1);
  49799. }
  49800. else {
  49801. var remaining = folders.length;
  49802. // Extract folder content
  49803. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  49804. var folder = folders_1[_i];
  49805. this._handleFolderDrop(folder, files_1, function () {
  49806. remaining--;
  49807. if (remaining === 0) {
  49808. _this._processFiles(files_1);
  49809. }
  49810. });
  49811. }
  49812. }
  49813. }
  49814. };
  49815. FilesInput.prototype.reload = function () {
  49816. var _this = this;
  49817. // If a ".babylon" file has been provided
  49818. if (this._sceneFileToLoad) {
  49819. if (this._currentScene) {
  49820. if (BABYLON.Tools.errorsCount > 0) {
  49821. BABYLON.Tools.ClearLogCache();
  49822. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  49823. }
  49824. this._engine.stopRenderLoop();
  49825. this._currentScene.dispose();
  49826. }
  49827. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  49828. _this._currentScene = newScene;
  49829. if (_this._sceneLoadedCallback) {
  49830. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  49831. }
  49832. // Wait for textures and shaders to be ready
  49833. _this._currentScene.executeWhenReady(function () {
  49834. _this._engine.runRenderLoop(function () {
  49835. _this.renderFunction();
  49836. });
  49837. });
  49838. }, function (progress) {
  49839. if (_this._progressCallback) {
  49840. _this._progressCallback(progress);
  49841. }
  49842. });
  49843. }
  49844. else {
  49845. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  49846. }
  49847. };
  49848. FilesInput.FilesToLoad = new Array();
  49849. return FilesInput;
  49850. }());
  49851. BABYLON.FilesInput = FilesInput;
  49852. })(BABYLON || (BABYLON = {}));
  49853. //# sourceMappingURL=babylon.filesInput.js.map
  49854. var BABYLON;
  49855. (function (BABYLON) {
  49856. var FramingBehavior = (function () {
  49857. function FramingBehavior() {
  49858. this._mode = FramingBehavior.FitFrustumSidesMode;
  49859. this._radiusScale = 1.0;
  49860. this._positionScale = 0.5;
  49861. this._defaultElevation = 0.3;
  49862. this._elevationReturnTime = 1500;
  49863. this._elevationReturnWaitTime = 1000;
  49864. this._zoomStopsAnimation = false;
  49865. this._framingTime = 1500;
  49866. this._isPointerDown = false;
  49867. this._lastFrameTime = null;
  49868. this._lastInteractionTime = -Infinity;
  49869. // Framing control
  49870. this._animatables = new Array();
  49871. this._betaIsAnimating = false;
  49872. this._lastFrameRadius = 0;
  49873. }
  49874. Object.defineProperty(FramingBehavior.prototype, "name", {
  49875. get: function () {
  49876. return "Framing";
  49877. },
  49878. enumerable: true,
  49879. configurable: true
  49880. });
  49881. Object.defineProperty(FramingBehavior.prototype, "mode", {
  49882. /**
  49883. * Gets current mode used by the behavior.
  49884. */
  49885. get: function () {
  49886. return this._mode;
  49887. },
  49888. /**
  49889. * Sets the current mode used by the behavior
  49890. */
  49891. set: function (mode) {
  49892. this._mode = mode;
  49893. },
  49894. enumerable: true,
  49895. configurable: true
  49896. });
  49897. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  49898. /**
  49899. * Gets the scale applied to the radius
  49900. */
  49901. get: function () {
  49902. return this._radiusScale;
  49903. },
  49904. /**
  49905. * Sets the scale applied to the radius (1 by default)
  49906. */
  49907. set: function (radius) {
  49908. this._radiusScale = radius;
  49909. },
  49910. enumerable: true,
  49911. configurable: true
  49912. });
  49913. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  49914. /**
  49915. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  49916. */
  49917. get: function () {
  49918. return this._positionScale;
  49919. },
  49920. /**
  49921. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  49922. */
  49923. set: function (scale) {
  49924. this._positionScale = scale;
  49925. },
  49926. enumerable: true,
  49927. configurable: true
  49928. });
  49929. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  49930. /**
  49931. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  49932. * behaviour is triggered, in radians.
  49933. */
  49934. get: function () {
  49935. return this._defaultElevation;
  49936. },
  49937. /**
  49938. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  49939. * behaviour is triggered, in radians.
  49940. */
  49941. set: function (elevation) {
  49942. this._defaultElevation = elevation;
  49943. },
  49944. enumerable: true,
  49945. configurable: true
  49946. });
  49947. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  49948. /**
  49949. * Gets the time (in milliseconds) taken to return to the default beta position.
  49950. * Negative value indicates camera should not return to default.
  49951. */
  49952. get: function () {
  49953. return this._elevationReturnTime;
  49954. },
  49955. /**
  49956. * Sets the time (in milliseconds) taken to return to the default beta position.
  49957. * Negative value indicates camera should not return to default.
  49958. */
  49959. set: function (speed) {
  49960. this._elevationReturnTime = speed;
  49961. },
  49962. enumerable: true,
  49963. configurable: true
  49964. });
  49965. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  49966. /**
  49967. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  49968. */
  49969. get: function () {
  49970. return this._elevationReturnWaitTime;
  49971. },
  49972. /**
  49973. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  49974. */
  49975. set: function (time) {
  49976. this._elevationReturnWaitTime = time;
  49977. },
  49978. enumerable: true,
  49979. configurable: true
  49980. });
  49981. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  49982. /**
  49983. * Gets the flag that indicates if user zooming should stop animation.
  49984. */
  49985. get: function () {
  49986. return this._zoomStopsAnimation;
  49987. },
  49988. /**
  49989. * Sets the flag that indicates if user zooming should stop animation.
  49990. */
  49991. set: function (flag) {
  49992. this._zoomStopsAnimation = flag;
  49993. },
  49994. enumerable: true,
  49995. configurable: true
  49996. });
  49997. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  49998. /**
  49999. * Gets the transition time when framing the mesh, in milliseconds
  50000. */
  50001. get: function () {
  50002. return this._framingTime;
  50003. },
  50004. /**
  50005. * Sets the transition time when framing the mesh, in milliseconds
  50006. */
  50007. set: function (time) {
  50008. this._framingTime = time;
  50009. },
  50010. enumerable: true,
  50011. configurable: true
  50012. });
  50013. FramingBehavior.prototype.attach = function (camera) {
  50014. var _this = this;
  50015. this._attachedCamera = camera;
  50016. var scene = this._attachedCamera.getScene();
  50017. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  50018. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50019. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50020. _this._isPointerDown = true;
  50021. return;
  50022. }
  50023. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50024. _this._isPointerDown = false;
  50025. }
  50026. });
  50027. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50028. if (mesh) {
  50029. _this.zoomOnMesh(mesh);
  50030. }
  50031. });
  50032. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50033. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50034. _this._applyUserInteraction();
  50035. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  50036. // back to the default position after a given timeout
  50037. _this._maintainCameraAboveGround();
  50038. });
  50039. };
  50040. FramingBehavior.prototype.detach = function () {
  50041. var scene = this._attachedCamera.getScene();
  50042. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50043. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50044. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50045. this._attachedCamera = null;
  50046. };
  50047. /**
  50048. * Targets the given mesh and updates zoom level accordingly.
  50049. * @param mesh The mesh to target.
  50050. * @param radius Optional. If a cached radius position already exists, overrides default.
  50051. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50052. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50053. */
  50054. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ) {
  50055. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50056. mesh.computeWorldMatrix(true);
  50057. var boundingBox = mesh.getBoundingInfo().boundingBox;
  50058. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ);
  50059. };
  50060. /**
  50061. * Targets the given mesh and updates zoom level accordingly.
  50062. * @param mesh The mesh to target.
  50063. * @param radius Optional. If a cached radius position already exists, overrides default.
  50064. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50065. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50066. */
  50067. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ) {
  50068. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50069. var zoomTarget;
  50070. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  50071. var bottom = minimumWorld.y;
  50072. var top = maximumWorld.y;
  50073. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  50074. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  50075. if (focusOnOriginXZ) {
  50076. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  50077. }
  50078. else {
  50079. var centerWorld = minimumWorld.add(radiusWorld);
  50080. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  50081. }
  50082. if (!this._vectorTransition) {
  50083. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  50084. }
  50085. this._betaIsAnimating = true;
  50086. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  50087. // sets the radius and lower radius bounds
  50088. // Small delta ensures camera is not always at lower zoom limit.
  50089. var delta = 0.1;
  50090. var radius = 0;
  50091. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  50092. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50093. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  50094. radius = position;
  50095. }
  50096. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50097. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50098. if (this._attachedCamera.lowerRadiusLimit === null) {
  50099. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  50100. }
  50101. }
  50102. // transition to new radius
  50103. if (!this._radiusTransition) {
  50104. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50105. }
  50106. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime));
  50107. };
  50108. /**
  50109. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  50110. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  50111. * frustum width.
  50112. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  50113. * to fully enclose the mesh in the viewing frustum.
  50114. */
  50115. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  50116. var size = maximumWorld.subtract(minimumWorld);
  50117. var boxVectorGlobalDiagonal = size.length();
  50118. var frustumSlope = this._getFrustumSlope();
  50119. // Formula for setting distance
  50120. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  50121. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  50122. // Horizon distance
  50123. var radius = radiusWithoutFraming * this._radiusScale;
  50124. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  50125. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  50126. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  50127. var camera = this._attachedCamera;
  50128. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50129. // Don't exceed the requested limit
  50130. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  50131. }
  50132. // Don't exceed the upper radius limit
  50133. if (camera.upperRadiusLimit) {
  50134. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  50135. }
  50136. return distance;
  50137. };
  50138. /**
  50139. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  50140. * is automatically returned to its default position (expected to be above ground plane).
  50141. */
  50142. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  50143. var _this = this;
  50144. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  50145. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  50146. var limitBeta = Math.PI * 0.5;
  50147. // Bring the camera back up if below the ground plane
  50148. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  50149. this._betaIsAnimating = true;
  50150. //Transition to new position
  50151. this.stopAllAnimations();
  50152. if (!this._betaTransition) {
  50153. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50154. }
  50155. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  50156. _this._clearAnimationLocks();
  50157. _this.stopAllAnimations();
  50158. }));
  50159. }
  50160. };
  50161. /**
  50162. * Returns the frustum slope based on the canvas ratio and camera FOV
  50163. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  50164. */
  50165. FramingBehavior.prototype._getFrustumSlope = function () {
  50166. // Calculate the viewport ratio
  50167. // Aspect Ratio is Height/Width.
  50168. var camera = this._attachedCamera;
  50169. var engine = camera.getScene().getEngine();
  50170. var aspectRatio = engine.getAspectRatio(camera);
  50171. // Camera FOV is the vertical field of view (top-bottom) in radians.
  50172. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  50173. var frustumSlopeY = Math.tan(camera.fov / 2);
  50174. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  50175. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  50176. // along the forward vector.
  50177. var frustumSlopeX = frustumSlopeY * aspectRatio;
  50178. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  50179. };
  50180. /**
  50181. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  50182. */
  50183. FramingBehavior.prototype._clearAnimationLocks = function () {
  50184. this._betaIsAnimating = false;
  50185. };
  50186. /**
  50187. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50188. */
  50189. FramingBehavior.prototype._applyUserInteraction = function () {
  50190. if (this.isUserIsMoving) {
  50191. this._lastInteractionTime = BABYLON.Tools.Now;
  50192. this.stopAllAnimations();
  50193. this._clearAnimationLocks();
  50194. }
  50195. };
  50196. /**
  50197. * Stops and removes all animations that have been applied to the camera
  50198. */
  50199. FramingBehavior.prototype.stopAllAnimations = function () {
  50200. this._attachedCamera.animations = [];
  50201. while (this._animatables.length) {
  50202. if (this._animatables[0]) {
  50203. this._animatables[0].onAnimationEnd = null;
  50204. this._animatables[0].stop();
  50205. }
  50206. this._animatables.shift();
  50207. }
  50208. };
  50209. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  50210. /**
  50211. * Gets a value indicating if the user is moving the camera
  50212. */
  50213. get: function () {
  50214. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50215. this._attachedCamera.inertialBetaOffset !== 0 ||
  50216. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50217. this._attachedCamera.inertialPanningX !== 0 ||
  50218. this._attachedCamera.inertialPanningY !== 0 ||
  50219. this._isPointerDown;
  50220. },
  50221. enumerable: true,
  50222. configurable: true
  50223. });
  50224. /**
  50225. * The easing function used by animations
  50226. */
  50227. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  50228. /**
  50229. * The easing mode used by animations
  50230. */
  50231. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  50232. // Statics
  50233. /**
  50234. * The camera can move all the way towards the mesh.
  50235. */
  50236. FramingBehavior.IgnoreBoundsSizeMode = 0;
  50237. /**
  50238. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  50239. */
  50240. FramingBehavior.FitFrustumSidesMode = 1;
  50241. return FramingBehavior;
  50242. }());
  50243. BABYLON.FramingBehavior = FramingBehavior;
  50244. })(BABYLON || (BABYLON = {}));
  50245. //# sourceMappingURL=babylon.framingBehavior.js.map
  50246. var BABYLON;
  50247. (function (BABYLON) {
  50248. /**
  50249. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  50250. */
  50251. var BouncingBehavior = (function () {
  50252. function BouncingBehavior() {
  50253. /**
  50254. * The duration of the animation, in milliseconds
  50255. */
  50256. this.transitionDuration = 450;
  50257. /**
  50258. * Length of the distance animated by the transition when lower radius is reached
  50259. */
  50260. this.lowerRadiusTransitionRange = 2;
  50261. /**
  50262. * Length of the distance animated by the transition when upper radius is reached
  50263. */
  50264. this.upperRadiusTransitionRange = -2;
  50265. this._autoTransitionRange = false;
  50266. // Animations
  50267. this._radiusIsAnimating = false;
  50268. this._radiusBounceTransition = null;
  50269. this._animatables = new Array();
  50270. }
  50271. Object.defineProperty(BouncingBehavior.prototype, "name", {
  50272. get: function () {
  50273. return "Bouncing";
  50274. },
  50275. enumerable: true,
  50276. configurable: true
  50277. });
  50278. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  50279. /**
  50280. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50281. */
  50282. get: function () {
  50283. return this._autoTransitionRange;
  50284. },
  50285. /**
  50286. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50287. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  50288. */
  50289. set: function (value) {
  50290. var _this = this;
  50291. if (this._autoTransitionRange === value) {
  50292. return;
  50293. }
  50294. this._autoTransitionRange = value;
  50295. var camera = this._attachedCamera;
  50296. if (value) {
  50297. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50298. if (!mesh) {
  50299. return;
  50300. }
  50301. mesh.computeWorldMatrix(true);
  50302. var diagonal = mesh.getBoundingInfo().diagonalLength;
  50303. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  50304. _this.upperRadiusTransitionRange = diagonal * 0.05;
  50305. });
  50306. }
  50307. else if (this._onMeshTargetChangedObserver) {
  50308. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50309. }
  50310. },
  50311. enumerable: true,
  50312. configurable: true
  50313. });
  50314. BouncingBehavior.prototype.attach = function (camera) {
  50315. var _this = this;
  50316. this._attachedCamera = camera;
  50317. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50318. // Add the bounce animation to the lower radius limit
  50319. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  50320. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  50321. }
  50322. // Add the bounce animation to the upper radius limit
  50323. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  50324. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  50325. }
  50326. });
  50327. };
  50328. BouncingBehavior.prototype.detach = function () {
  50329. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50330. if (this._onMeshTargetChangedObserver) {
  50331. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50332. }
  50333. this._attachedCamera = null;
  50334. };
  50335. /**
  50336. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  50337. * @param radiusLimit The limit to check against.
  50338. * @return Bool to indicate if at limit.
  50339. */
  50340. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  50341. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  50342. return true;
  50343. }
  50344. return false;
  50345. };
  50346. /**
  50347. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  50348. * @param radiusDelta The delta by which to animate to. Can be negative.
  50349. */
  50350. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  50351. var _this = this;
  50352. if (!this._radiusBounceTransition) {
  50353. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  50354. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  50355. }
  50356. // Prevent zoom until bounce has completed
  50357. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  50358. this._attachedCamera.wheelPrecision = Infinity;
  50359. this._attachedCamera.inertialRadiusOffset = 0;
  50360. // Animate to the radius limit
  50361. this.stopAllAnimations();
  50362. this._radiusIsAnimating = true;
  50363. 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(); }));
  50364. };
  50365. /**
  50366. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  50367. */
  50368. BouncingBehavior.prototype._clearAnimationLocks = function () {
  50369. this._radiusIsAnimating = false;
  50370. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  50371. };
  50372. /**
  50373. * Stops and removes all animations that have been applied to the camera
  50374. */
  50375. BouncingBehavior.prototype.stopAllAnimations = function () {
  50376. this._attachedCamera.animations = [];
  50377. while (this._animatables.length) {
  50378. this._animatables[0].onAnimationEnd = null;
  50379. this._animatables[0].stop();
  50380. this._animatables.shift();
  50381. }
  50382. };
  50383. /**
  50384. * The easing function used by animations
  50385. */
  50386. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  50387. /**
  50388. * The easing mode used by animations
  50389. */
  50390. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  50391. return BouncingBehavior;
  50392. }());
  50393. BABYLON.BouncingBehavior = BouncingBehavior;
  50394. })(BABYLON || (BABYLON = {}));
  50395. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  50396. var BABYLON;
  50397. (function (BABYLON) {
  50398. var AutoRotationBehavior = (function () {
  50399. function AutoRotationBehavior() {
  50400. this._zoomStopsAnimation = false;
  50401. this._idleRotationSpeed = 0.05;
  50402. this._idleRotationWaitTime = 2000;
  50403. this._idleRotationSpinupTime = 2000;
  50404. this._isPointerDown = false;
  50405. this._lastFrameTime = null;
  50406. this._lastInteractionTime = -Infinity;
  50407. this._cameraRotationSpeed = 0;
  50408. this._lastFrameRadius = 0;
  50409. }
  50410. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  50411. get: function () {
  50412. return "AutoRotation";
  50413. },
  50414. enumerable: true,
  50415. configurable: true
  50416. });
  50417. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  50418. /**
  50419. * Gets the flag that indicates if user zooming should stop animation.
  50420. */
  50421. get: function () {
  50422. return this._zoomStopsAnimation;
  50423. },
  50424. /**
  50425. * Sets the flag that indicates if user zooming should stop animation.
  50426. */
  50427. set: function (flag) {
  50428. this._zoomStopsAnimation = flag;
  50429. },
  50430. enumerable: true,
  50431. configurable: true
  50432. });
  50433. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  50434. /**
  50435. * Gets the default speed at which the camera rotates around the model.
  50436. */
  50437. get: function () {
  50438. return this._idleRotationSpeed;
  50439. },
  50440. /**
  50441. * Sets the default speed at which the camera rotates around the model.
  50442. */
  50443. set: function (speed) {
  50444. this._idleRotationSpeed = speed;
  50445. },
  50446. enumerable: true,
  50447. configurable: true
  50448. });
  50449. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  50450. /**
  50451. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  50452. */
  50453. get: function () {
  50454. return this._idleRotationWaitTime;
  50455. },
  50456. /**
  50457. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  50458. */
  50459. set: function (time) {
  50460. this._idleRotationWaitTime = time;
  50461. },
  50462. enumerable: true,
  50463. configurable: true
  50464. });
  50465. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  50466. /**
  50467. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50468. */
  50469. get: function () {
  50470. return this._idleRotationSpinupTime;
  50471. },
  50472. /**
  50473. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50474. */
  50475. set: function (time) {
  50476. this._idleRotationSpinupTime = time;
  50477. },
  50478. enumerable: true,
  50479. configurable: true
  50480. });
  50481. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  50482. /**
  50483. * Gets a value indicating if the camera is currently rotating because of this behavior
  50484. */
  50485. get: function () {
  50486. return Math.abs(this._cameraRotationSpeed) > 0;
  50487. },
  50488. enumerable: true,
  50489. configurable: true
  50490. });
  50491. AutoRotationBehavior.prototype.attach = function (camera) {
  50492. var _this = this;
  50493. this._attachedCamera = camera;
  50494. var scene = this._attachedCamera.getScene();
  50495. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50496. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50497. _this._isPointerDown = true;
  50498. return;
  50499. }
  50500. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50501. _this._isPointerDown = false;
  50502. }
  50503. });
  50504. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50505. var now = BABYLON.Tools.Now;
  50506. var dt = 16;
  50507. if (_this._lastFrameTime != null) {
  50508. dt = now - _this._lastFrameTime;
  50509. }
  50510. _this._lastFrameTime = now;
  50511. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50512. _this._applyUserInteraction();
  50513. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  50514. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  50515. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  50516. // Step camera rotation by rotation speed
  50517. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  50518. });
  50519. };
  50520. AutoRotationBehavior.prototype.detach = function () {
  50521. var scene = this._attachedCamera.getScene();
  50522. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50523. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50524. this._attachedCamera = null;
  50525. };
  50526. /**
  50527. * Returns true if user is scrolling.
  50528. * @return true if user is scrolling.
  50529. */
  50530. AutoRotationBehavior.prototype._userIsZooming = function () {
  50531. return this._attachedCamera.inertialRadiusOffset !== 0;
  50532. };
  50533. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  50534. var zoomHasHitLimit = false;
  50535. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  50536. zoomHasHitLimit = true;
  50537. }
  50538. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  50539. this._lastFrameRadius = this._attachedCamera.radius;
  50540. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  50541. };
  50542. /**
  50543. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50544. */
  50545. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  50546. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  50547. this._lastInteractionTime = BABYLON.Tools.Now;
  50548. }
  50549. };
  50550. // Tools
  50551. AutoRotationBehavior.prototype._userIsMoving = function () {
  50552. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50553. this._attachedCamera.inertialBetaOffset !== 0 ||
  50554. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50555. this._attachedCamera.inertialPanningX !== 0 ||
  50556. this._attachedCamera.inertialPanningY !== 0 ||
  50557. this._isPointerDown;
  50558. };
  50559. return AutoRotationBehavior;
  50560. }());
  50561. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  50562. })(BABYLON || (BABYLON = {}));
  50563. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  50564. var BABYLON;
  50565. (function (BABYLON) {
  50566. var MorphTarget = (function () {
  50567. function MorphTarget(name, influence) {
  50568. if (influence === void 0) { influence = 0; }
  50569. this.name = name;
  50570. this.animations = new Array();
  50571. this.onInfluenceChanged = new BABYLON.Observable();
  50572. this.influence = influence;
  50573. }
  50574. Object.defineProperty(MorphTarget.prototype, "influence", {
  50575. get: function () {
  50576. return this._influence;
  50577. },
  50578. set: function (influence) {
  50579. if (this._influence === influence) {
  50580. return;
  50581. }
  50582. var previous = this._influence;
  50583. this._influence = influence;
  50584. if (this.onInfluenceChanged.hasObservers) {
  50585. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  50586. }
  50587. },
  50588. enumerable: true,
  50589. configurable: true
  50590. });
  50591. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  50592. get: function () {
  50593. return this._normals !== undefined;
  50594. },
  50595. enumerable: true,
  50596. configurable: true
  50597. });
  50598. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  50599. get: function () {
  50600. return this._tangents !== undefined;
  50601. },
  50602. enumerable: true,
  50603. configurable: true
  50604. });
  50605. MorphTarget.prototype.setPositions = function (data) {
  50606. this._positions = new Float32Array(data);
  50607. };
  50608. MorphTarget.prototype.getPositions = function () {
  50609. return this._positions;
  50610. };
  50611. MorphTarget.prototype.setNormals = function (data) {
  50612. this._normals = new Float32Array(data);
  50613. };
  50614. MorphTarget.prototype.getNormals = function () {
  50615. return this._normals;
  50616. };
  50617. MorphTarget.prototype.setTangents = function (data) {
  50618. this._tangents = new Float32Array(data);
  50619. };
  50620. MorphTarget.prototype.getTangents = function () {
  50621. return this._tangents;
  50622. };
  50623. /**
  50624. * Serializes the current target into a Serialization object.
  50625. * Returns the serialized object.
  50626. */
  50627. MorphTarget.prototype.serialize = function () {
  50628. var serializationObject = {};
  50629. serializationObject.name = this.name;
  50630. serializationObject.influence = this.influence;
  50631. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  50632. if (this.hasNormals) {
  50633. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  50634. }
  50635. if (this.hasTangents) {
  50636. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  50637. }
  50638. return serializationObject;
  50639. };
  50640. // Statics
  50641. MorphTarget.Parse = function (serializationObject) {
  50642. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  50643. result.setPositions(serializationObject.positions);
  50644. if (serializationObject.normals) {
  50645. result.setNormals(serializationObject.normals);
  50646. }
  50647. if (serializationObject.tangents) {
  50648. result.setTangents(serializationObject.tangents);
  50649. }
  50650. return result;
  50651. };
  50652. MorphTarget.FromMesh = function (mesh, name, influence) {
  50653. if (!name) {
  50654. name = mesh.name;
  50655. }
  50656. var result = new MorphTarget(name, influence);
  50657. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  50658. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50659. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  50660. }
  50661. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  50662. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  50663. }
  50664. return result;
  50665. };
  50666. return MorphTarget;
  50667. }());
  50668. BABYLON.MorphTarget = MorphTarget;
  50669. })(BABYLON || (BABYLON = {}));
  50670. //# sourceMappingURL=babylon.morphTarget.js.map
  50671. var BABYLON;
  50672. (function (BABYLON) {
  50673. var MorphTargetManager = (function () {
  50674. function MorphTargetManager(scene) {
  50675. this._targets = new Array();
  50676. this._targetObservable = new Array();
  50677. this._activeTargets = new BABYLON.SmartArray(16);
  50678. this._supportsNormals = false;
  50679. this._supportsTangents = false;
  50680. this._vertexCount = 0;
  50681. this._uniqueId = 0;
  50682. this._tempInfluences = new Array();
  50683. if (!scene) {
  50684. scene = BABYLON.Engine.LastCreatedScene;
  50685. }
  50686. this._scene = scene;
  50687. this._scene.morphTargetManagers.push(this);
  50688. this._uniqueId = scene.getUniqueId();
  50689. }
  50690. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  50691. get: function () {
  50692. return this._uniqueId;
  50693. },
  50694. enumerable: true,
  50695. configurable: true
  50696. });
  50697. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  50698. get: function () {
  50699. return this._vertexCount;
  50700. },
  50701. enumerable: true,
  50702. configurable: true
  50703. });
  50704. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  50705. get: function () {
  50706. return this._supportsNormals;
  50707. },
  50708. enumerable: true,
  50709. configurable: true
  50710. });
  50711. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  50712. get: function () {
  50713. return this._supportsTangents;
  50714. },
  50715. enumerable: true,
  50716. configurable: true
  50717. });
  50718. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  50719. get: function () {
  50720. return this._targets.length;
  50721. },
  50722. enumerable: true,
  50723. configurable: true
  50724. });
  50725. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  50726. get: function () {
  50727. return this._activeTargets.length;
  50728. },
  50729. enumerable: true,
  50730. configurable: true
  50731. });
  50732. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  50733. get: function () {
  50734. return this._influences;
  50735. },
  50736. enumerable: true,
  50737. configurable: true
  50738. });
  50739. MorphTargetManager.prototype.getActiveTarget = function (index) {
  50740. return this._activeTargets.data[index];
  50741. };
  50742. MorphTargetManager.prototype.getTarget = function (index) {
  50743. return this._targets[index];
  50744. };
  50745. MorphTargetManager.prototype.addTarget = function (target) {
  50746. var _this = this;
  50747. if (this._vertexCount) {
  50748. if (this._vertexCount !== target.getPositions().length / 3) {
  50749. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  50750. return;
  50751. }
  50752. }
  50753. this._targets.push(target);
  50754. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  50755. _this._syncActiveTargets(needUpdate);
  50756. }));
  50757. this._syncActiveTargets(true);
  50758. };
  50759. MorphTargetManager.prototype.removeTarget = function (target) {
  50760. var index = this._targets.indexOf(target);
  50761. if (index >= 0) {
  50762. this._targets.splice(index, 1);
  50763. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  50764. this._vertexCount = 0;
  50765. this._syncActiveTargets(true);
  50766. }
  50767. };
  50768. /**
  50769. * Serializes the current manager into a Serialization object.
  50770. * Returns the serialized object.
  50771. */
  50772. MorphTargetManager.prototype.serialize = function () {
  50773. var serializationObject = {};
  50774. serializationObject.id = this.uniqueId;
  50775. serializationObject.targets = [];
  50776. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  50777. var target = _a[_i];
  50778. serializationObject.targets.push(target.serialize());
  50779. }
  50780. return serializationObject;
  50781. };
  50782. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  50783. this._syncActiveTargets(needUpdate);
  50784. };
  50785. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  50786. var influenceCount = 0;
  50787. this._activeTargets.reset();
  50788. this._supportsNormals = true;
  50789. this._supportsTangents = true;
  50790. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  50791. var target = _a[_i];
  50792. if (target.influence > 0) {
  50793. this._activeTargets.push(target);
  50794. this._tempInfluences[influenceCount++] = target.influence;
  50795. this._supportsNormals = this._supportsNormals && target.hasNormals;
  50796. this._supportsTangents = this._supportsTangents && target.hasTangents;
  50797. if (this._vertexCount === 0) {
  50798. this._vertexCount = target.getPositions().length / 3;
  50799. }
  50800. }
  50801. }
  50802. if (!this._influences || this._influences.length !== influenceCount) {
  50803. this._influences = new Float32Array(influenceCount);
  50804. }
  50805. for (var index = 0; index < influenceCount; index++) {
  50806. this._influences[index] = this._tempInfluences[index];
  50807. }
  50808. if (needUpdate) {
  50809. // Flag meshes as dirty to resync with the active targets
  50810. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  50811. var mesh = _c[_b];
  50812. if (mesh.morphTargetManager === this) {
  50813. mesh._syncGeometryWithMorphTargetManager();
  50814. }
  50815. }
  50816. }
  50817. };
  50818. // Statics
  50819. MorphTargetManager.Parse = function (serializationObject, scene) {
  50820. var result = new MorphTargetManager(scene);
  50821. result._uniqueId = serializationObject.id;
  50822. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  50823. var targetData = _a[_i];
  50824. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  50825. }
  50826. return result;
  50827. };
  50828. return MorphTargetManager;
  50829. }());
  50830. BABYLON.MorphTargetManager = MorphTargetManager;
  50831. })(BABYLON || (BABYLON = {}));
  50832. //# sourceMappingURL=babylon.morphTargetManager.js.map
  50833. 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}"};
  50834. 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};"};
  50835. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  50836. var BABYLON;
  50837. (function (BABYLON) {
  50838. var GridMaterialDefines = (function (_super) {
  50839. __extends(GridMaterialDefines, _super);
  50840. function GridMaterialDefines() {
  50841. var _this = _super.call(this) || this;
  50842. _this.TRANSPARENT = false;
  50843. _this.FOG = false;
  50844. _this.PREMULTIPLYALPHA = false;
  50845. _this.rebuild();
  50846. return _this;
  50847. }
  50848. return GridMaterialDefines;
  50849. }(BABYLON.MaterialDefines));
  50850. /**
  50851. * The grid materials allows you to wrap any shape with a grid.
  50852. * Colors are customizable.
  50853. */
  50854. var GridMaterial = (function (_super) {
  50855. __extends(GridMaterial, _super);
  50856. /**
  50857. * constructor
  50858. * @param name The name given to the material in order to identify it afterwards.
  50859. * @param scene The scene the material is used in.
  50860. */
  50861. function GridMaterial(name, scene) {
  50862. var _this = _super.call(this, name, scene) || this;
  50863. /**
  50864. * Main color of the grid (e.g. between lines)
  50865. */
  50866. _this.mainColor = BABYLON.Color3.Black();
  50867. /**
  50868. * Color of the grid lines.
  50869. */
  50870. _this.lineColor = BABYLON.Color3.Teal();
  50871. /**
  50872. * The scale of the grid compared to unit.
  50873. */
  50874. _this.gridRatio = 1.0;
  50875. /**
  50876. * The frequency of thicker lines.
  50877. */
  50878. _this.majorUnitFrequency = 10;
  50879. /**
  50880. * The visibility of minor units in the grid.
  50881. */
  50882. _this.minorUnitVisibility = 0.33;
  50883. /**
  50884. * The grid opacity outside of the lines.
  50885. */
  50886. _this.opacity = 1.0;
  50887. /**
  50888. * Determine RBG output is premultiplied by alpha value.
  50889. */
  50890. _this.preMultiplyAlpha = false;
  50891. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  50892. return _this;
  50893. }
  50894. /**
  50895. * Returns wehter or not the grid requires alpha blending.
  50896. */
  50897. GridMaterial.prototype.needAlphaBlending = function () {
  50898. return this.opacity < 1.0;
  50899. };
  50900. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  50901. if (this.isFrozen) {
  50902. if (this._wasPreviouslyReady && subMesh.effect) {
  50903. return true;
  50904. }
  50905. }
  50906. if (!subMesh._materialDefines) {
  50907. subMesh._materialDefines = new GridMaterialDefines();
  50908. }
  50909. var defines = subMesh._materialDefines;
  50910. var scene = this.getScene();
  50911. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  50912. if (this._renderId === scene.getRenderId()) {
  50913. return true;
  50914. }
  50915. }
  50916. var engine = scene.getEngine();
  50917. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  50918. defines.TRANSPARENT = !defines.TRANSPARENT;
  50919. defines.markAsUnprocessed();
  50920. }
  50921. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  50922. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  50923. defines.markAsUnprocessed();
  50924. }
  50925. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  50926. // Get correct effect
  50927. if (defines.isDirty) {
  50928. defines.markAsProcessed();
  50929. scene.resetCachedMaterial();
  50930. // Attributes
  50931. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  50932. // Defines
  50933. var join = defines.toString();
  50934. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  50935. }
  50936. if (!subMesh.effect.isReady()) {
  50937. return false;
  50938. }
  50939. this._renderId = scene.getRenderId();
  50940. this._wasPreviouslyReady = true;
  50941. return true;
  50942. };
  50943. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  50944. var scene = this.getScene();
  50945. var defines = subMesh._materialDefines;
  50946. if (!defines) {
  50947. return;
  50948. }
  50949. var effect = subMesh.effect;
  50950. this._activeEffect = effect;
  50951. // Matrices
  50952. this.bindOnlyWorldMatrix(world);
  50953. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  50954. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  50955. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  50956. // Uniforms
  50957. if (this._mustRebind(scene, effect)) {
  50958. this._activeEffect.setColor3("mainColor", this.mainColor);
  50959. this._activeEffect.setColor3("lineColor", this.lineColor);
  50960. this._gridControl.x = this.gridRatio;
  50961. this._gridControl.y = Math.round(this.majorUnitFrequency);
  50962. this._gridControl.z = this.minorUnitVisibility;
  50963. this._gridControl.w = this.opacity;
  50964. this._activeEffect.setVector4("gridControl", this._gridControl);
  50965. }
  50966. // Fog
  50967. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  50968. this._afterBind(mesh, this._activeEffect);
  50969. };
  50970. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  50971. _super.prototype.dispose.call(this, forceDisposeEffect);
  50972. };
  50973. GridMaterial.prototype.clone = function (name) {
  50974. var _this = this;
  50975. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  50976. };
  50977. GridMaterial.prototype.serialize = function () {
  50978. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50979. serializationObject.customType = "BABYLON.GridMaterial";
  50980. return serializationObject;
  50981. };
  50982. GridMaterial.prototype.getClassName = function () {
  50983. return "GridMaterial";
  50984. };
  50985. GridMaterial.Parse = function (source, scene, rootUrl) {
  50986. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  50987. };
  50988. __decorate([
  50989. BABYLON.serializeAsColor3()
  50990. ], GridMaterial.prototype, "mainColor", void 0);
  50991. __decorate([
  50992. BABYLON.serializeAsColor3()
  50993. ], GridMaterial.prototype, "lineColor", void 0);
  50994. __decorate([
  50995. BABYLON.serialize()
  50996. ], GridMaterial.prototype, "gridRatio", void 0);
  50997. __decorate([
  50998. BABYLON.serialize()
  50999. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  51000. __decorate([
  51001. BABYLON.serialize()
  51002. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  51003. __decorate([
  51004. BABYLON.serialize()
  51005. ], GridMaterial.prototype, "opacity", void 0);
  51006. __decorate([
  51007. BABYLON.serialize()
  51008. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  51009. return GridMaterial;
  51010. }(BABYLON.PushMaterial));
  51011. BABYLON.GridMaterial = GridMaterial;
  51012. })(BABYLON || (BABYLON = {}));
  51013. //# sourceMappingURL=babylon.gridmaterial.js.map
  51014. 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}";
  51015. 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}";
  51016. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  51017. var BABYLON;
  51018. (function (BABYLON) {
  51019. var GLTFLoaderCoordinateSystemMode;
  51020. (function (GLTFLoaderCoordinateSystemMode) {
  51021. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  51022. // 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.
  51023. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  51024. // The glTF right-handed data is not transformed in any form and is loaded directly.
  51025. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  51026. // Sets the useRightHandedSystem flag on the scene.
  51027. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  51028. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  51029. var GLTFFileLoader = (function () {
  51030. function GLTFFileLoader() {
  51031. // V2 options
  51032. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  51033. this.name = "gltf";
  51034. this.extensions = {
  51035. ".gltf": { isBinary: false },
  51036. ".glb": { isBinary: true }
  51037. };
  51038. }
  51039. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  51040. var loaderData = GLTFFileLoader._parse(data, onError);
  51041. if (!loaderData) {
  51042. return;
  51043. }
  51044. var loader = this._getLoader(loaderData, onError);
  51045. if (!loader) {
  51046. return;
  51047. }
  51048. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51049. };
  51050. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  51051. var loaderData = GLTFFileLoader._parse(data, onError);
  51052. if (!loaderData) {
  51053. return;
  51054. }
  51055. var loader = this._getLoader(loaderData, onError);
  51056. if (!loader) {
  51057. return;
  51058. }
  51059. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51060. };
  51061. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  51062. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  51063. };
  51064. GLTFFileLoader._parse = function (data, onError) {
  51065. if (data instanceof ArrayBuffer) {
  51066. return GLTFFileLoader._parseBinary(data, onError);
  51067. }
  51068. try {
  51069. return {
  51070. json: JSON.parse(data),
  51071. bin: null
  51072. };
  51073. }
  51074. catch (e) {
  51075. onError(e.message);
  51076. return null;
  51077. }
  51078. };
  51079. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  51080. var loaderVersion = { major: 2, minor: 0 };
  51081. var asset = loaderData.json.asset || {};
  51082. var version = GLTFFileLoader._parseVersion(asset.version);
  51083. if (!version) {
  51084. onError("Invalid version: " + asset.version);
  51085. return null;
  51086. }
  51087. if (asset.minVersion !== undefined) {
  51088. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  51089. if (!minVersion) {
  51090. onError("Invalid minimum version: " + asset.minVersion);
  51091. return null;
  51092. }
  51093. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  51094. onError("Incompatible minimum version: " + asset.minVersion);
  51095. return null;
  51096. }
  51097. }
  51098. var createLoaders = {
  51099. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  51100. 2: GLTFFileLoader.CreateGLTFLoaderV2
  51101. };
  51102. var createLoader = createLoaders[version.major];
  51103. if (!createLoader) {
  51104. onError("Unsupported version: " + asset.version);
  51105. return null;
  51106. }
  51107. return createLoader(this);
  51108. };
  51109. GLTFFileLoader._parseBinary = function (data, onError) {
  51110. var Binary = {
  51111. Magic: 0x46546C67
  51112. };
  51113. var binaryReader = new BinaryReader(data);
  51114. var magic = binaryReader.readUint32();
  51115. if (magic !== Binary.Magic) {
  51116. onError("Unexpected magic: " + magic);
  51117. return null;
  51118. }
  51119. var version = binaryReader.readUint32();
  51120. switch (version) {
  51121. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  51122. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  51123. }
  51124. onError("Unsupported version: " + version);
  51125. return null;
  51126. };
  51127. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  51128. var ContentFormat = {
  51129. JSON: 0
  51130. };
  51131. var length = binaryReader.readUint32();
  51132. if (length != binaryReader.getLength()) {
  51133. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51134. return null;
  51135. }
  51136. var contentLength = binaryReader.readUint32();
  51137. var contentFormat = binaryReader.readUint32();
  51138. var content;
  51139. switch (contentFormat) {
  51140. case ContentFormat.JSON:
  51141. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  51142. break;
  51143. default:
  51144. onError("Unexpected content format: " + contentFormat);
  51145. return null;
  51146. }
  51147. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  51148. var body = binaryReader.readUint8Array(bytesRemaining);
  51149. return {
  51150. json: content,
  51151. bin: body
  51152. };
  51153. };
  51154. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  51155. var ChunkFormat = {
  51156. JSON: 0x4E4F534A,
  51157. BIN: 0x004E4942
  51158. };
  51159. var length = binaryReader.readUint32();
  51160. if (length !== binaryReader.getLength()) {
  51161. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51162. return null;
  51163. }
  51164. // JSON chunk
  51165. var chunkLength = binaryReader.readUint32();
  51166. var chunkFormat = binaryReader.readUint32();
  51167. if (chunkFormat !== ChunkFormat.JSON) {
  51168. onError("First chunk format is not JSON");
  51169. return null;
  51170. }
  51171. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  51172. // Look for BIN chunk
  51173. var bin = null;
  51174. while (binaryReader.getPosition() < binaryReader.getLength()) {
  51175. chunkLength = binaryReader.readUint32();
  51176. chunkFormat = binaryReader.readUint32();
  51177. switch (chunkFormat) {
  51178. case ChunkFormat.JSON:
  51179. onError("Unexpected JSON chunk");
  51180. return null;
  51181. case ChunkFormat.BIN:
  51182. bin = binaryReader.readUint8Array(chunkLength);
  51183. break;
  51184. default:
  51185. // ignore unrecognized chunkFormat
  51186. binaryReader.skipBytes(chunkLength);
  51187. break;
  51188. }
  51189. }
  51190. return {
  51191. json: json,
  51192. bin: bin
  51193. };
  51194. };
  51195. GLTFFileLoader._parseVersion = function (version) {
  51196. if (!version) {
  51197. return null;
  51198. }
  51199. var parts = version.split(".");
  51200. if (parts.length != 2) {
  51201. return null;
  51202. }
  51203. var major = +parts[0];
  51204. if (isNaN(major)) {
  51205. return null;
  51206. }
  51207. var minor = +parts[1];
  51208. if (isNaN(minor)) {
  51209. return null;
  51210. }
  51211. return {
  51212. major: major,
  51213. minor: minor
  51214. };
  51215. };
  51216. GLTFFileLoader._compareVersion = function (a, b) {
  51217. if (a.major > b.major)
  51218. return 1;
  51219. if (a.major < b.major)
  51220. return -1;
  51221. if (a.minor > b.minor)
  51222. return 1;
  51223. if (a.minor < b.minor)
  51224. return -1;
  51225. return 0;
  51226. };
  51227. GLTFFileLoader._decodeBufferToText = function (view) {
  51228. var result = "";
  51229. var length = view.byteLength;
  51230. for (var i = 0; i < length; ++i) {
  51231. result += String.fromCharCode(view[i]);
  51232. }
  51233. return result;
  51234. };
  51235. // V1 options
  51236. GLTFFileLoader.HomogeneousCoordinates = false;
  51237. GLTFFileLoader.IncrementalLoading = true;
  51238. return GLTFFileLoader;
  51239. }());
  51240. BABYLON.GLTFFileLoader = GLTFFileLoader;
  51241. var BinaryReader = (function () {
  51242. function BinaryReader(arrayBuffer) {
  51243. this._arrayBuffer = arrayBuffer;
  51244. this._dataView = new DataView(arrayBuffer);
  51245. this._byteOffset = 0;
  51246. }
  51247. BinaryReader.prototype.getPosition = function () {
  51248. return this._byteOffset;
  51249. };
  51250. BinaryReader.prototype.getLength = function () {
  51251. return this._arrayBuffer.byteLength;
  51252. };
  51253. BinaryReader.prototype.readUint32 = function () {
  51254. var value = this._dataView.getUint32(this._byteOffset, true);
  51255. this._byteOffset += 4;
  51256. return value;
  51257. };
  51258. BinaryReader.prototype.readUint8Array = function (length) {
  51259. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  51260. this._byteOffset += length;
  51261. return value;
  51262. };
  51263. BinaryReader.prototype.skipBytes = function (length) {
  51264. this._byteOffset += length;
  51265. };
  51266. return BinaryReader;
  51267. }());
  51268. if (BABYLON.SceneLoader) {
  51269. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  51270. }
  51271. })(BABYLON || (BABYLON = {}));
  51272. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  51273. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51274. var BABYLON;
  51275. (function (BABYLON) {
  51276. var GLTF1;
  51277. (function (GLTF1) {
  51278. /**
  51279. * Enums
  51280. */
  51281. var EComponentType;
  51282. (function (EComponentType) {
  51283. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  51284. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51285. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  51286. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51287. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  51288. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  51289. var EShaderType;
  51290. (function (EShaderType) {
  51291. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  51292. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  51293. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  51294. var EParameterType;
  51295. (function (EParameterType) {
  51296. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  51297. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51298. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  51299. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51300. EParameterType[EParameterType["INT"] = 5124] = "INT";
  51301. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  51302. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  51303. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  51304. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  51305. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  51306. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  51307. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  51308. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  51309. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  51310. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  51311. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  51312. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  51313. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  51314. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  51315. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  51316. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  51317. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  51318. var ETextureWrapMode;
  51319. (function (ETextureWrapMode) {
  51320. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  51321. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  51322. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  51323. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  51324. var ETextureFilterType;
  51325. (function (ETextureFilterType) {
  51326. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  51327. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  51328. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  51329. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  51330. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  51331. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  51332. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  51333. var ETextureFormat;
  51334. (function (ETextureFormat) {
  51335. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  51336. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  51337. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  51338. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  51339. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  51340. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  51341. var ECullingType;
  51342. (function (ECullingType) {
  51343. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  51344. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  51345. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  51346. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  51347. var EBlendingFunction;
  51348. (function (EBlendingFunction) {
  51349. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  51350. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  51351. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  51352. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  51353. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  51354. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  51355. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  51356. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  51357. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  51358. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  51359. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  51360. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  51361. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  51362. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  51363. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  51364. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  51365. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  51366. })(BABYLON || (BABYLON = {}));
  51367. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  51368. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51369. var BABYLON;
  51370. (function (BABYLON) {
  51371. var GLTF1;
  51372. (function (GLTF1) {
  51373. /**
  51374. * Tokenizer. Used for shaders compatibility
  51375. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  51376. */
  51377. var ETokenType;
  51378. (function (ETokenType) {
  51379. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  51380. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  51381. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  51382. })(ETokenType || (ETokenType = {}));
  51383. var Tokenizer = (function () {
  51384. function Tokenizer(toParse) {
  51385. this._pos = 0;
  51386. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  51387. this._toParse = toParse;
  51388. this._maxPos = toParse.length;
  51389. }
  51390. Tokenizer.prototype.getNextToken = function () {
  51391. if (this.isEnd())
  51392. return ETokenType.END_OF_INPUT;
  51393. this.currentString = this.read();
  51394. this.currentToken = ETokenType.UNKNOWN;
  51395. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  51396. this.currentToken = ETokenType.IDENTIFIER;
  51397. this.currentIdentifier = this.currentString;
  51398. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  51399. this.currentIdentifier += this.currentString;
  51400. this.forward();
  51401. }
  51402. }
  51403. return this.currentToken;
  51404. };
  51405. Tokenizer.prototype.peek = function () {
  51406. return this._toParse[this._pos];
  51407. };
  51408. Tokenizer.prototype.read = function () {
  51409. return this._toParse[this._pos++];
  51410. };
  51411. Tokenizer.prototype.forward = function () {
  51412. this._pos++;
  51413. };
  51414. Tokenizer.prototype.isEnd = function () {
  51415. return this._pos >= this._maxPos;
  51416. };
  51417. return Tokenizer;
  51418. }());
  51419. /**
  51420. * Values
  51421. */
  51422. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  51423. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  51424. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  51425. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  51426. /**
  51427. * Parse
  51428. */
  51429. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  51430. for (var buf in parsedBuffers) {
  51431. var parsedBuffer = parsedBuffers[buf];
  51432. gltfRuntime.buffers[buf] = parsedBuffer;
  51433. gltfRuntime.buffersCount++;
  51434. }
  51435. };
  51436. var parseShaders = function (parsedShaders, gltfRuntime) {
  51437. for (var sha in parsedShaders) {
  51438. var parsedShader = parsedShaders[sha];
  51439. gltfRuntime.shaders[sha] = parsedShader;
  51440. gltfRuntime.shaderscount++;
  51441. }
  51442. };
  51443. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  51444. for (var object in parsedObjects) {
  51445. var parsedObject = parsedObjects[object];
  51446. gltfRuntime[runtimeProperty][object] = parsedObject;
  51447. }
  51448. };
  51449. /**
  51450. * Utils
  51451. */
  51452. var normalizeUVs = function (buffer) {
  51453. if (!buffer) {
  51454. return;
  51455. }
  51456. for (var i = 0; i < buffer.length / 2; i++) {
  51457. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  51458. }
  51459. };
  51460. var replaceInString = function (str, searchValue, replaceValue) {
  51461. while (str.indexOf(searchValue) !== -1) {
  51462. str = str.replace(searchValue, replaceValue);
  51463. }
  51464. return str;
  51465. };
  51466. var getAttribute = function (attributeParameter) {
  51467. if (attributeParameter.semantic === "NORMAL") {
  51468. return "normal";
  51469. }
  51470. else if (attributeParameter.semantic === "POSITION") {
  51471. return "position";
  51472. }
  51473. else if (attributeParameter.semantic === "JOINT") {
  51474. return "matricesIndices";
  51475. }
  51476. else if (attributeParameter.semantic === "WEIGHT") {
  51477. return "matricesWeights";
  51478. }
  51479. else if (attributeParameter.semantic === "COLOR") {
  51480. return "color";
  51481. }
  51482. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  51483. var channel = Number(attributeParameter.semantic.split("_")[1]);
  51484. return "uv" + (channel === 0 ? "" : channel + 1);
  51485. }
  51486. };
  51487. /**
  51488. * Returns the animation path (glTF -> Babylon)
  51489. */
  51490. var getAnimationPath = function (path) {
  51491. var index = glTFAnimationPaths.indexOf(path);
  51492. if (index !== -1) {
  51493. return babylonAnimationPaths[index];
  51494. }
  51495. return path;
  51496. };
  51497. /**
  51498. * Loads and creates animations
  51499. */
  51500. var loadAnimations = function (gltfRuntime) {
  51501. for (var anim in gltfRuntime.animations) {
  51502. var animation = gltfRuntime.animations[anim];
  51503. var lastAnimation = null;
  51504. for (var i = 0; i < animation.channels.length; i++) {
  51505. // Get parameters and load buffers
  51506. var channel = animation.channels[i];
  51507. var sampler = animation.samplers[channel.sampler];
  51508. if (!sampler) {
  51509. continue;
  51510. }
  51511. var inputData = null;
  51512. var outputData = null;
  51513. if (animation.parameters) {
  51514. inputData = animation.parameters[sampler.input];
  51515. outputData = animation.parameters[sampler.output];
  51516. }
  51517. else {
  51518. inputData = sampler.input;
  51519. outputData = sampler.output;
  51520. }
  51521. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  51522. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  51523. var targetID = channel.target.id;
  51524. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  51525. if (targetNode === null) {
  51526. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  51527. }
  51528. if (targetNode === null) {
  51529. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  51530. continue;
  51531. }
  51532. var isBone = targetNode instanceof BABYLON.Bone;
  51533. // Get target path (position, rotation or scaling)
  51534. var targetPath = channel.target.path;
  51535. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  51536. if (targetPathIndex !== -1) {
  51537. targetPath = babylonAnimationPaths[targetPathIndex];
  51538. }
  51539. // Determine animation type
  51540. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  51541. if (!isBone) {
  51542. if (targetPath === "rotationQuaternion") {
  51543. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  51544. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  51545. }
  51546. else {
  51547. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  51548. }
  51549. }
  51550. // Create animation and key frames
  51551. var babylonAnimation = null;
  51552. var keys = [];
  51553. var arrayOffset = 0;
  51554. var modifyKey = false;
  51555. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  51556. babylonAnimation = lastAnimation;
  51557. modifyKey = true;
  51558. }
  51559. if (!modifyKey) {
  51560. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51561. }
  51562. // For each frame
  51563. for (var j = 0; j < bufferInput.length; j++) {
  51564. var value = null;
  51565. if (targetPath === "rotationQuaternion") {
  51566. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  51567. arrayOffset += 4;
  51568. }
  51569. else {
  51570. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  51571. arrayOffset += 3;
  51572. }
  51573. if (isBone) {
  51574. var bone = targetNode;
  51575. var translation = BABYLON.Vector3.Zero();
  51576. var rotationQuaternion = new BABYLON.Quaternion();
  51577. var scaling = BABYLON.Vector3.Zero();
  51578. // Warning on decompose
  51579. var mat = bone.getBaseMatrix();
  51580. if (modifyKey) {
  51581. mat = lastAnimation.getKeys()[j].value;
  51582. }
  51583. mat.decompose(scaling, rotationQuaternion, translation);
  51584. if (targetPath === "position") {
  51585. translation = value;
  51586. }
  51587. else if (targetPath === "rotationQuaternion") {
  51588. rotationQuaternion = value;
  51589. }
  51590. else {
  51591. scaling = value;
  51592. }
  51593. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  51594. }
  51595. if (!modifyKey) {
  51596. keys.push({
  51597. frame: bufferInput[j],
  51598. value: value
  51599. });
  51600. }
  51601. else {
  51602. lastAnimation.getKeys()[j].value = value;
  51603. }
  51604. }
  51605. // Finish
  51606. if (!modifyKey) {
  51607. babylonAnimation.setKeys(keys);
  51608. targetNode.animations.push(babylonAnimation);
  51609. }
  51610. lastAnimation = babylonAnimation;
  51611. gltfRuntime.scene.stopAnimation(targetNode);
  51612. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  51613. }
  51614. }
  51615. };
  51616. /**
  51617. * Returns the bones transformation matrix
  51618. */
  51619. var configureBoneTransformation = function (node) {
  51620. var mat = null;
  51621. if (node.translation || node.rotation || node.scale) {
  51622. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  51623. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  51624. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  51625. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  51626. }
  51627. else {
  51628. mat = BABYLON.Matrix.FromArray(node.matrix);
  51629. }
  51630. return mat;
  51631. };
  51632. /**
  51633. * Returns the parent bone
  51634. */
  51635. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  51636. // Try to find
  51637. for (var i = 0; i < newSkeleton.bones.length; i++) {
  51638. if (newSkeleton.bones[i].name === jointName) {
  51639. return newSkeleton.bones[i];
  51640. }
  51641. }
  51642. // Not found, search in gltf nodes
  51643. var nodes = gltfRuntime.nodes;
  51644. for (var nde in nodes) {
  51645. var node = nodes[nde];
  51646. if (!node.jointName) {
  51647. continue;
  51648. }
  51649. var children = node.children;
  51650. for (var i = 0; i < children.length; i++) {
  51651. var child = gltfRuntime.nodes[children[i]];
  51652. if (!child.jointName) {
  51653. continue;
  51654. }
  51655. if (child.jointName === jointName) {
  51656. var mat = configureBoneTransformation(node);
  51657. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  51658. bone.id = nde;
  51659. return bone;
  51660. }
  51661. }
  51662. }
  51663. return null;
  51664. };
  51665. /**
  51666. * Returns the appropriate root node
  51667. */
  51668. var getNodeToRoot = function (nodesToRoot, id) {
  51669. for (var i = 0; i < nodesToRoot.length; i++) {
  51670. var nodeToRoot = nodesToRoot[i];
  51671. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  51672. var child = nodeToRoot.node.children[j];
  51673. if (child === id) {
  51674. return nodeToRoot.bone;
  51675. }
  51676. }
  51677. }
  51678. return null;
  51679. };
  51680. /**
  51681. * Returns the node with the joint name
  51682. */
  51683. var getJointNode = function (gltfRuntime, jointName) {
  51684. var nodes = gltfRuntime.nodes;
  51685. var node = nodes[jointName];
  51686. if (node) {
  51687. return {
  51688. node: node,
  51689. id: jointName
  51690. };
  51691. }
  51692. for (var nde in nodes) {
  51693. node = nodes[nde];
  51694. if (node.jointName === jointName) {
  51695. return {
  51696. node: node,
  51697. id: nde
  51698. };
  51699. }
  51700. }
  51701. return null;
  51702. };
  51703. /**
  51704. * Checks if a nodes is in joints
  51705. */
  51706. var nodeIsInJoints = function (skins, id) {
  51707. for (var i = 0; i < skins.jointNames.length; i++) {
  51708. if (skins.jointNames[i] === id) {
  51709. return true;
  51710. }
  51711. }
  51712. return false;
  51713. };
  51714. /**
  51715. * Fills the nodes to root for bones and builds hierarchy
  51716. */
  51717. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  51718. // Creates nodes for root
  51719. for (var nde in gltfRuntime.nodes) {
  51720. var node = gltfRuntime.nodes[nde];
  51721. var id = nde;
  51722. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  51723. continue;
  51724. }
  51725. // Create node to root bone
  51726. var mat = configureBoneTransformation(node);
  51727. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  51728. bone.id = id;
  51729. nodesToRoot.push({ bone: bone, node: node, id: id });
  51730. }
  51731. // Parenting
  51732. for (var i = 0; i < nodesToRoot.length; i++) {
  51733. var nodeToRoot = nodesToRoot[i];
  51734. var children = nodeToRoot.node.children;
  51735. for (var j = 0; j < children.length; j++) {
  51736. var child = null;
  51737. for (var k = 0; k < nodesToRoot.length; k++) {
  51738. if (nodesToRoot[k].id === children[j]) {
  51739. child = nodesToRoot[k];
  51740. break;
  51741. }
  51742. }
  51743. if (child) {
  51744. child.bone._parent = nodeToRoot.bone;
  51745. nodeToRoot.bone.children.push(child.bone);
  51746. }
  51747. }
  51748. }
  51749. };
  51750. var printMat = function (m) {
  51751. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  51752. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  51753. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  51754. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  51755. };
  51756. /**
  51757. * Imports a skeleton
  51758. */
  51759. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  51760. if (!newSkeleton) {
  51761. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  51762. }
  51763. if (!skins.babylonSkeleton) {
  51764. return newSkeleton;
  51765. }
  51766. // Matrices
  51767. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  51768. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  51769. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  51770. // Find the root bones
  51771. var nodesToRoot = [];
  51772. var nodesToRootToAdd = [];
  51773. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  51774. newSkeleton.bones = [];
  51775. // Joints
  51776. for (var i = 0; i < skins.jointNames.length; i++) {
  51777. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  51778. var node = jointNode.node;
  51779. if (!node) {
  51780. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  51781. continue;
  51782. }
  51783. var id = jointNode.id;
  51784. // Optimize, if the bone already exists...
  51785. var existingBone = gltfRuntime.scene.getBoneByID(id);
  51786. if (existingBone) {
  51787. newSkeleton.bones.push(existingBone);
  51788. continue;
  51789. }
  51790. // Search for parent bone
  51791. var foundBone = false;
  51792. var parentBone = null;
  51793. for (var j = 0; j < i; j++) {
  51794. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  51795. if (!joint) {
  51796. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  51797. continue;
  51798. }
  51799. var children = joint.children;
  51800. if (!children) {
  51801. continue;
  51802. }
  51803. foundBone = false;
  51804. for (var k = 0; k < children.length; k++) {
  51805. if (children[k] === id) {
  51806. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  51807. foundBone = true;
  51808. break;
  51809. }
  51810. }
  51811. if (foundBone) {
  51812. break;
  51813. }
  51814. }
  51815. // Create bone
  51816. var mat = configureBoneTransformation(node);
  51817. if (!parentBone && nodesToRoot.length > 0) {
  51818. parentBone = getNodeToRoot(nodesToRoot, id);
  51819. if (parentBone) {
  51820. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  51821. nodesToRootToAdd.push(parentBone);
  51822. }
  51823. }
  51824. }
  51825. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  51826. bone.id = id;
  51827. }
  51828. // Polish
  51829. var bones = newSkeleton.bones;
  51830. newSkeleton.bones = [];
  51831. for (var i = 0; i < skins.jointNames.length; i++) {
  51832. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  51833. if (!jointNode) {
  51834. continue;
  51835. }
  51836. for (var j = 0; j < bones.length; j++) {
  51837. if (bones[j].id === jointNode.id) {
  51838. newSkeleton.bones.push(bones[j]);
  51839. break;
  51840. }
  51841. }
  51842. }
  51843. newSkeleton.prepare();
  51844. // Finish
  51845. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  51846. newSkeleton.bones.push(nodesToRootToAdd[i]);
  51847. }
  51848. return newSkeleton;
  51849. };
  51850. /**
  51851. * Imports a mesh and its geometries
  51852. */
  51853. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  51854. if (!newMesh) {
  51855. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  51856. newMesh.id = id;
  51857. }
  51858. if (!node.babylonNode) {
  51859. return newMesh;
  51860. }
  51861. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  51862. if (!newMesh.material) {
  51863. newMesh.material = multiMat;
  51864. }
  51865. var vertexData = new BABYLON.VertexData();
  51866. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  51867. var verticesStarts = [];
  51868. var verticesCounts = [];
  51869. var indexStarts = [];
  51870. var indexCounts = [];
  51871. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  51872. var meshID = meshes[meshIndex];
  51873. var mesh = gltfRuntime.meshes[meshID];
  51874. if (!mesh) {
  51875. continue;
  51876. }
  51877. // Positions, normals and UVs
  51878. for (var i = 0; i < mesh.primitives.length; i++) {
  51879. // Temporary vertex data
  51880. var tempVertexData = new BABYLON.VertexData();
  51881. var primitive = mesh.primitives[i];
  51882. if (primitive.mode !== 4) {
  51883. // continue;
  51884. }
  51885. var attributes = primitive.attributes;
  51886. var accessor = null;
  51887. var buffer = null;
  51888. // Set positions, normal and uvs
  51889. for (var semantic in attributes) {
  51890. // Link accessor and buffer view
  51891. accessor = gltfRuntime.accessors[attributes[semantic]];
  51892. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  51893. if (semantic === "NORMAL") {
  51894. tempVertexData.normals = new Float32Array(buffer.length);
  51895. tempVertexData.normals.set(buffer);
  51896. }
  51897. else if (semantic === "POSITION") {
  51898. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  51899. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  51900. for (var j = 0; j < buffer.length; j += 4) {
  51901. tempVertexData.positions[j] = buffer[j];
  51902. tempVertexData.positions[j + 1] = buffer[j + 1];
  51903. tempVertexData.positions[j + 2] = buffer[j + 2];
  51904. }
  51905. }
  51906. else {
  51907. tempVertexData.positions = new Float32Array(buffer.length);
  51908. tempVertexData.positions.set(buffer);
  51909. }
  51910. verticesCounts.push(tempVertexData.positions.length);
  51911. }
  51912. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  51913. var channel = Number(semantic.split("_")[1]);
  51914. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  51915. var uvs = new Float32Array(buffer.length);
  51916. uvs.set(buffer);
  51917. normalizeUVs(uvs);
  51918. tempVertexData.set(uvs, uvKind);
  51919. }
  51920. else if (semantic === "JOINT") {
  51921. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  51922. tempVertexData.matricesIndices.set(buffer);
  51923. }
  51924. else if (semantic === "WEIGHT") {
  51925. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  51926. tempVertexData.matricesWeights.set(buffer);
  51927. }
  51928. else if (semantic === "COLOR") {
  51929. tempVertexData.colors = new Float32Array(buffer.length);
  51930. tempVertexData.colors.set(buffer);
  51931. }
  51932. }
  51933. // Indices
  51934. accessor = gltfRuntime.accessors[primitive.indices];
  51935. if (accessor) {
  51936. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  51937. tempVertexData.indices = new Int32Array(buffer.length);
  51938. tempVertexData.indices.set(buffer);
  51939. indexCounts.push(tempVertexData.indices.length);
  51940. }
  51941. else {
  51942. // Set indices on the fly
  51943. var indices = [];
  51944. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  51945. indices.push(j);
  51946. }
  51947. tempVertexData.indices = new Int32Array(indices);
  51948. indexCounts.push(tempVertexData.indices.length);
  51949. }
  51950. vertexData.merge(tempVertexData);
  51951. tempVertexData = undefined;
  51952. // Sub material
  51953. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  51954. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  51955. // Update vertices start and index start
  51956. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  51957. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  51958. }
  51959. }
  51960. // Apply geometry
  51961. geometry.setAllVerticesData(vertexData, false);
  51962. newMesh.computeWorldMatrix(true);
  51963. // Apply submeshes
  51964. newMesh.subMeshes = [];
  51965. var index = 0;
  51966. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  51967. var meshID = meshes[meshIndex];
  51968. var mesh = gltfRuntime.meshes[meshID];
  51969. if (!mesh) {
  51970. continue;
  51971. }
  51972. for (var i = 0; i < mesh.primitives.length; i++) {
  51973. if (mesh.primitives[i].mode !== 4) {
  51974. //continue;
  51975. }
  51976. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  51977. index++;
  51978. }
  51979. }
  51980. // Finish
  51981. return newMesh;
  51982. };
  51983. /**
  51984. * Configure node transformation from position, rotation and scaling
  51985. */
  51986. var configureNode = function (newNode, position, rotation, scaling) {
  51987. if (newNode.position) {
  51988. newNode.position = position;
  51989. }
  51990. if (newNode.rotationQuaternion || newNode.rotation) {
  51991. newNode.rotationQuaternion = rotation;
  51992. }
  51993. if (newNode.scaling) {
  51994. newNode.scaling = scaling;
  51995. }
  51996. };
  51997. /**
  51998. * Configures node from transformation matrix
  51999. */
  52000. var configureNodeFromMatrix = function (newNode, node, parent) {
  52001. if (node.matrix) {
  52002. var position = new BABYLON.Vector3(0, 0, 0);
  52003. var rotation = new BABYLON.Quaternion();
  52004. var scaling = new BABYLON.Vector3(0, 0, 0);
  52005. var mat = BABYLON.Matrix.FromArray(node.matrix);
  52006. mat.decompose(scaling, rotation, position);
  52007. configureNode(newNode, position, rotation, scaling);
  52008. }
  52009. else {
  52010. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  52011. }
  52012. newNode.computeWorldMatrix(true);
  52013. };
  52014. /**
  52015. * Imports a node
  52016. */
  52017. var importNode = function (gltfRuntime, node, id, parent) {
  52018. var lastNode = null;
  52019. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  52020. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  52021. return null;
  52022. }
  52023. }
  52024. // Meshes
  52025. if (node.skin) {
  52026. if (node.meshes) {
  52027. var skin = gltfRuntime.skins[node.skin];
  52028. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  52029. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  52030. if (newMesh.skeleton === null) {
  52031. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  52032. if (!skin.babylonSkeleton) {
  52033. skin.babylonSkeleton = newMesh.skeleton;
  52034. }
  52035. }
  52036. lastNode = newMesh;
  52037. }
  52038. }
  52039. else if (node.meshes) {
  52040. /**
  52041. * Improve meshes property
  52042. */
  52043. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  52044. lastNode = newMesh;
  52045. }
  52046. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52047. var light = gltfRuntime.lights[node.light];
  52048. if (light) {
  52049. if (light.type === "ambient") {
  52050. var ambienLight = light[light.type];
  52051. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52052. hemiLight.name = node.name;
  52053. if (ambienLight.color) {
  52054. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  52055. }
  52056. lastNode = hemiLight;
  52057. }
  52058. else if (light.type === "directional") {
  52059. var directionalLight = light[light.type];
  52060. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52061. dirLight.name = node.name;
  52062. if (directionalLight.color) {
  52063. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  52064. }
  52065. lastNode = dirLight;
  52066. }
  52067. else if (light.type === "point") {
  52068. var pointLight = light[light.type];
  52069. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52070. ptLight.name = node.name;
  52071. if (pointLight.color) {
  52072. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  52073. }
  52074. lastNode = ptLight;
  52075. }
  52076. else if (light.type === "spot") {
  52077. var spotLight = light[light.type];
  52078. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  52079. spLight.name = node.name;
  52080. if (spotLight.color) {
  52081. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  52082. }
  52083. if (spotLight.fallOfAngle) {
  52084. spLight.angle = spotLight.fallOfAngle;
  52085. }
  52086. if (spotLight.fallOffExponent) {
  52087. spLight.exponent = spotLight.fallOffExponent;
  52088. }
  52089. lastNode = spLight;
  52090. }
  52091. }
  52092. }
  52093. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52094. var camera = gltfRuntime.cameras[node.camera];
  52095. if (camera) {
  52096. if (camera.type === "orthographic") {
  52097. var orthographicCamera = camera[camera.type];
  52098. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52099. orthoCamera.name = node.name;
  52100. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  52101. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52102. lastNode = orthoCamera;
  52103. }
  52104. else if (camera.type === "perspective") {
  52105. var perspectiveCamera = camera[camera.type];
  52106. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52107. persCamera.name = node.name;
  52108. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52109. if (!perspectiveCamera.aspectRatio) {
  52110. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  52111. }
  52112. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  52113. persCamera.maxZ = perspectiveCamera.zfar;
  52114. persCamera.minZ = perspectiveCamera.znear;
  52115. }
  52116. lastNode = persCamera;
  52117. }
  52118. }
  52119. }
  52120. // Empty node
  52121. if (!node.jointName) {
  52122. if (node.babylonNode) {
  52123. return node.babylonNode;
  52124. }
  52125. else if (lastNode === null) {
  52126. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52127. node.babylonNode = dummy;
  52128. lastNode = dummy;
  52129. }
  52130. }
  52131. if (lastNode !== null) {
  52132. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  52133. configureNodeFromMatrix(lastNode, node, parent);
  52134. }
  52135. else {
  52136. var translation = node.translation || [0, 0, 0];
  52137. var rotation = node.rotation || [0, 0, 0, 1];
  52138. var scale = node.scale || [1, 1, 1];
  52139. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  52140. }
  52141. lastNode.updateCache(true);
  52142. node.babylonNode = lastNode;
  52143. }
  52144. return lastNode;
  52145. };
  52146. /**
  52147. * Traverses nodes and creates them
  52148. */
  52149. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  52150. var node = gltfRuntime.nodes[id];
  52151. var newNode = null;
  52152. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  52153. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  52154. meshIncluded = true;
  52155. }
  52156. else {
  52157. meshIncluded = false;
  52158. }
  52159. }
  52160. else {
  52161. meshIncluded = true;
  52162. }
  52163. if (!node.jointName && meshIncluded) {
  52164. newNode = importNode(gltfRuntime, node, id, parent);
  52165. if (newNode !== null) {
  52166. newNode.id = id;
  52167. newNode.parent = parent;
  52168. }
  52169. }
  52170. if (node.children) {
  52171. for (var i = 0; i < node.children.length; i++) {
  52172. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  52173. }
  52174. }
  52175. };
  52176. /**
  52177. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  52178. */
  52179. var postLoad = function (gltfRuntime) {
  52180. // Nodes
  52181. var currentScene = gltfRuntime.currentScene;
  52182. if (currentScene) {
  52183. for (var i = 0; i < currentScene.nodes.length; i++) {
  52184. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52185. }
  52186. }
  52187. else {
  52188. for (var thing in gltfRuntime.scenes) {
  52189. currentScene = gltfRuntime.scenes[thing];
  52190. for (var i = 0; i < currentScene.nodes.length; i++) {
  52191. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52192. }
  52193. }
  52194. }
  52195. // Set animations
  52196. loadAnimations(gltfRuntime);
  52197. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  52198. var skeleton = gltfRuntime.scene.skeletons[i];
  52199. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  52200. }
  52201. };
  52202. /**
  52203. * onBind shaderrs callback to set uniforms and matrices
  52204. */
  52205. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  52206. var materialValues = material.values || technique.parameters;
  52207. for (var unif in unTreatedUniforms) {
  52208. var uniform = unTreatedUniforms[unif];
  52209. var type = uniform.type;
  52210. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  52211. if (uniform.semantic && !uniform.source && !uniform.node) {
  52212. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  52213. }
  52214. else if (uniform.semantic && (uniform.source || uniform.node)) {
  52215. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  52216. if (source === null) {
  52217. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  52218. }
  52219. if (source === null) {
  52220. continue;
  52221. }
  52222. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  52223. }
  52224. }
  52225. else {
  52226. var value = materialValues[technique.uniforms[unif]];
  52227. if (!value) {
  52228. continue;
  52229. }
  52230. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52231. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  52232. if (texture === null || texture === undefined) {
  52233. continue;
  52234. }
  52235. shaderMaterial.getEffect().setTexture(unif, texture);
  52236. }
  52237. else {
  52238. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  52239. }
  52240. }
  52241. }
  52242. onSuccess(shaderMaterial);
  52243. };
  52244. /**
  52245. * Prepare uniforms to send the only one time
  52246. * Loads the appropriate textures
  52247. */
  52248. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  52249. var materialValues = material.values || technique.parameters;
  52250. var techniqueUniforms = technique.uniforms;
  52251. /**
  52252. * Prepare values here (not matrices)
  52253. */
  52254. for (var unif in unTreatedUniforms) {
  52255. var uniform = unTreatedUniforms[unif];
  52256. var type = uniform.type;
  52257. var value = materialValues[techniqueUniforms[unif]];
  52258. if (value === undefined) {
  52259. // In case the value is the same for all materials
  52260. value = uniform.value;
  52261. }
  52262. if (!value) {
  52263. continue;
  52264. }
  52265. var onLoadTexture = function (uniformName) {
  52266. return function (texture) {
  52267. if (uniform.value) {
  52268. // Static uniform
  52269. shaderMaterial.setTexture(uniformName, texture);
  52270. delete unTreatedUniforms[uniformName];
  52271. }
  52272. };
  52273. };
  52274. // Texture (sampler2D)
  52275. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52276. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  52277. }
  52278. else {
  52279. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  52280. // Static uniform
  52281. delete unTreatedUniforms[unif];
  52282. }
  52283. }
  52284. }
  52285. };
  52286. /**
  52287. * Shader compilation failed
  52288. */
  52289. var onShaderCompileError = function (program, shaderMaterial, onError) {
  52290. return function (effect, error) {
  52291. shaderMaterial.dispose(true);
  52292. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  52293. };
  52294. };
  52295. /**
  52296. * Shader compilation success
  52297. */
  52298. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  52299. return function (_) {
  52300. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  52301. shaderMaterial.onBind = function (mesh) {
  52302. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  52303. };
  52304. };
  52305. };
  52306. /**
  52307. * Returns the appropriate uniform if already handled by babylon
  52308. */
  52309. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  52310. for (var unif in technique.uniforms) {
  52311. var uniform = technique.uniforms[unif];
  52312. var uniformParameter = technique.parameters[uniform];
  52313. if (tokenizer.currentIdentifier === unif) {
  52314. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  52315. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52316. if (transformIndex !== -1) {
  52317. delete unTreatedUniforms[unif];
  52318. return babylonTransforms[transformIndex];
  52319. }
  52320. }
  52321. }
  52322. }
  52323. return tokenizer.currentIdentifier;
  52324. };
  52325. /**
  52326. * All shaders loaded. Create materials one by one
  52327. */
  52328. var importMaterials = function (gltfRuntime) {
  52329. // Create materials
  52330. for (var mat in gltfRuntime.materials) {
  52331. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  52332. }
  52333. };
  52334. /**
  52335. * Implementation of the base glTF spec
  52336. */
  52337. var GLTFLoaderBase = (function () {
  52338. function GLTFLoaderBase() {
  52339. }
  52340. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  52341. var gltfRuntime = {
  52342. extensions: {},
  52343. accessors: {},
  52344. buffers: {},
  52345. bufferViews: {},
  52346. meshes: {},
  52347. lights: {},
  52348. cameras: {},
  52349. nodes: {},
  52350. images: {},
  52351. textures: {},
  52352. shaders: {},
  52353. programs: {},
  52354. samplers: {},
  52355. techniques: {},
  52356. materials: {},
  52357. animations: {},
  52358. skins: {},
  52359. extensionsUsed: [],
  52360. scenes: {},
  52361. buffersCount: 0,
  52362. shaderscount: 0,
  52363. scene: scene,
  52364. rootUrl: rootUrl,
  52365. loadedBufferCount: 0,
  52366. loadedBufferViews: {},
  52367. loadedShaderCount: 0,
  52368. importOnlyMeshes: false,
  52369. dummyNodes: []
  52370. };
  52371. // Parse
  52372. if (parsedData.extensions) {
  52373. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  52374. }
  52375. if (parsedData.extensionsUsed) {
  52376. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  52377. }
  52378. if (parsedData.buffers) {
  52379. parseBuffers(parsedData.buffers, gltfRuntime);
  52380. }
  52381. if (parsedData.bufferViews) {
  52382. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  52383. }
  52384. if (parsedData.accessors) {
  52385. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  52386. }
  52387. if (parsedData.meshes) {
  52388. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  52389. }
  52390. if (parsedData.lights) {
  52391. parseObject(parsedData.lights, "lights", gltfRuntime);
  52392. }
  52393. if (parsedData.cameras) {
  52394. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  52395. }
  52396. if (parsedData.nodes) {
  52397. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  52398. }
  52399. if (parsedData.images) {
  52400. parseObject(parsedData.images, "images", gltfRuntime);
  52401. }
  52402. if (parsedData.textures) {
  52403. parseObject(parsedData.textures, "textures", gltfRuntime);
  52404. }
  52405. if (parsedData.shaders) {
  52406. parseShaders(parsedData.shaders, gltfRuntime);
  52407. }
  52408. if (parsedData.programs) {
  52409. parseObject(parsedData.programs, "programs", gltfRuntime);
  52410. }
  52411. if (parsedData.samplers) {
  52412. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  52413. }
  52414. if (parsedData.techniques) {
  52415. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  52416. }
  52417. if (parsedData.materials) {
  52418. parseObject(parsedData.materials, "materials", gltfRuntime);
  52419. }
  52420. if (parsedData.animations) {
  52421. parseObject(parsedData.animations, "animations", gltfRuntime);
  52422. }
  52423. if (parsedData.skins) {
  52424. parseObject(parsedData.skins, "skins", gltfRuntime);
  52425. }
  52426. if (parsedData.scenes) {
  52427. gltfRuntime.scenes = parsedData.scenes;
  52428. }
  52429. if (parsedData.scene && parsedData.scenes) {
  52430. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  52431. }
  52432. return gltfRuntime;
  52433. };
  52434. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  52435. var buffer = gltfRuntime.buffers[id];
  52436. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  52437. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  52438. }
  52439. else {
  52440. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  52441. onError(request.status + " " + request.statusText);
  52442. });
  52443. }
  52444. };
  52445. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  52446. var texture = gltfRuntime.textures[id];
  52447. if (!texture || !texture.source) {
  52448. onError(null);
  52449. return;
  52450. }
  52451. if (texture.babylonTexture) {
  52452. onSuccess(null);
  52453. return;
  52454. }
  52455. var source = gltfRuntime.images[texture.source];
  52456. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  52457. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  52458. }
  52459. else {
  52460. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  52461. onError(request.status + " " + request.statusText);
  52462. });
  52463. }
  52464. };
  52465. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  52466. var texture = gltfRuntime.textures[id];
  52467. if (texture.babylonTexture) {
  52468. onSuccess(texture.babylonTexture);
  52469. return;
  52470. }
  52471. var sampler = gltfRuntime.samplers[texture.sampler];
  52472. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  52473. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  52474. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  52475. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  52476. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  52477. var blob = new Blob([buffer]);
  52478. var blobURL = URL.createObjectURL(blob);
  52479. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  52480. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  52481. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  52482. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  52483. newTexture.name = id;
  52484. texture.babylonTexture = newTexture;
  52485. onSuccess(newTexture);
  52486. };
  52487. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  52488. var shader = gltfRuntime.shaders[id];
  52489. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  52490. var shaderString = atob(shader.uri.split(",")[1]);
  52491. onSuccess(shaderString);
  52492. }
  52493. else {
  52494. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  52495. onError(request.status + " " + request.statusText);
  52496. });
  52497. }
  52498. };
  52499. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  52500. var material = gltfRuntime.materials[id];
  52501. var technique = gltfRuntime.techniques[material.technique];
  52502. if (!technique) {
  52503. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  52504. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  52505. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52506. onSuccess(defaultMaterial);
  52507. return;
  52508. }
  52509. var program = gltfRuntime.programs[technique.program];
  52510. var states = technique.states;
  52511. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  52512. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  52513. var newVertexShader = "";
  52514. var newPixelShader = "";
  52515. var vertexTokenizer = new Tokenizer(vertexShader);
  52516. var pixelTokenizer = new Tokenizer(pixelShader);
  52517. var unTreatedUniforms = {};
  52518. var uniforms = [];
  52519. var attributes = [];
  52520. var samplers = [];
  52521. // Fill uniform, sampler2D and attributes
  52522. for (var unif in technique.uniforms) {
  52523. var uniform = technique.uniforms[unif];
  52524. var uniformParameter = technique.parameters[uniform];
  52525. unTreatedUniforms[unif] = uniformParameter;
  52526. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  52527. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52528. if (transformIndex !== -1) {
  52529. uniforms.push(babylonTransforms[transformIndex]);
  52530. delete unTreatedUniforms[unif];
  52531. }
  52532. else {
  52533. uniforms.push(unif);
  52534. }
  52535. }
  52536. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  52537. samplers.push(unif);
  52538. }
  52539. else {
  52540. uniforms.push(unif);
  52541. }
  52542. }
  52543. for (var attr in technique.attributes) {
  52544. var attribute = technique.attributes[attr];
  52545. var attributeParameter = technique.parameters[attribute];
  52546. if (attributeParameter.semantic) {
  52547. attributes.push(getAttribute(attributeParameter));
  52548. }
  52549. }
  52550. // Configure vertex shader
  52551. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  52552. var tokenType = vertexTokenizer.currentToken;
  52553. if (tokenType !== ETokenType.IDENTIFIER) {
  52554. newVertexShader += vertexTokenizer.currentString;
  52555. continue;
  52556. }
  52557. var foundAttribute = false;
  52558. for (var attr in technique.attributes) {
  52559. var attribute = technique.attributes[attr];
  52560. var attributeParameter = technique.parameters[attribute];
  52561. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  52562. newVertexShader += getAttribute(attributeParameter);
  52563. foundAttribute = true;
  52564. break;
  52565. }
  52566. }
  52567. if (foundAttribute) {
  52568. continue;
  52569. }
  52570. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  52571. }
  52572. // Configure pixel shader
  52573. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  52574. var tokenType = pixelTokenizer.currentToken;
  52575. if (tokenType !== ETokenType.IDENTIFIER) {
  52576. newPixelShader += pixelTokenizer.currentString;
  52577. continue;
  52578. }
  52579. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  52580. }
  52581. // Create shader material
  52582. var shaderPath = {
  52583. vertex: program.vertexShader + id,
  52584. fragment: program.fragmentShader + id
  52585. };
  52586. var options = {
  52587. attributes: attributes,
  52588. uniforms: uniforms,
  52589. samplers: samplers,
  52590. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  52591. };
  52592. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  52593. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  52594. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  52595. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  52596. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  52597. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52598. if (states && states.functions) {
  52599. var functions = states.functions;
  52600. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  52601. shaderMaterial.backFaceCulling = false;
  52602. }
  52603. var blendFunc = functions.blendFuncSeparate;
  52604. if (blendFunc) {
  52605. 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) {
  52606. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  52607. }
  52608. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52609. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  52610. }
  52611. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52612. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  52613. }
  52614. 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) {
  52615. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  52616. }
  52617. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52618. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  52619. }
  52620. 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) {
  52621. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  52622. }
  52623. }
  52624. }
  52625. };
  52626. return GLTFLoaderBase;
  52627. }());
  52628. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  52629. /**
  52630. * glTF V1 Loader
  52631. */
  52632. var GLTFLoader = (function () {
  52633. function GLTFLoader() {
  52634. }
  52635. GLTFLoader.RegisterExtension = function (extension) {
  52636. if (GLTFLoader.Extensions[extension.name]) {
  52637. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  52638. return;
  52639. }
  52640. GLTFLoader.Extensions[extension.name] = extension;
  52641. };
  52642. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  52643. var _this = this;
  52644. scene.useRightHandedSystem = true;
  52645. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  52646. gltfRuntime.importOnlyMeshes = true;
  52647. if (meshesNames === "") {
  52648. gltfRuntime.importMeshesNames = [];
  52649. }
  52650. else if (typeof meshesNames === "string") {
  52651. gltfRuntime.importMeshesNames = [meshesNames];
  52652. }
  52653. else if (meshesNames && !(meshesNames instanceof Array)) {
  52654. gltfRuntime.importMeshesNames = [meshesNames];
  52655. }
  52656. else {
  52657. gltfRuntime.importMeshesNames = [];
  52658. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  52659. }
  52660. // Create nodes
  52661. _this._createNodes(gltfRuntime);
  52662. var meshes = [];
  52663. var skeletons = [];
  52664. // Fill arrays of meshes and skeletons
  52665. for (var nde in gltfRuntime.nodes) {
  52666. var node = gltfRuntime.nodes[nde];
  52667. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  52668. meshes.push(node.babylonNode);
  52669. }
  52670. }
  52671. for (var skl in gltfRuntime.skins) {
  52672. var skin = gltfRuntime.skins[skl];
  52673. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  52674. skeletons.push(skin.babylonSkeleton);
  52675. }
  52676. }
  52677. // Load buffers, shaders, materials, etc.
  52678. _this._loadBuffersAsync(gltfRuntime, function () {
  52679. _this._loadShadersAsync(gltfRuntime, function () {
  52680. importMaterials(gltfRuntime);
  52681. postLoad(gltfRuntime);
  52682. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  52683. onSuccess(meshes, null, skeletons);
  52684. }
  52685. });
  52686. }, onProgress);
  52687. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  52688. onSuccess(meshes, null, skeletons);
  52689. }
  52690. }, onError);
  52691. return true;
  52692. };
  52693. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  52694. var _this = this;
  52695. scene.useRightHandedSystem = true;
  52696. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  52697. // Load runtime extensios
  52698. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  52699. // Create nodes
  52700. _this._createNodes(gltfRuntime);
  52701. // Load buffers, shaders, materials, etc.
  52702. _this._loadBuffersAsync(gltfRuntime, function () {
  52703. _this._loadShadersAsync(gltfRuntime, function () {
  52704. importMaterials(gltfRuntime);
  52705. postLoad(gltfRuntime);
  52706. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  52707. onSuccess();
  52708. }
  52709. });
  52710. });
  52711. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  52712. onSuccess();
  52713. }
  52714. }, onError);
  52715. }, onError);
  52716. };
  52717. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  52718. var hasShaders = false;
  52719. var processShader = function (sha, shader) {
  52720. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  52721. gltfRuntime.loadedShaderCount++;
  52722. if (shaderString) {
  52723. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  52724. }
  52725. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  52726. onload();
  52727. }
  52728. }, function () {
  52729. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  52730. });
  52731. };
  52732. for (var sha in gltfRuntime.shaders) {
  52733. hasShaders = true;
  52734. var shader = gltfRuntime.shaders[sha];
  52735. if (shader) {
  52736. processShader.bind(this, sha, shader)();
  52737. }
  52738. else {
  52739. BABYLON.Tools.Error("No shader named: " + sha);
  52740. }
  52741. }
  52742. if (!hasShaders) {
  52743. onload();
  52744. }
  52745. };
  52746. ;
  52747. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  52748. var hasBuffers = false;
  52749. var processBuffer = function (buf, buffer) {
  52750. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  52751. gltfRuntime.loadedBufferCount++;
  52752. if (bufferView) {
  52753. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  52754. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  52755. }
  52756. gltfRuntime.loadedBufferViews[buf] = bufferView;
  52757. }
  52758. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  52759. onLoad();
  52760. }
  52761. }, function () {
  52762. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  52763. });
  52764. };
  52765. for (var buf in gltfRuntime.buffers) {
  52766. hasBuffers = true;
  52767. var buffer = gltfRuntime.buffers[buf];
  52768. if (buffer) {
  52769. processBuffer.bind(this, buf, buffer)();
  52770. }
  52771. else {
  52772. BABYLON.Tools.Error("No buffer named: " + buf);
  52773. }
  52774. }
  52775. if (!hasBuffers) {
  52776. onLoad();
  52777. }
  52778. };
  52779. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  52780. var currentScene = gltfRuntime.currentScene;
  52781. if (currentScene) {
  52782. // Only one scene even if multiple scenes are defined
  52783. for (var i = 0; i < currentScene.nodes.length; i++) {
  52784. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52785. }
  52786. }
  52787. else {
  52788. // Load all scenes
  52789. for (var thing in gltfRuntime.scenes) {
  52790. currentScene = gltfRuntime.scenes[thing];
  52791. for (var i = 0; i < currentScene.nodes.length; i++) {
  52792. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52793. }
  52794. }
  52795. }
  52796. };
  52797. GLTFLoader.Extensions = {};
  52798. return GLTFLoader;
  52799. }());
  52800. GLTF1.GLTFLoader = GLTFLoader;
  52801. ;
  52802. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  52803. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  52804. })(BABYLON || (BABYLON = {}));
  52805. //# sourceMappingURL=babylon.glTFLoader.js.map
  52806. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  52807. var BABYLON;
  52808. (function (BABYLON) {
  52809. var GLTF1;
  52810. (function (GLTF1) {
  52811. /**
  52812. * Utils functions for GLTF
  52813. */
  52814. var GLTFUtils = (function () {
  52815. function GLTFUtils() {
  52816. }
  52817. /**
  52818. * Sets the given "parameter" matrix
  52819. * @param scene: the {BABYLON.Scene} object
  52820. * @param source: the source node where to pick the matrix
  52821. * @param parameter: the GLTF technique parameter
  52822. * @param uniformName: the name of the shader's uniform
  52823. * @param shaderMaterial: the shader material
  52824. */
  52825. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  52826. var mat = null;
  52827. if (parameter.semantic === "MODEL") {
  52828. mat = source.getWorldMatrix();
  52829. }
  52830. else if (parameter.semantic === "PROJECTION") {
  52831. mat = scene.getProjectionMatrix();
  52832. }
  52833. else if (parameter.semantic === "VIEW") {
  52834. mat = scene.getViewMatrix();
  52835. }
  52836. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  52837. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  52838. }
  52839. else if (parameter.semantic === "MODELVIEW") {
  52840. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  52841. }
  52842. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  52843. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  52844. }
  52845. else if (parameter.semantic === "MODELINVERSE") {
  52846. mat = source.getWorldMatrix().invert();
  52847. }
  52848. else if (parameter.semantic === "VIEWINVERSE") {
  52849. mat = scene.getViewMatrix().invert();
  52850. }
  52851. else if (parameter.semantic === "PROJECTIONINVERSE") {
  52852. mat = scene.getProjectionMatrix().invert();
  52853. }
  52854. else if (parameter.semantic === "MODELVIEWINVERSE") {
  52855. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  52856. }
  52857. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  52858. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  52859. }
  52860. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  52861. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  52862. }
  52863. else {
  52864. debugger;
  52865. }
  52866. switch (parameter.type) {
  52867. case GLTF1.EParameterType.FLOAT_MAT2:
  52868. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  52869. break;
  52870. case GLTF1.EParameterType.FLOAT_MAT3:
  52871. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  52872. break;
  52873. case GLTF1.EParameterType.FLOAT_MAT4:
  52874. shaderMaterial.setMatrix(uniformName, mat);
  52875. break;
  52876. default: break;
  52877. }
  52878. };
  52879. /**
  52880. * Sets the given "parameter" matrix
  52881. * @param shaderMaterial: the shader material
  52882. * @param uniform: the name of the shader's uniform
  52883. * @param value: the value of the uniform
  52884. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  52885. */
  52886. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  52887. switch (type) {
  52888. case GLTF1.EParameterType.FLOAT:
  52889. shaderMaterial.setFloat(uniform, value);
  52890. return true;
  52891. case GLTF1.EParameterType.FLOAT_VEC2:
  52892. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  52893. return true;
  52894. case GLTF1.EParameterType.FLOAT_VEC3:
  52895. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  52896. return true;
  52897. case GLTF1.EParameterType.FLOAT_VEC4:
  52898. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  52899. return true;
  52900. default: return false;
  52901. }
  52902. };
  52903. /**
  52904. * If the uri is a base64 string
  52905. * @param uri: the uri to test
  52906. */
  52907. GLTFUtils.IsBase64 = function (uri) {
  52908. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  52909. };
  52910. /**
  52911. * Decode the base64 uri
  52912. * @param uri: the uri to decode
  52913. */
  52914. GLTFUtils.DecodeBase64 = function (uri) {
  52915. var decodedString = atob(uri.split(",")[1]);
  52916. var bufferLength = decodedString.length;
  52917. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  52918. for (var i = 0; i < bufferLength; i++) {
  52919. bufferView[i] = decodedString.charCodeAt(i);
  52920. }
  52921. return bufferView.buffer;
  52922. };
  52923. /**
  52924. * Returns the wrap mode of the texture
  52925. * @param mode: the mode value
  52926. */
  52927. GLTFUtils.GetWrapMode = function (mode) {
  52928. switch (mode) {
  52929. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  52930. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  52931. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  52932. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  52933. }
  52934. };
  52935. /**
  52936. * Returns the byte stride giving an accessor
  52937. * @param accessor: the GLTF accessor objet
  52938. */
  52939. GLTFUtils.GetByteStrideFromType = function (accessor) {
  52940. // Needs this function since "byteStride" isn't requiered in glTF format
  52941. var type = accessor.type;
  52942. switch (type) {
  52943. case "VEC2": return 2;
  52944. case "VEC3": return 3;
  52945. case "VEC4": return 4;
  52946. case "MAT2": return 4;
  52947. case "MAT3": return 9;
  52948. case "MAT4": return 16;
  52949. default: return 1;
  52950. }
  52951. };
  52952. /**
  52953. * Returns the texture filter mode giving a mode value
  52954. * @param mode: the filter mode value
  52955. */
  52956. GLTFUtils.GetTextureFilterMode = function (mode) {
  52957. switch (mode) {
  52958. case GLTF1.ETextureFilterType.LINEAR:
  52959. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  52960. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  52961. case GLTF1.ETextureFilterType.NEAREST:
  52962. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  52963. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  52964. }
  52965. };
  52966. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  52967. var byteOffset = bufferView.byteOffset + byteOffset;
  52968. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  52969. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  52970. throw new Error("Buffer access is out of range");
  52971. }
  52972. var buffer = loadedBufferView.buffer;
  52973. byteOffset += loadedBufferView.byteOffset;
  52974. switch (componentType) {
  52975. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  52976. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  52977. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  52978. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  52979. default: return new Float32Array(buffer, byteOffset, byteLength);
  52980. }
  52981. };
  52982. /**
  52983. * Returns a buffer from its accessor
  52984. * @param gltfRuntime: the GLTF runtime
  52985. * @param accessor: the GLTF accessor
  52986. */
  52987. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  52988. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  52989. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  52990. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  52991. };
  52992. /**
  52993. * Decodes a buffer view into a string
  52994. * @param view: the buffer view
  52995. */
  52996. GLTFUtils.DecodeBufferToText = function (view) {
  52997. var result = "";
  52998. var length = view.byteLength;
  52999. for (var i = 0; i < length; ++i) {
  53000. result += String.fromCharCode(view[i]);
  53001. }
  53002. return result;
  53003. };
  53004. /**
  53005. * Returns the default material of gltf. Related to
  53006. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  53007. * @param scene: the Babylon.js scene
  53008. */
  53009. GLTFUtils.GetDefaultMaterial = function (scene) {
  53010. if (!GLTFUtils._DefaultMaterial) {
  53011. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  53012. "precision highp float;",
  53013. "",
  53014. "uniform mat4 worldView;",
  53015. "uniform mat4 projection;",
  53016. "",
  53017. "attribute vec3 position;",
  53018. "",
  53019. "void main(void)",
  53020. "{",
  53021. " gl_Position = projection * worldView * vec4(position, 1.0);",
  53022. "}"
  53023. ].join("\n");
  53024. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  53025. "precision highp float;",
  53026. "",
  53027. "uniform vec4 u_emission;",
  53028. "",
  53029. "void main(void)",
  53030. "{",
  53031. " gl_FragColor = u_emission;",
  53032. "}"
  53033. ].join("\n");
  53034. var shaderPath = {
  53035. vertex: "GLTFDefaultMaterial",
  53036. fragment: "GLTFDefaultMaterial"
  53037. };
  53038. var options = {
  53039. attributes: ["position"],
  53040. uniforms: ["worldView", "projection", "u_emission"],
  53041. samplers: [],
  53042. needAlphaBlending: false
  53043. };
  53044. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  53045. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  53046. }
  53047. return GLTFUtils._DefaultMaterial;
  53048. };
  53049. // The GLTF default material
  53050. GLTFUtils._DefaultMaterial = null;
  53051. return GLTFUtils;
  53052. }());
  53053. GLTF1.GLTFUtils = GLTFUtils;
  53054. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53055. })(BABYLON || (BABYLON = {}));
  53056. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  53057. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53058. var BABYLON;
  53059. (function (BABYLON) {
  53060. var GLTF1;
  53061. (function (GLTF1) {
  53062. var GLTFLoaderExtension = (function () {
  53063. function GLTFLoaderExtension(name) {
  53064. this._name = name;
  53065. }
  53066. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  53067. get: function () {
  53068. return this._name;
  53069. },
  53070. enumerable: true,
  53071. configurable: true
  53072. });
  53073. /**
  53074. * Defines an override for loading the runtime
  53075. * Return true to stop further extensions from loading the runtime
  53076. */
  53077. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53078. return false;
  53079. };
  53080. /**
  53081. * Defines an onverride for creating gltf runtime
  53082. * Return true to stop further extensions from creating the runtime
  53083. */
  53084. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53085. return false;
  53086. };
  53087. /**
  53088. * Defines an override for loading buffers
  53089. * Return true to stop further extensions from loading this buffer
  53090. */
  53091. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53092. return false;
  53093. };
  53094. /**
  53095. * Defines an override for loading texture buffers
  53096. * Return true to stop further extensions from loading this texture data
  53097. */
  53098. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53099. return false;
  53100. };
  53101. /**
  53102. * Defines an override for creating textures
  53103. * Return true to stop further extensions from loading this texture
  53104. */
  53105. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53106. return false;
  53107. };
  53108. /**
  53109. * Defines an override for loading shader strings
  53110. * Return true to stop further extensions from loading this shader data
  53111. */
  53112. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53113. return false;
  53114. };
  53115. /**
  53116. * Defines an override for loading materials
  53117. * Return true to stop further extensions from loading this material
  53118. */
  53119. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53120. return false;
  53121. };
  53122. // ---------
  53123. // Utilities
  53124. // ---------
  53125. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53126. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53127. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  53128. }, function () {
  53129. setTimeout(function () {
  53130. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53131. });
  53132. });
  53133. };
  53134. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53135. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53136. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  53137. }, function () {
  53138. setTimeout(function () {
  53139. onSuccess();
  53140. });
  53141. });
  53142. };
  53143. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53144. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53145. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53146. }, function () {
  53147. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53148. });
  53149. };
  53150. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  53151. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  53152. };
  53153. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53154. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53155. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53156. }, function () {
  53157. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53158. });
  53159. };
  53160. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53161. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53162. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53163. }, function () {
  53164. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53165. });
  53166. };
  53167. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53168. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53169. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53170. }, function () {
  53171. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53172. });
  53173. };
  53174. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53175. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53176. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53177. }, function () {
  53178. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53179. });
  53180. };
  53181. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  53182. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  53183. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  53184. if (func(loaderExtension)) {
  53185. return;
  53186. }
  53187. }
  53188. defaultFunc();
  53189. };
  53190. return GLTFLoaderExtension;
  53191. }());
  53192. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  53193. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53194. })(BABYLON || (BABYLON = {}));
  53195. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  53196. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53197. var BABYLON;
  53198. (function (BABYLON) {
  53199. var GLTF1;
  53200. (function (GLTF1) {
  53201. var BinaryExtensionBufferName = "binary_glTF";
  53202. var EContentFormat;
  53203. (function (EContentFormat) {
  53204. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  53205. })(EContentFormat || (EContentFormat = {}));
  53206. ;
  53207. ;
  53208. ;
  53209. var GLTFBinaryExtension = (function (_super) {
  53210. __extends(GLTFBinaryExtension, _super);
  53211. function GLTFBinaryExtension() {
  53212. return _super.call(this, "KHR_binary_glTF") || this;
  53213. }
  53214. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53215. var extensionsUsed = data.json.extensionsUsed;
  53216. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  53217. return false;
  53218. }
  53219. this._bin = data.bin;
  53220. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53221. return true;
  53222. };
  53223. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53224. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  53225. return false;
  53226. }
  53227. if (id !== BinaryExtensionBufferName) {
  53228. return false;
  53229. }
  53230. onSuccess(this._bin);
  53231. return true;
  53232. };
  53233. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53234. var texture = gltfRuntime.textures[id];
  53235. var source = gltfRuntime.images[texture.source];
  53236. if (!source.extensions || !(this.name in source.extensions)) {
  53237. return false;
  53238. }
  53239. var sourceExt = source.extensions[this.name];
  53240. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  53241. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53242. onSuccess(buffer);
  53243. return true;
  53244. };
  53245. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53246. var shader = gltfRuntime.shaders[id];
  53247. if (!shader.extensions || !(this.name in shader.extensions)) {
  53248. return false;
  53249. }
  53250. var binaryExtensionShader = shader.extensions[this.name];
  53251. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  53252. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53253. setTimeout(function () {
  53254. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  53255. onSuccess(shaderString);
  53256. });
  53257. return true;
  53258. };
  53259. return GLTFBinaryExtension;
  53260. }(GLTF1.GLTFLoaderExtension));
  53261. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  53262. var BinaryReader = (function () {
  53263. function BinaryReader(arrayBuffer) {
  53264. this._arrayBuffer = arrayBuffer;
  53265. this._dataView = new DataView(arrayBuffer);
  53266. this._byteOffset = 0;
  53267. }
  53268. BinaryReader.prototype.getUint32 = function () {
  53269. var value = this._dataView.getUint32(this._byteOffset, true);
  53270. this._byteOffset += 4;
  53271. return value;
  53272. };
  53273. BinaryReader.prototype.getUint8Array = function (length) {
  53274. if (!length) {
  53275. length = this._arrayBuffer.byteLength - this._byteOffset;
  53276. }
  53277. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  53278. this._byteOffset += length;
  53279. return value;
  53280. };
  53281. return BinaryReader;
  53282. }());
  53283. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  53284. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53285. })(BABYLON || (BABYLON = {}));
  53286. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  53287. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53288. var BABYLON;
  53289. (function (BABYLON) {
  53290. var GLTF1;
  53291. (function (GLTF1) {
  53292. ;
  53293. ;
  53294. ;
  53295. var GLTFMaterialsCommonExtension = (function (_super) {
  53296. __extends(GLTFMaterialsCommonExtension, _super);
  53297. function GLTFMaterialsCommonExtension() {
  53298. return _super.call(this, "KHR_materials_common") || this;
  53299. }
  53300. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53301. if (!gltfRuntime.extensions)
  53302. return false;
  53303. var extension = gltfRuntime.extensions[this.name];
  53304. if (!extension)
  53305. return false;
  53306. // Create lights
  53307. var lights = extension.lights;
  53308. if (lights) {
  53309. for (var thing in lights) {
  53310. var light = lights[thing];
  53311. switch (light.type) {
  53312. case "ambient":
  53313. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  53314. var ambient = light.ambient;
  53315. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  53316. break;
  53317. case "point":
  53318. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  53319. var point = light.point;
  53320. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  53321. break;
  53322. case "directional":
  53323. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  53324. var directional = light.directional;
  53325. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  53326. break;
  53327. case "spot":
  53328. var spot = light.spot;
  53329. 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);
  53330. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  53331. break;
  53332. default:
  53333. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  53334. break;
  53335. }
  53336. }
  53337. }
  53338. return false;
  53339. };
  53340. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53341. var material = gltfRuntime.materials[id];
  53342. if (!material || !material.extensions)
  53343. return false;
  53344. var extension = material.extensions[this.name];
  53345. if (!extension)
  53346. return false;
  53347. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  53348. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  53349. if (extension.technique === "CONSTANT") {
  53350. standardMaterial.disableLighting = true;
  53351. }
  53352. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  53353. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  53354. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  53355. // Ambient
  53356. if (typeof extension.values.ambient === "string") {
  53357. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  53358. }
  53359. else {
  53360. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  53361. }
  53362. // Diffuse
  53363. if (typeof extension.values.diffuse === "string") {
  53364. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  53365. }
  53366. else {
  53367. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  53368. }
  53369. // Emission
  53370. if (typeof extension.values.emission === "string") {
  53371. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  53372. }
  53373. else {
  53374. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  53375. }
  53376. // Specular
  53377. if (typeof extension.values.specular === "string") {
  53378. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  53379. }
  53380. else {
  53381. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  53382. }
  53383. return true;
  53384. };
  53385. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  53386. // Create buffer from texture url
  53387. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  53388. // Create texture from buffer
  53389. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  53390. }, onError);
  53391. };
  53392. return GLTFMaterialsCommonExtension;
  53393. }(GLTF1.GLTFLoaderExtension));
  53394. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  53395. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  53396. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53397. })(BABYLON || (BABYLON = {}));
  53398. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  53399. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53400. var BABYLON;
  53401. (function (BABYLON) {
  53402. var GLTF2;
  53403. (function (GLTF2) {
  53404. /**
  53405. * Enums
  53406. */
  53407. var EComponentType;
  53408. (function (EComponentType) {
  53409. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  53410. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  53411. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  53412. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  53413. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  53414. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  53415. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  53416. var EMeshPrimitiveMode;
  53417. (function (EMeshPrimitiveMode) {
  53418. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  53419. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  53420. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  53421. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  53422. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  53423. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  53424. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  53425. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  53426. var ETextureMagFilter;
  53427. (function (ETextureMagFilter) {
  53428. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  53429. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  53430. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  53431. var ETextureMinFilter;
  53432. (function (ETextureMinFilter) {
  53433. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  53434. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  53435. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  53436. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  53437. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  53438. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  53439. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  53440. var ETextureWrapMode;
  53441. (function (ETextureWrapMode) {
  53442. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  53443. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  53444. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  53445. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  53446. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  53447. })(BABYLON || (BABYLON = {}));
  53448. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  53449. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53450. var BABYLON;
  53451. (function (BABYLON) {
  53452. var GLTF2;
  53453. (function (GLTF2) {
  53454. var GLTFLoader = (function () {
  53455. function GLTFLoader(parent) {
  53456. this._renderReady = false;
  53457. this._disposed = false;
  53458. this._objectURLs = new Array();
  53459. this._blockPendingTracking = false;
  53460. // Observable with boolean indicating success or error.
  53461. this._renderReadyObservable = new BABYLON.Observable();
  53462. // Count of pending work that needs to complete before the asset is rendered.
  53463. this._renderPendingCount = 0;
  53464. // Count of pending work that needs to complete before the loader is cleared.
  53465. this._loaderPendingCount = 0;
  53466. this._parent = parent;
  53467. }
  53468. GLTFLoader.RegisterExtension = function (extension) {
  53469. if (GLTFLoader.Extensions[extension.name]) {
  53470. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  53471. return;
  53472. }
  53473. GLTFLoader.Extensions[extension.name] = extension;
  53474. // Keep the order of registration so that extensions registered first are called first.
  53475. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  53476. };
  53477. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  53478. get: function () {
  53479. return this._gltf;
  53480. },
  53481. enumerable: true,
  53482. configurable: true
  53483. });
  53484. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  53485. get: function () {
  53486. return this._babylonScene;
  53487. },
  53488. enumerable: true,
  53489. configurable: true
  53490. });
  53491. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  53492. if (this._renderReady) {
  53493. func();
  53494. }
  53495. else {
  53496. this._renderReadyObservable.add(func);
  53497. }
  53498. };
  53499. GLTFLoader.prototype.dispose = function () {
  53500. if (this._disposed) {
  53501. return;
  53502. }
  53503. this._disposed = true;
  53504. // Revoke object urls created during load
  53505. this._objectURLs.forEach(function (url) { return URL.revokeObjectURL(url); });
  53506. this._objectURLs.length = 0;
  53507. this._gltf = undefined;
  53508. this._babylonScene = undefined;
  53509. this._rootUrl = undefined;
  53510. this._defaultMaterial = undefined;
  53511. this._successCallback = undefined;
  53512. this._errorCallback = undefined;
  53513. this._renderReady = false;
  53514. this._renderReadyObservable.clear();
  53515. this._renderPendingCount = 0;
  53516. this._loaderPendingCount = 0;
  53517. };
  53518. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53519. var _this = this;
  53520. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  53521. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  53522. }, onProgress, onError);
  53523. };
  53524. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53525. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  53526. };
  53527. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53528. this._loadData(data);
  53529. this._babylonScene = scene;
  53530. this._rootUrl = rootUrl;
  53531. this._successCallback = onSuccess;
  53532. this._progressCallback = onProgress;
  53533. this._errorCallback = onError;
  53534. this.addPendingData(this);
  53535. this._loadScene(nodeNames);
  53536. this._loadAnimations();
  53537. this.removePendingData(this);
  53538. };
  53539. GLTFLoader.prototype._onError = function (message) {
  53540. this._errorCallback(message);
  53541. this.dispose();
  53542. };
  53543. GLTFLoader.prototype._onProgress = function (event) {
  53544. this._progressCallback(event);
  53545. };
  53546. GLTFLoader.prototype._onRenderReady = function () {
  53547. switch (this._parent.coordinateSystemMode) {
  53548. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  53549. if (!this._babylonScene.useRightHandedSystem) {
  53550. this._addRightHandToLeftHandRootTransform();
  53551. }
  53552. break;
  53553. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  53554. // do nothing
  53555. break;
  53556. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  53557. this._babylonScene.useRightHandedSystem = true;
  53558. break;
  53559. default:
  53560. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  53561. break;
  53562. }
  53563. this._showMeshes();
  53564. this._startAnimations();
  53565. this._successCallback();
  53566. this._renderReadyObservable.notifyObservers(this);
  53567. };
  53568. GLTFLoader.prototype._onLoaderComplete = function () {
  53569. if (this._parent.onComplete) {
  53570. this._parent.onComplete();
  53571. }
  53572. };
  53573. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  53574. if (this._parent.onFirstLODComplete) {
  53575. this._parent.onFirstLODComplete();
  53576. }
  53577. };
  53578. GLTFLoader.prototype._loadData = function (data) {
  53579. this._gltf = data.json;
  53580. var binaryBuffer;
  53581. var buffers = this._gltf.buffers;
  53582. if (buffers.length > 0 && buffers[0].uri === undefined) {
  53583. binaryBuffer = buffers[0];
  53584. }
  53585. if (data.bin) {
  53586. if (binaryBuffer) {
  53587. if (binaryBuffer.byteLength != data.bin.byteLength) {
  53588. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  53589. }
  53590. }
  53591. else {
  53592. BABYLON.Tools.Warn("Unexpected BIN chunk");
  53593. }
  53594. binaryBuffer.loadedData = data.bin;
  53595. }
  53596. };
  53597. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  53598. var rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  53599. rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  53600. rootMesh.rotation.y = Math.PI;
  53601. var nodes = this._gltf.nodes;
  53602. for (var i = 0; i < nodes.length; i++) {
  53603. var mesh = nodes[i].babylonMesh;
  53604. if (mesh && !mesh.parent) {
  53605. mesh.parent = rootMesh;
  53606. }
  53607. }
  53608. };
  53609. GLTFLoader.prototype._getMeshes = function () {
  53610. var meshes = [];
  53611. var nodes = this._gltf.nodes;
  53612. if (nodes) {
  53613. nodes.forEach(function (node) {
  53614. if (node.babylonMesh) {
  53615. meshes.push(node.babylonMesh);
  53616. }
  53617. });
  53618. }
  53619. return meshes;
  53620. };
  53621. GLTFLoader.prototype._getSkeletons = function () {
  53622. var skeletons = [];
  53623. var skins = this._gltf.skins;
  53624. if (skins) {
  53625. skins.forEach(function (skin) {
  53626. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  53627. skeletons.push(skin.babylonSkeleton);
  53628. }
  53629. });
  53630. }
  53631. return skeletons;
  53632. };
  53633. GLTFLoader.prototype._getAnimationTargets = function () {
  53634. var targets = [];
  53635. var animations = this._gltf.animations;
  53636. if (animations) {
  53637. animations.forEach(function (animation) {
  53638. targets.push.apply(targets, animation.targets);
  53639. });
  53640. }
  53641. return targets;
  53642. };
  53643. GLTFLoader.prototype._showMeshes = function () {
  53644. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  53645. };
  53646. GLTFLoader.prototype._startAnimations = function () {
  53647. var _this = this;
  53648. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  53649. };
  53650. GLTFLoader.prototype._loadScene = function (nodeNames) {
  53651. var _this = this;
  53652. var scene = this._gltf.scenes[this._gltf.scene || 0];
  53653. var nodeIndices = scene.nodes;
  53654. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  53655. node.index = index;
  53656. node.parent = parentNode;
  53657. return true;
  53658. });
  53659. var materials = this._gltf.materials;
  53660. if (materials) {
  53661. materials.forEach(function (material, index) { return material.index = index; });
  53662. }
  53663. if (nodeNames) {
  53664. if (!(nodeNames instanceof Array)) {
  53665. nodeNames = [nodeNames];
  53666. }
  53667. var filteredNodeIndices = new Array();
  53668. this._traverseNodes(nodeIndices, function (node) {
  53669. if (nodeNames.indexOf(node.name) === -1) {
  53670. return true;
  53671. }
  53672. filteredNodeIndices.push(node.index);
  53673. return false;
  53674. });
  53675. nodeIndices = filteredNodeIndices;
  53676. }
  53677. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  53678. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  53679. };
  53680. GLTFLoader.prototype._loadSkin = function (node) {
  53681. var _this = this;
  53682. if (node.skin !== undefined) {
  53683. var skin = this._gltf.skins[node.skin];
  53684. var skeletonId = "skeleton" + node.skin;
  53685. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  53686. skin.index = node.skin;
  53687. for (var i = 0; i < skin.joints.length; i++) {
  53688. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  53689. }
  53690. if (skin.skeleton === undefined) {
  53691. // TODO: handle when skeleton is not defined
  53692. throw new Error("Not implemented");
  53693. }
  53694. if (skin.inverseBindMatrices === undefined) {
  53695. // TODO: handle when inverse bind matrices are not defined
  53696. throw new Error("Not implemented");
  53697. }
  53698. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  53699. this._loadAccessorAsync(accessor, function (data) {
  53700. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  53701. });
  53702. }
  53703. return true;
  53704. };
  53705. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  53706. var jointIndex = skin.joints.indexOf(node.index);
  53707. if (jointIndex === -1) {
  53708. this._createBone(node, skin);
  53709. }
  53710. var babylonBone = node.babylonSkinToBones[skin.index];
  53711. // TODO: explain the math
  53712. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  53713. matrix.invertToRef(matrix);
  53714. if (parentNode) {
  53715. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  53716. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  53717. }
  53718. babylonBone.updateMatrix(matrix);
  53719. return true;
  53720. };
  53721. GLTFLoader.prototype._createBone = function (node, skin) {
  53722. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  53723. node.babylonSkinToBones = node.babylonSkinToBones || {};
  53724. node.babylonSkinToBones[skin.index] = babylonBone;
  53725. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  53726. node.babylonAnimationTargets.push(babylonBone);
  53727. return babylonBone;
  53728. };
  53729. GLTFLoader.prototype._loadMesh = function (node) {
  53730. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  53731. babylonMesh.isVisible = false;
  53732. this._loadTransform(node, babylonMesh);
  53733. if (node.mesh !== undefined) {
  53734. var mesh = this._gltf.meshes[node.mesh];
  53735. this._loadMeshData(node, mesh, babylonMesh);
  53736. }
  53737. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  53738. node.babylonMesh = babylonMesh;
  53739. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  53740. node.babylonAnimationTargets.push(node.babylonMesh);
  53741. if (node.skin !== undefined) {
  53742. var skin = this._gltf.skins[node.skin];
  53743. babylonMesh.skeleton = skin.babylonSkeleton;
  53744. }
  53745. if (node.camera !== undefined) {
  53746. // TODO: handle cameras
  53747. }
  53748. return true;
  53749. };
  53750. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  53751. var _this = this;
  53752. babylonMesh.name = mesh.name || babylonMesh.name;
  53753. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  53754. babylonMesh.material = babylonMultiMaterial;
  53755. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  53756. var vertexData = new BABYLON.VertexData();
  53757. vertexData.positions = [];
  53758. vertexData.indices = [];
  53759. var subMeshInfos = [];
  53760. var loadedPrimitives = 0;
  53761. var totalPrimitives = mesh.primitives.length;
  53762. var _loop_1 = function (i) {
  53763. var primitive = mesh.primitives[i];
  53764. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  53765. // TODO: handle other primitive modes
  53766. throw new Error("Not implemented");
  53767. }
  53768. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  53769. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  53770. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  53771. subMeshInfos.push({
  53772. materialIndex: i,
  53773. verticesStart: vertexData.positions.length,
  53774. verticesCount: subVertexData.positions.length,
  53775. indicesStart: vertexData.indices.length,
  53776. indicesCount: subVertexData.indices.length,
  53777. loadMaterial: function () {
  53778. if (primitive.material === undefined) {
  53779. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  53780. }
  53781. else {
  53782. var material = _this._gltf.materials[primitive.material];
  53783. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  53784. if (isNew && _this._parent.onMaterialLoaded) {
  53785. _this._parent.onMaterialLoaded(babylonMaterial);
  53786. }
  53787. if (_this._parent.onBeforeMaterialReadyAsync) {
  53788. _this.addLoaderPendingData(material);
  53789. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  53790. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  53791. _this.removeLoaderPendingData(material);
  53792. });
  53793. }
  53794. else {
  53795. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  53796. }
  53797. });
  53798. }
  53799. }
  53800. });
  53801. vertexData.merge(subVertexData);
  53802. if (++loadedPrimitives === totalPrimitives) {
  53803. geometry.setAllVerticesData(vertexData, false);
  53804. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  53805. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  53806. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  53807. babylonMesh.subMeshes = [];
  53808. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  53809. }
  53810. });
  53811. };
  53812. var this_1 = this;
  53813. for (var i = 0; i < totalPrimitives; i++) {
  53814. _loop_1(i);
  53815. }
  53816. };
  53817. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  53818. var _this = this;
  53819. var attributes = primitive.attributes;
  53820. if (!attributes) {
  53821. this._onError("Primitive has no attributes");
  53822. return;
  53823. }
  53824. var vertexData = new BABYLON.VertexData();
  53825. var loadedAttributes = 0;
  53826. var totalAttributes = Object.keys(attributes).length;
  53827. var _loop_2 = function (semantic) {
  53828. accessor = this_2._gltf.accessors[attributes[semantic]];
  53829. this_2._loadAccessorAsync(accessor, function (data) {
  53830. switch (semantic) {
  53831. case "NORMAL":
  53832. vertexData.normals = data;
  53833. break;
  53834. case "POSITION":
  53835. vertexData.positions = data;
  53836. break;
  53837. case "TANGENT":
  53838. vertexData.tangents = data;
  53839. break;
  53840. case "TEXCOORD_0":
  53841. vertexData.uvs = data;
  53842. break;
  53843. case "TEXCOORD_1":
  53844. vertexData.uvs2 = data;
  53845. break;
  53846. case "JOINTS_0":
  53847. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  53848. break;
  53849. case "WEIGHTS_0":
  53850. vertexData.matricesWeights = data;
  53851. break;
  53852. case "COLOR_0":
  53853. vertexData.colors = data;
  53854. break;
  53855. default:
  53856. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  53857. break;
  53858. }
  53859. if (++loadedAttributes === totalAttributes) {
  53860. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  53861. if (indicesAccessor) {
  53862. _this._loadAccessorAsync(indicesAccessor, function (data) {
  53863. vertexData.indices = data;
  53864. onSuccess(vertexData);
  53865. });
  53866. }
  53867. else {
  53868. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  53869. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  53870. onSuccess(vertexData);
  53871. }
  53872. }
  53873. });
  53874. };
  53875. var this_2 = this, accessor;
  53876. for (var semantic in attributes) {
  53877. _loop_2(semantic);
  53878. }
  53879. };
  53880. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  53881. var targets = primitive.targets;
  53882. if (!targets) {
  53883. return;
  53884. }
  53885. if (!babylonMesh.morphTargetManager) {
  53886. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  53887. }
  53888. for (var index = 0; index < targets.length; index++) {
  53889. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  53890. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  53891. }
  53892. };
  53893. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  53894. var targets = primitive.targets;
  53895. if (!targets) {
  53896. return;
  53897. }
  53898. var _loop_3 = function () {
  53899. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  53900. attributes = targets[index];
  53901. var _loop_4 = function (semantic) {
  53902. accessor = this_3._gltf.accessors[attributes[semantic]];
  53903. this_3._loadAccessorAsync(accessor, function (data) {
  53904. if (accessor.name) {
  53905. babylonMorphTarget.name = accessor.name;
  53906. }
  53907. // glTF stores morph target information as deltas while babylon.js expects the final data.
  53908. // As a result we have to add the original data to the delta to calculate the final data.
  53909. var values = data;
  53910. switch (semantic) {
  53911. case "NORMAL":
  53912. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  53913. babylonMorphTarget.setNormals(values);
  53914. break;
  53915. case "POSITION":
  53916. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  53917. babylonMorphTarget.setPositions(values);
  53918. break;
  53919. case "TANGENT":
  53920. // Tangent data for morph targets is stored as xyz delta.
  53921. // The vertexData.tangent is stored as xyzw.
  53922. // So we need to skip every fourth vertexData.tangent.
  53923. for (var i = 0, j = 0; i < values.length; i++, j++) {
  53924. values[i] += vertexData.tangents[j];
  53925. if ((i + 1) % 3 == 0) {
  53926. j++;
  53927. }
  53928. }
  53929. babylonMorphTarget.setTangents(values);
  53930. break;
  53931. default:
  53932. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  53933. break;
  53934. }
  53935. });
  53936. };
  53937. for (var semantic in attributes) {
  53938. _loop_4(semantic);
  53939. }
  53940. };
  53941. var this_3 = this, attributes, accessor;
  53942. for (var index = 0; index < targets.length; index++) {
  53943. _loop_3();
  53944. }
  53945. };
  53946. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  53947. var position = BABYLON.Vector3.Zero();
  53948. var rotation = BABYLON.Quaternion.Identity();
  53949. var scaling = BABYLON.Vector3.One();
  53950. if (node.matrix) {
  53951. var mat = BABYLON.Matrix.FromArray(node.matrix);
  53952. mat.decompose(scaling, rotation, position);
  53953. }
  53954. else {
  53955. if (node.translation)
  53956. position = BABYLON.Vector3.FromArray(node.translation);
  53957. if (node.rotation)
  53958. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  53959. if (node.scale)
  53960. scaling = BABYLON.Vector3.FromArray(node.scale);
  53961. }
  53962. babylonMesh.position = position;
  53963. babylonMesh.rotationQuaternion = rotation;
  53964. babylonMesh.scaling = scaling;
  53965. };
  53966. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  53967. if (parentNode === void 0) { parentNode = null; }
  53968. for (var i = 0; i < indices.length; i++) {
  53969. this._traverseNode(indices[i], action, parentNode);
  53970. }
  53971. };
  53972. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  53973. if (parentNode === void 0) { parentNode = null; }
  53974. var node = this._gltf.nodes[index];
  53975. if (!action(node, index, parentNode)) {
  53976. return;
  53977. }
  53978. if (node.children) {
  53979. for (var i = 0; i < node.children.length; i++) {
  53980. this._traverseNode(node.children[i], action, node);
  53981. }
  53982. }
  53983. };
  53984. GLTFLoader.prototype._loadAnimations = function () {
  53985. var animations = this._gltf.animations;
  53986. if (!animations || animations.length === 0) {
  53987. return;
  53988. }
  53989. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  53990. var animation = animations[animationIndex];
  53991. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  53992. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  53993. }
  53994. }
  53995. };
  53996. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  53997. var channel = animation.channels[channelIndex];
  53998. var samplerIndex = channel.sampler;
  53999. var sampler = animation.samplers[samplerIndex];
  54000. var targetNode = this._gltf.nodes[channel.target.node];
  54001. if (!targetNode) {
  54002. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  54003. return;
  54004. }
  54005. var targetPath = {
  54006. "translation": "position",
  54007. "rotation": "rotationQuaternion",
  54008. "scale": "scaling",
  54009. "weights": "influence"
  54010. }[channel.target.path];
  54011. if (!targetPath) {
  54012. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  54013. return;
  54014. }
  54015. var animationType = {
  54016. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54017. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  54018. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54019. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  54020. }[targetPath];
  54021. var inputData;
  54022. var outputData;
  54023. var checkSuccess = function () {
  54024. if (!inputData || !outputData) {
  54025. return;
  54026. }
  54027. var outputBufferOffset = 0;
  54028. var getNextOutputValue = {
  54029. "position": function () {
  54030. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54031. outputBufferOffset += 3;
  54032. return value;
  54033. },
  54034. "rotationQuaternion": function () {
  54035. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  54036. outputBufferOffset += 4;
  54037. return value;
  54038. },
  54039. "scaling": function () {
  54040. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54041. outputBufferOffset += 3;
  54042. return value;
  54043. },
  54044. "influence": function () {
  54045. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  54046. var value = new Array(numTargets);
  54047. for (var i = 0; i < numTargets; i++) {
  54048. value[i] = outputData[outputBufferOffset++];
  54049. }
  54050. return value;
  54051. },
  54052. }[targetPath];
  54053. var getNextKey = {
  54054. "LINEAR": function (frameIndex) { return ({
  54055. frame: inputData[frameIndex],
  54056. value: getNextOutputValue()
  54057. }); },
  54058. "CUBICSPLINE": function (frameIndex) { return ({
  54059. frame: inputData[frameIndex],
  54060. inTangent: getNextOutputValue(),
  54061. value: getNextOutputValue(),
  54062. outTangent: getNextOutputValue()
  54063. }); },
  54064. }[sampler.interpolation];
  54065. var keys = new Array(inputData.length);
  54066. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  54067. keys[frameIndex] = getNextKey(frameIndex);
  54068. }
  54069. animation.targets = animation.targets || [];
  54070. if (targetPath === "influence") {
  54071. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  54072. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  54073. var morphTarget = morphTargetManager.getTarget(targetIndex);
  54074. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  54075. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54076. babylonAnimation.setKeys(keys.map(function (key) { return ({
  54077. frame: key.frame,
  54078. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  54079. value: key.value[targetIndex],
  54080. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  54081. }); }));
  54082. morphTarget.animations.push(babylonAnimation);
  54083. animation.targets.push(morphTarget);
  54084. }
  54085. }
  54086. else {
  54087. var animationName = animation.name || "anim" + animationIndex;
  54088. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54089. babylonAnimation.setKeys(keys);
  54090. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  54091. var target = targetNode.babylonAnimationTargets[i];
  54092. target.animations.push(babylonAnimation.clone());
  54093. animation.targets.push(target);
  54094. }
  54095. }
  54096. };
  54097. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  54098. inputData = data;
  54099. checkSuccess();
  54100. });
  54101. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  54102. outputData = data;
  54103. checkSuccess();
  54104. });
  54105. };
  54106. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  54107. var _this = this;
  54108. var buffer = this._gltf.buffers[index];
  54109. this.addPendingData(buffer);
  54110. if (buffer.loadedData) {
  54111. setTimeout(function () {
  54112. onSuccess(buffer.loadedData);
  54113. _this.removePendingData(buffer);
  54114. });
  54115. }
  54116. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  54117. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  54118. buffer.loadedData = new Uint8Array(data);
  54119. setTimeout(function () {
  54120. onSuccess(buffer.loadedData);
  54121. _this.removePendingData(buffer);
  54122. });
  54123. }
  54124. else if (buffer.loadedObservable) {
  54125. buffer.loadedObservable.add(function (buffer) {
  54126. onSuccess(buffer.loadedData);
  54127. _this.removePendingData(buffer);
  54128. });
  54129. }
  54130. else {
  54131. buffer.loadedObservable = new BABYLON.Observable();
  54132. buffer.loadedObservable.add(function (buffer) {
  54133. onSuccess(buffer.loadedData);
  54134. _this.removePendingData(buffer);
  54135. });
  54136. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  54137. buffer.loadedData = new Uint8Array(data);
  54138. buffer.loadedObservable.notifyObservers(buffer);
  54139. buffer.loadedObservable = null;
  54140. }, function (event) {
  54141. if (!_this._disposed) {
  54142. _this._onProgress(event);
  54143. }
  54144. }, this._babylonScene.database, true, function (request) {
  54145. if (!_this._disposed) {
  54146. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  54147. _this.removePendingData(buffer);
  54148. }
  54149. });
  54150. }
  54151. };
  54152. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, componentType, onSuccess) {
  54153. var _this = this;
  54154. byteOffset += (bufferView.byteOffset || 0);
  54155. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  54156. if (byteOffset + byteLength > bufferData.byteLength) {
  54157. _this._onError("Buffer access is out of range");
  54158. return;
  54159. }
  54160. var buffer = bufferData.buffer;
  54161. byteOffset += bufferData.byteOffset;
  54162. var bufferViewData;
  54163. switch (componentType) {
  54164. case GLTF2.EComponentType.BYTE:
  54165. bufferViewData = new Int8Array(buffer, byteOffset, byteLength);
  54166. break;
  54167. case GLTF2.EComponentType.UNSIGNED_BYTE:
  54168. bufferViewData = new Uint8Array(buffer, byteOffset, byteLength);
  54169. break;
  54170. case GLTF2.EComponentType.SHORT:
  54171. bufferViewData = new Int16Array(buffer, byteOffset, byteLength);
  54172. break;
  54173. case GLTF2.EComponentType.UNSIGNED_SHORT:
  54174. bufferViewData = new Uint16Array(buffer, byteOffset, byteLength);
  54175. break;
  54176. case GLTF2.EComponentType.UNSIGNED_INT:
  54177. bufferViewData = new Uint32Array(buffer, byteOffset, byteLength);
  54178. break;
  54179. case GLTF2.EComponentType.FLOAT:
  54180. bufferViewData = new Float32Array(buffer, byteOffset, byteLength);
  54181. break;
  54182. default:
  54183. _this._onError("Invalid component type (" + componentType + ")");
  54184. return;
  54185. }
  54186. onSuccess(bufferViewData);
  54187. });
  54188. };
  54189. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  54190. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  54191. var byteOffset = accessor.byteOffset || 0;
  54192. var byteLength = accessor.count * this._getByteStrideFromType(accessor);
  54193. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, accessor.componentType, onSuccess);
  54194. };
  54195. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  54196. switch (accessor.type) {
  54197. case "SCALAR": return 1;
  54198. case "VEC2": return 2;
  54199. case "VEC3": return 3;
  54200. case "VEC4": return 4;
  54201. case "MAT2": return 4;
  54202. case "MAT3": return 9;
  54203. case "MAT4": return 16;
  54204. default:
  54205. this._onError("Invalid accessor type (" + accessor.type + ")");
  54206. return 0;
  54207. }
  54208. };
  54209. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  54210. set: function (value) {
  54211. this._blockPendingTracking = value;
  54212. },
  54213. enumerable: true,
  54214. configurable: true
  54215. });
  54216. GLTFLoader.prototype.addPendingData = function (data) {
  54217. if (!this._renderReady) {
  54218. this._renderPendingCount++;
  54219. }
  54220. this.addLoaderPendingData(data);
  54221. };
  54222. GLTFLoader.prototype.removePendingData = function (data) {
  54223. if (!this._renderReady) {
  54224. if (--this._renderPendingCount === 0) {
  54225. this._renderReady = true;
  54226. this._onRenderReady();
  54227. }
  54228. }
  54229. this.removeLoaderPendingData(data);
  54230. };
  54231. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  54232. if (!this._nonBlockingData) {
  54233. this._nonBlockingData = new Array();
  54234. }
  54235. this._nonBlockingData.push(data);
  54236. };
  54237. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  54238. if (this._blockPendingTracking) {
  54239. this.addLoaderNonBlockingPendingData(data);
  54240. return;
  54241. }
  54242. this._loaderPendingCount++;
  54243. };
  54244. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  54245. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  54246. if (indexInPending !== -1) {
  54247. this._nonBlockingData.splice(indexInPending, 1);
  54248. }
  54249. else if (--this._loaderPendingCount === 0) {
  54250. this._onLoaderFirstLODComplete();
  54251. }
  54252. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  54253. this._onLoaderComplete();
  54254. this.dispose();
  54255. }
  54256. };
  54257. GLTFLoader.prototype._getDefaultMaterial = function () {
  54258. if (!this._defaultMaterial) {
  54259. var id = "__gltf_default";
  54260. var material = this._babylonScene.getMaterialByName(id);
  54261. if (!material) {
  54262. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  54263. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54264. material.metallic = 1;
  54265. material.roughness = 1;
  54266. }
  54267. this._defaultMaterial = material;
  54268. }
  54269. return this._defaultMaterial;
  54270. };
  54271. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  54272. var babylonMaterial = material.babylonMaterial;
  54273. // Ensure metallic workflow
  54274. babylonMaterial.metallic = 1;
  54275. babylonMaterial.roughness = 1;
  54276. var properties = material.pbrMetallicRoughness;
  54277. if (!properties) {
  54278. return;
  54279. }
  54280. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  54281. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  54282. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  54283. if (properties.baseColorTexture) {
  54284. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  54285. }
  54286. if (properties.metallicRoughnessTexture) {
  54287. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  54288. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  54289. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  54290. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  54291. }
  54292. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  54293. };
  54294. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  54295. if (material.babylonMaterial) {
  54296. assign(material.babylonMaterial, false);
  54297. return;
  54298. }
  54299. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  54300. return;
  54301. }
  54302. this.createPbrMaterial(material);
  54303. this.loadMaterialBaseProperties(material);
  54304. this._loadMaterialMetallicRoughnessProperties(material);
  54305. assign(material.babylonMaterial, true);
  54306. };
  54307. GLTFLoader.prototype.createPbrMaterial = function (material) {
  54308. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  54309. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54310. material.babylonMaterial = babylonMaterial;
  54311. };
  54312. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  54313. var babylonMaterial = material.babylonMaterial;
  54314. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  54315. if (material.doubleSided) {
  54316. babylonMaterial.backFaceCulling = false;
  54317. babylonMaterial.twoSidedLighting = true;
  54318. }
  54319. if (material.normalTexture) {
  54320. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  54321. babylonMaterial.invertNormalMapX = true;
  54322. babylonMaterial.invertNormalMapY = true;
  54323. if (material.normalTexture.scale !== undefined) {
  54324. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  54325. }
  54326. }
  54327. if (material.occlusionTexture) {
  54328. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  54329. babylonMaterial.useAmbientInGrayScale = true;
  54330. if (material.occlusionTexture.strength !== undefined) {
  54331. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  54332. }
  54333. }
  54334. if (material.emissiveTexture) {
  54335. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  54336. }
  54337. };
  54338. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  54339. var babylonMaterial = material.babylonMaterial;
  54340. var alphaMode = material.alphaMode || "OPAQUE";
  54341. switch (alphaMode) {
  54342. case "OPAQUE":
  54343. // default is opaque
  54344. break;
  54345. case "MASK":
  54346. case "BLEND":
  54347. if (colorFactor) {
  54348. babylonMaterial.alpha = colorFactor[3];
  54349. }
  54350. if (babylonMaterial.albedoTexture) {
  54351. babylonMaterial.albedoTexture.hasAlpha = true;
  54352. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  54353. }
  54354. break;
  54355. default:
  54356. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  54357. break;
  54358. }
  54359. };
  54360. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  54361. var _this = this;
  54362. var texture = this._gltf.textures[textureInfo.index];
  54363. var texCoord = textureInfo.texCoord || 0;
  54364. if (!texture || texture.source === undefined) {
  54365. return null;
  54366. }
  54367. // check the cache first
  54368. var babylonTexture;
  54369. if (texture.babylonTextures) {
  54370. babylonTexture = texture.babylonTextures[texCoord];
  54371. if (!babylonTexture) {
  54372. for (var i = 0; i < texture.babylonTextures.length; i++) {
  54373. babylonTexture = texture.babylonTextures[i];
  54374. if (babylonTexture) {
  54375. babylonTexture = babylonTexture.clone();
  54376. babylonTexture.coordinatesIndex = texCoord;
  54377. break;
  54378. }
  54379. }
  54380. }
  54381. return babylonTexture;
  54382. }
  54383. var source = this._gltf.images[texture.source];
  54384. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  54385. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  54386. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  54387. this.addPendingData(texture);
  54388. babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  54389. if (!_this._disposed) {
  54390. _this.removePendingData(texture);
  54391. }
  54392. }, function () {
  54393. if (!_this._disposed) {
  54394. _this._onError("Failed to load texture '" + source.uri + "'");
  54395. _this.removePendingData(texture);
  54396. }
  54397. });
  54398. var setTextureData = function (data) {
  54399. var url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  54400. _this._objectURLs.push(url);
  54401. babylonTexture.updateURL(url);
  54402. };
  54403. if (!source.uri) {
  54404. var bufferView = this._gltf.bufferViews[source.bufferView];
  54405. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  54406. }
  54407. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  54408. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  54409. }
  54410. else {
  54411. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  54412. if (!_this._disposed) {
  54413. _this._onProgress(event);
  54414. }
  54415. }, this._babylonScene.database, true, function (request) {
  54416. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  54417. });
  54418. }
  54419. babylonTexture.coordinatesIndex = texCoord;
  54420. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  54421. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  54422. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  54423. // Cache the texture
  54424. texture.babylonTextures = texture.babylonTextures || [];
  54425. texture.babylonTextures[texCoord] = babylonTexture;
  54426. if (this._parent.onTextureLoaded) {
  54427. this._parent.onTextureLoaded(babylonTexture);
  54428. }
  54429. return babylonTexture;
  54430. };
  54431. GLTFLoader.Extensions = {};
  54432. return GLTFLoader;
  54433. }());
  54434. GLTF2.GLTFLoader = GLTFLoader;
  54435. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  54436. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54437. })(BABYLON || (BABYLON = {}));
  54438. //# sourceMappingURL=babylon.glTFLoader.js.map
  54439. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  54440. var BABYLON;
  54441. (function (BABYLON) {
  54442. var GLTF2;
  54443. (function (GLTF2) {
  54444. /**
  54445. * Utils functions for GLTF
  54446. */
  54447. var GLTFUtils = (function () {
  54448. function GLTFUtils() {
  54449. }
  54450. /**
  54451. * If the uri is a base64 string
  54452. * @param uri: the uri to test
  54453. */
  54454. GLTFUtils.IsBase64 = function (uri) {
  54455. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  54456. };
  54457. /**
  54458. * Decode the base64 uri
  54459. * @param uri: the uri to decode
  54460. */
  54461. GLTFUtils.DecodeBase64 = function (uri) {
  54462. var decodedString = atob(uri.split(",")[1]);
  54463. var bufferLength = decodedString.length;
  54464. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  54465. for (var i = 0; i < bufferLength; i++) {
  54466. bufferView[i] = decodedString.charCodeAt(i);
  54467. }
  54468. return bufferView.buffer;
  54469. };
  54470. GLTFUtils.ForEach = function (view, func) {
  54471. for (var index = 0; index < view.length; index++) {
  54472. func(view[index], index);
  54473. }
  54474. };
  54475. GLTFUtils.GetTextureWrapMode = function (mode) {
  54476. // Set defaults if undefined
  54477. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  54478. switch (mode) {
  54479. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: BABYLON.Texture.CLAMP_ADDRESSMODE;
  54480. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  54481. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  54482. default:
  54483. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  54484. return BABYLON.Texture.WRAP_ADDRESSMODE;
  54485. }
  54486. };
  54487. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  54488. // Set defaults if undefined
  54489. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  54490. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST : minFilter;
  54491. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  54492. switch (minFilter) {
  54493. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  54494. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  54495. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  54496. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  54497. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  54498. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  54499. default:
  54500. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  54501. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  54502. }
  54503. }
  54504. else {
  54505. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  54506. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  54507. }
  54508. switch (minFilter) {
  54509. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  54510. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  54511. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  54512. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  54513. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  54514. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  54515. default:
  54516. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  54517. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  54518. }
  54519. }
  54520. };
  54521. /**
  54522. * Decodes a buffer view into a string
  54523. * @param view: the buffer view
  54524. */
  54525. GLTFUtils.DecodeBufferToText = function (view) {
  54526. var result = "";
  54527. var length = view.byteLength;
  54528. for (var i = 0; i < length; ++i) {
  54529. result += String.fromCharCode(view[i]);
  54530. }
  54531. return result;
  54532. };
  54533. return GLTFUtils;
  54534. }());
  54535. GLTF2.GLTFUtils = GLTFUtils;
  54536. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54537. })(BABYLON || (BABYLON = {}));
  54538. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  54539. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  54540. var BABYLON;
  54541. (function (BABYLON) {
  54542. var GLTF2;
  54543. (function (GLTF2) {
  54544. var GLTFLoaderExtension = (function () {
  54545. function GLTFLoaderExtension() {
  54546. this.enabled = true;
  54547. }
  54548. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  54549. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  54550. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  54551. };
  54552. GLTFLoaderExtension._ApplyExtensions = function (action) {
  54553. var extensions = GLTFLoaderExtension._Extensions;
  54554. if (!extensions) {
  54555. return;
  54556. }
  54557. for (var i = 0; i < extensions.length; i++) {
  54558. var extension = extensions[i];
  54559. if (extension.enabled && action(extension)) {
  54560. return true;
  54561. }
  54562. }
  54563. return false;
  54564. };
  54565. //
  54566. // Utilities
  54567. //
  54568. GLTFLoaderExtension._Extensions = [];
  54569. return GLTFLoaderExtension;
  54570. }());
  54571. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  54572. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54573. })(BABYLON || (BABYLON = {}));
  54574. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  54575. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  54576. var BABYLON;
  54577. (function (BABYLON) {
  54578. var GLTF2;
  54579. (function (GLTF2) {
  54580. var Extensions;
  54581. (function (Extensions) {
  54582. var MSFTLOD = (function (_super) {
  54583. __extends(MSFTLOD, _super);
  54584. function MSFTLOD() {
  54585. return _super !== null && _super.apply(this, arguments) || this;
  54586. }
  54587. Object.defineProperty(MSFTLOD.prototype, "name", {
  54588. get: function () {
  54589. return "MSFT_lod";
  54590. },
  54591. enumerable: true,
  54592. configurable: true
  54593. });
  54594. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  54595. if (!material.extensions) {
  54596. return false;
  54597. }
  54598. var properties = material.extensions[this.name];
  54599. if (!properties) {
  54600. return false;
  54601. }
  54602. // Clear out the extension so that it won't get loaded again.
  54603. material.extensions[this.name] = undefined;
  54604. // Tell the loader not to clear its state until the highest LOD is loaded.
  54605. var materialLODs = [material.index].concat(properties.ids);
  54606. loader.addLoaderPendingData(material);
  54607. for (var index = 0; index < materialLODs.length; index++) {
  54608. loader.addLoaderNonBlockingPendingData(index);
  54609. }
  54610. // Start with the lowest quality LOD.
  54611. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  54612. return true;
  54613. };
  54614. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  54615. var _this = this;
  54616. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  54617. if (lod !== materialLODs.length - 1) {
  54618. loader.blockPendingTracking = true;
  54619. }
  54620. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  54621. assign(babylonMaterial, isNew);
  54622. loader.removeLoaderPendingData(lod);
  54623. // Loading is considered complete if this is the lowest quality LOD.
  54624. if (lod === materialLODs.length - 1) {
  54625. loader.removeLoaderPendingData(material);
  54626. }
  54627. if (lod === 0) {
  54628. loader.blockPendingTracking = false;
  54629. return;
  54630. }
  54631. // Load the next LOD when the loader is ready to render and
  54632. // all active material textures of the current LOD are loaded.
  54633. loader.executeWhenRenderReady(function () {
  54634. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  54635. setTimeout(function () {
  54636. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  54637. }, MSFTLOD.MinimalLODDelay);
  54638. });
  54639. });
  54640. });
  54641. };
  54642. /**
  54643. * Specify the minimal delay between LODs in ms (default = 250)
  54644. */
  54645. MSFTLOD.MinimalLODDelay = 250;
  54646. return MSFTLOD;
  54647. }(GLTF2.GLTFLoaderExtension));
  54648. Extensions.MSFTLOD = MSFTLOD;
  54649. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  54650. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  54651. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54652. })(BABYLON || (BABYLON = {}));
  54653. //# sourceMappingURL=MSFT_lod.js.map
  54654. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  54655. var BABYLON;
  54656. (function (BABYLON) {
  54657. var GLTF2;
  54658. (function (GLTF2) {
  54659. var Extensions;
  54660. (function (Extensions) {
  54661. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  54662. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  54663. function KHRMaterialsPbrSpecularGlossiness() {
  54664. return _super !== null && _super.apply(this, arguments) || this;
  54665. }
  54666. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  54667. get: function () {
  54668. return "KHR_materials_pbrSpecularGlossiness";
  54669. },
  54670. enumerable: true,
  54671. configurable: true
  54672. });
  54673. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  54674. if (!material.extensions) {
  54675. return false;
  54676. }
  54677. var properties = material.extensions[this.name];
  54678. if (!properties) {
  54679. return false;
  54680. }
  54681. loader.createPbrMaterial(material);
  54682. loader.loadMaterialBaseProperties(material);
  54683. this._loadSpecularGlossinessProperties(loader, material, properties);
  54684. assign(material.babylonMaterial, true);
  54685. return true;
  54686. };
  54687. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  54688. var babylonMaterial = material.babylonMaterial;
  54689. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  54690. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  54691. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  54692. if (properties.diffuseTexture) {
  54693. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  54694. loader.loadMaterialAlphaProperties(material);
  54695. }
  54696. if (properties.specularGlossinessTexture) {
  54697. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  54698. babylonMaterial.reflectivityTexture.hasAlpha = true;
  54699. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  54700. }
  54701. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  54702. };
  54703. return KHRMaterialsPbrSpecularGlossiness;
  54704. }(GLTF2.GLTFLoaderExtension));
  54705. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  54706. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  54707. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  54708. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54709. })(BABYLON || (BABYLON = {}));
  54710. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  54711. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54712. module.exports = BABYLON;
  54713. };