babylon.max.js 3.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var KeyboardEventTypes = (function () {
  20. function KeyboardEventTypes() {
  21. }
  22. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  23. get: function () {
  24. return KeyboardEventTypes._KEYDOWN;
  25. },
  26. enumerable: true,
  27. configurable: true
  28. });
  29. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  30. get: function () {
  31. return KeyboardEventTypes._KEYUP;
  32. },
  33. enumerable: true,
  34. configurable: true
  35. });
  36. KeyboardEventTypes._KEYDOWN = 0x01;
  37. KeyboardEventTypes._KEYUP = 0x02;
  38. return KeyboardEventTypes;
  39. }());
  40. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  41. var KeyboardInfo = (function () {
  42. function KeyboardInfo(type, event) {
  43. this.type = type;
  44. this.event = event;
  45. }
  46. return KeyboardInfo;
  47. }());
  48. BABYLON.KeyboardInfo = KeyboardInfo;
  49. /**
  50. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  51. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  52. */
  53. var KeyboardInfoPre = (function (_super) {
  54. __extends(KeyboardInfoPre, _super);
  55. function KeyboardInfoPre(type, event) {
  56. var _this = _super.call(this, type, event) || this;
  57. _this.skipOnPointerObservable = false;
  58. return _this;
  59. }
  60. return KeyboardInfoPre;
  61. }(KeyboardInfo));
  62. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  63. })(BABYLON || (BABYLON = {}));
  64. //# sourceMappingURL=babylon.keyboardEvents.js.map
  65. var BABYLON;
  66. (function (BABYLON) {
  67. var PointerEventTypes = (function () {
  68. function PointerEventTypes() {
  69. }
  70. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  71. get: function () {
  72. return PointerEventTypes._POINTERDOWN;
  73. },
  74. enumerable: true,
  75. configurable: true
  76. });
  77. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  78. get: function () {
  79. return PointerEventTypes._POINTERUP;
  80. },
  81. enumerable: true,
  82. configurable: true
  83. });
  84. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  85. get: function () {
  86. return PointerEventTypes._POINTERMOVE;
  87. },
  88. enumerable: true,
  89. configurable: true
  90. });
  91. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  92. get: function () {
  93. return PointerEventTypes._POINTERWHEEL;
  94. },
  95. enumerable: true,
  96. configurable: true
  97. });
  98. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  99. get: function () {
  100. return PointerEventTypes._POINTERPICK;
  101. },
  102. enumerable: true,
  103. configurable: true
  104. });
  105. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  106. get: function () {
  107. return PointerEventTypes._POINTERTAP;
  108. },
  109. enumerable: true,
  110. configurable: true
  111. });
  112. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  113. get: function () {
  114. return PointerEventTypes._POINTERDOUBLETAP;
  115. },
  116. enumerable: true,
  117. configurable: true
  118. });
  119. PointerEventTypes._POINTERDOWN = 0x01;
  120. PointerEventTypes._POINTERUP = 0x02;
  121. PointerEventTypes._POINTERMOVE = 0x04;
  122. PointerEventTypes._POINTERWHEEL = 0x08;
  123. PointerEventTypes._POINTERPICK = 0x10;
  124. PointerEventTypes._POINTERTAP = 0x20;
  125. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  126. return PointerEventTypes;
  127. }());
  128. BABYLON.PointerEventTypes = PointerEventTypes;
  129. var PointerInfoBase = (function () {
  130. function PointerInfoBase(type, event) {
  131. this.type = type;
  132. this.event = event;
  133. }
  134. return PointerInfoBase;
  135. }());
  136. BABYLON.PointerInfoBase = PointerInfoBase;
  137. /**
  138. * This class is used to store pointer related info for the onPrePointerObservable event.
  139. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  140. */
  141. var PointerInfoPre = (function (_super) {
  142. __extends(PointerInfoPre, _super);
  143. function PointerInfoPre(type, event, localX, localY) {
  144. var _this = _super.call(this, type, event) || this;
  145. _this.skipOnPointerObservable = false;
  146. _this.localPosition = new BABYLON.Vector2(localX, localY);
  147. return _this;
  148. }
  149. return PointerInfoPre;
  150. }(PointerInfoBase));
  151. BABYLON.PointerInfoPre = PointerInfoPre;
  152. /**
  153. * This type contains all the data related to a pointer event in Babylon.js.
  154. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  155. */
  156. var PointerInfo = (function (_super) {
  157. __extends(PointerInfo, _super);
  158. function PointerInfo(type, event, pickInfo) {
  159. var _this = _super.call(this, type, event) || this;
  160. _this.pickInfo = pickInfo;
  161. return _this;
  162. }
  163. return PointerInfo;
  164. }(PointerInfoBase));
  165. BABYLON.PointerInfo = PointerInfo;
  166. })(BABYLON || (BABYLON = {}));
  167. //# sourceMappingURL=babylon.pointerEvents.js.map
  168. var BABYLON;
  169. (function (BABYLON) {
  170. BABYLON.ToGammaSpace = 1 / 2.2;
  171. BABYLON.ToLinearSpace = 2.2;
  172. BABYLON.Epsilon = 0.001;
  173. var Color3 = (function () {
  174. /**
  175. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  176. */
  177. function Color3(r, g, b) {
  178. if (r === void 0) { r = 0; }
  179. if (g === void 0) { g = 0; }
  180. if (b === void 0) { b = 0; }
  181. this.r = r;
  182. this.g = g;
  183. this.b = b;
  184. }
  185. /**
  186. * Returns a string with the Color3 current values.
  187. */
  188. Color3.prototype.toString = function () {
  189. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  190. };
  191. /**
  192. * Returns the string "Color3".
  193. */
  194. Color3.prototype.getClassName = function () {
  195. return "Color3";
  196. };
  197. /**
  198. * Returns the Color3 hash code.
  199. */
  200. Color3.prototype.getHashCode = function () {
  201. var hash = this.r || 0;
  202. hash = (hash * 397) ^ (this.g || 0);
  203. hash = (hash * 397) ^ (this.b || 0);
  204. return hash;
  205. };
  206. // Operators
  207. /**
  208. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  209. * Returns the Color3.
  210. */
  211. Color3.prototype.toArray = function (array, index) {
  212. if (index === undefined) {
  213. index = 0;
  214. }
  215. array[index] = this.r;
  216. array[index + 1] = this.g;
  217. array[index + 2] = this.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color4 object from the current Color3 and the passed alpha.
  222. */
  223. Color3.prototype.toColor4 = function (alpha) {
  224. if (alpha === void 0) { alpha = 1; }
  225. return new Color4(this.r, this.g, this.b, alpha);
  226. };
  227. /**
  228. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  229. */
  230. Color3.prototype.asArray = function () {
  231. var result = [];
  232. this.toArray(result, 0);
  233. return result;
  234. };
  235. /**
  236. * Returns the luminance value (float).
  237. */
  238. Color3.prototype.toLuminance = function () {
  239. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  240. };
  241. /**
  242. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  243. * Returns this new object.
  244. */
  245. Color3.prototype.multiply = function (otherColor) {
  246. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  247. };
  248. /**
  249. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  250. * Returns the current Color3.
  251. */
  252. Color3.prototype.multiplyToRef = function (otherColor, result) {
  253. result.r = this.r * otherColor.r;
  254. result.g = this.g * otherColor.g;
  255. result.b = this.b * otherColor.b;
  256. return this;
  257. };
  258. /**
  259. * Boolean : True if the rgb values are equal to the passed ones.
  260. */
  261. Color3.prototype.equals = function (otherColor) {
  262. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  263. };
  264. /**
  265. * Boolean : True if the rgb values are equal to the passed ones.
  266. */
  267. Color3.prototype.equalsFloats = function (r, g, b) {
  268. return this.r === r && this.g === g && this.b === b;
  269. };
  270. /**
  271. * Multiplies in place each rgb value by scale.
  272. * Returns the updated Color3.
  273. */
  274. Color3.prototype.scale = function (scale) {
  275. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  276. };
  277. /**
  278. * Multiplies the rgb values by scale and stores the result into "result".
  279. * Returns the unmodified current Color3.
  280. */
  281. Color3.prototype.scaleToRef = function (scale, result) {
  282. result.r = this.r * scale;
  283. result.g = this.g * scale;
  284. result.b = this.b * scale;
  285. return this;
  286. };
  287. /**
  288. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  289. */
  290. Color3.prototype.add = function (otherColor) {
  291. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  292. };
  293. /**
  294. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  295. * Returns the unmodified current Color3.
  296. */
  297. Color3.prototype.addToRef = function (otherColor, result) {
  298. result.r = this.r + otherColor.r;
  299. result.g = this.g + otherColor.g;
  300. result.b = this.b + otherColor.b;
  301. return this;
  302. };
  303. /**
  304. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  305. */
  306. Color3.prototype.subtract = function (otherColor) {
  307. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  308. };
  309. /**
  310. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  311. * Returns the unmodified current Color3.
  312. */
  313. Color3.prototype.subtractToRef = function (otherColor, result) {
  314. result.r = this.r - otherColor.r;
  315. result.g = this.g - otherColor.g;
  316. result.b = this.b - otherColor.b;
  317. return this;
  318. };
  319. /**
  320. * Returns a new Color3 copied the current one.
  321. */
  322. Color3.prototype.clone = function () {
  323. return new Color3(this.r, this.g, this.b);
  324. };
  325. /**
  326. * Copies the rgb values from the source in the current Color3.
  327. * Returns the updated Color3.
  328. */
  329. Color3.prototype.copyFrom = function (source) {
  330. this.r = source.r;
  331. this.g = source.g;
  332. this.b = source.b;
  333. return this;
  334. };
  335. /**
  336. * Updates the Color3 rgb values from the passed floats.
  337. * Returns the Color3.
  338. */
  339. Color3.prototype.copyFromFloats = function (r, g, b) {
  340. this.r = r;
  341. this.g = g;
  342. this.b = b;
  343. return this;
  344. };
  345. /**
  346. * Updates the Color3 rgb values from the passed floats.
  347. * Returns the Color3.
  348. */
  349. Color3.prototype.set = function (r, g, b) {
  350. return this.copyFromFloats(r, g, b);
  351. };
  352. /**
  353. * Returns the Color3 hexadecimal code as a string.
  354. */
  355. Color3.prototype.toHexString = function () {
  356. var intR = (this.r * 255) | 0;
  357. var intG = (this.g * 255) | 0;
  358. var intB = (this.b * 255) | 0;
  359. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  360. };
  361. /**
  362. * Returns a new Color3 converted to linear space.
  363. */
  364. Color3.prototype.toLinearSpace = function () {
  365. var convertedColor = new Color3();
  366. this.toLinearSpaceToRef(convertedColor);
  367. return convertedColor;
  368. };
  369. /**
  370. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  371. * Returns the unmodified Color3.
  372. */
  373. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  374. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  375. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  376. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  377. return this;
  378. };
  379. /**
  380. * Returns a new Color3 converted to gamma space.
  381. */
  382. Color3.prototype.toGammaSpace = function () {
  383. var convertedColor = new Color3();
  384. this.toGammaSpaceToRef(convertedColor);
  385. return convertedColor;
  386. };
  387. /**
  388. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  389. * Returns the unmodified Color3.
  390. */
  391. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  392. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  393. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  394. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  395. return this;
  396. };
  397. // Statics
  398. /**
  399. * Creates a new Color3 from the string containing valid hexadecimal values.
  400. */
  401. Color3.FromHexString = function (hex) {
  402. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  403. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  404. return new Color3(0, 0, 0);
  405. }
  406. var r = parseInt(hex.substring(1, 3), 16);
  407. var g = parseInt(hex.substring(3, 5), 16);
  408. var b = parseInt(hex.substring(5, 7), 16);
  409. return Color3.FromInts(r, g, b);
  410. };
  411. /**
  412. * Creates a new Vector3 from the startind index of the passed array.
  413. */
  414. Color3.FromArray = function (array, offset) {
  415. if (offset === void 0) { offset = 0; }
  416. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  417. };
  418. /**
  419. * Creates a new Color3 from integer values ( < 256).
  420. */
  421. Color3.FromInts = function (r, g, b) {
  422. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  423. };
  424. /**
  425. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  426. */
  427. Color3.Lerp = function (start, end, amount) {
  428. var r = start.r + ((end.r - start.r) * amount);
  429. var g = start.g + ((end.g - start.g) * amount);
  430. var b = start.b + ((end.b - start.b) * amount);
  431. return new Color3(r, g, b);
  432. };
  433. Color3.Red = function () { return new Color3(1, 0, 0); };
  434. Color3.Green = function () { return new Color3(0, 1, 0); };
  435. Color3.Blue = function () { return new Color3(0, 0, 1); };
  436. Color3.Black = function () { return new Color3(0, 0, 0); };
  437. Color3.White = function () { return new Color3(1, 1, 1); };
  438. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  439. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  440. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  441. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  442. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  443. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  444. return Color3;
  445. }());
  446. BABYLON.Color3 = Color3;
  447. var Color4 = (function () {
  448. /**
  449. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  450. */
  451. function Color4(r, g, b, a) {
  452. if (r === void 0) { r = 0; }
  453. if (g === void 0) { g = 0; }
  454. if (b === void 0) { b = 0; }
  455. if (a === void 0) { a = 1; }
  456. this.r = r;
  457. this.g = g;
  458. this.b = b;
  459. this.a = a;
  460. }
  461. // Operators
  462. /**
  463. * Adds in place the passed Color4 values to the current Color4.
  464. * Returns the updated Color4.
  465. */
  466. Color4.prototype.addInPlace = function (right) {
  467. this.r += right.r;
  468. this.g += right.g;
  469. this.b += right.b;
  470. this.a += right.a;
  471. return this;
  472. };
  473. /**
  474. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  475. */
  476. Color4.prototype.asArray = function () {
  477. var result = [];
  478. this.toArray(result, 0);
  479. return result;
  480. };
  481. /**
  482. * Stores from the starting index in the passed array the Color4 successive values.
  483. * Returns the Color4.
  484. */
  485. Color4.prototype.toArray = function (array, index) {
  486. if (index === undefined) {
  487. index = 0;
  488. }
  489. array[index] = this.r;
  490. array[index + 1] = this.g;
  491. array[index + 2] = this.b;
  492. array[index + 3] = this.a;
  493. return this;
  494. };
  495. /**
  496. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  497. */
  498. Color4.prototype.add = function (right) {
  499. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  500. };
  501. /**
  502. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  503. */
  504. Color4.prototype.subtract = function (right) {
  505. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  506. };
  507. /**
  508. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  509. * Returns the Color4.
  510. */
  511. Color4.prototype.subtractToRef = function (right, result) {
  512. result.r = this.r - right.r;
  513. result.g = this.g - right.g;
  514. result.b = this.b - right.b;
  515. result.a = this.a - right.a;
  516. return this;
  517. };
  518. /**
  519. * Creates a new Color4 with the current Color4 values multiplied by scale.
  520. */
  521. Color4.prototype.scale = function (scale) {
  522. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  523. };
  524. /**
  525. * Multiplies the current Color4 values by scale and stores the result in "result".
  526. * Returns the Color4.
  527. */
  528. Color4.prototype.scaleToRef = function (scale, result) {
  529. result.r = this.r * scale;
  530. result.g = this.g * scale;
  531. result.b = this.b * scale;
  532. result.a = this.a * scale;
  533. return this;
  534. };
  535. /**
  536. * Multipy an RGBA Color4 value by another and return a new Color4 object
  537. * @param color The Color4 (RGBA) value to multiply by
  538. * @returns A new Color4.
  539. */
  540. Color4.prototype.multiply = function (color) {
  541. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  542. };
  543. /**
  544. * Multipy an RGBA Color4 value by another and push the result in a reference value
  545. * @param color The Color4 (RGBA) value to multiply by
  546. * @param result The Color4 (RGBA) to fill the result in
  547. * @returns the result Color4.
  548. */
  549. Color4.prototype.multiplyToRef = function (color, result) {
  550. result.r = this.r * color.r;
  551. result.g = this.g * color.g;
  552. result.b = this.b * color.b;
  553. result.a = this.a * color.a;
  554. return result;
  555. };
  556. /**
  557. * Returns a string with the Color4 values.
  558. */
  559. Color4.prototype.toString = function () {
  560. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  561. };
  562. /**
  563. * Returns the string "Color4"
  564. */
  565. Color4.prototype.getClassName = function () {
  566. return "Color4";
  567. };
  568. /**
  569. * Return the Color4 hash code as a number.
  570. */
  571. Color4.prototype.getHashCode = function () {
  572. var hash = this.r || 0;
  573. hash = (hash * 397) ^ (this.g || 0);
  574. hash = (hash * 397) ^ (this.b || 0);
  575. hash = (hash * 397) ^ (this.a || 0);
  576. return hash;
  577. };
  578. /**
  579. * Creates a new Color4 copied from the current one.
  580. */
  581. Color4.prototype.clone = function () {
  582. return new Color4(this.r, this.g, this.b, this.a);
  583. };
  584. /**
  585. * Copies the passed Color4 values into the current one.
  586. * Returns the updated Color4.
  587. */
  588. Color4.prototype.copyFrom = function (source) {
  589. this.r = source.r;
  590. this.g = source.g;
  591. this.b = source.b;
  592. this.a = source.a;
  593. return this;
  594. };
  595. /**
  596. * Copies the passed float values into the current one.
  597. * Returns the updated Color4.
  598. */
  599. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  600. this.r = r;
  601. this.g = g;
  602. this.b = b;
  603. this.a = a;
  604. return this;
  605. };
  606. /**
  607. * Copies the passed float values into the current one.
  608. * Returns the updated Color4.
  609. */
  610. Color4.prototype.set = function (r, g, b, a) {
  611. return this.copyFromFloats(r, g, b, a);
  612. };
  613. /**
  614. * Returns a string containing the hexadecimal Color4 code.
  615. */
  616. Color4.prototype.toHexString = function () {
  617. var intR = (this.r * 255) | 0;
  618. var intG = (this.g * 255) | 0;
  619. var intB = (this.b * 255) | 0;
  620. var intA = (this.a * 255) | 0;
  621. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  622. };
  623. /**
  624. * Returns a new Color4 converted to linear space.
  625. */
  626. Color4.prototype.toLinearSpace = function () {
  627. var convertedColor = new Color4();
  628. this.toLinearSpaceToRef(convertedColor);
  629. return convertedColor;
  630. };
  631. /**
  632. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  633. * Returns the unmodified Color4.
  634. */
  635. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  636. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  637. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  638. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  639. convertedColor.a = this.a;
  640. return this;
  641. };
  642. /**
  643. * Returns a new Color4 converted to gamma space.
  644. */
  645. Color4.prototype.toGammaSpace = function () {
  646. var convertedColor = new Color4();
  647. this.toGammaSpaceToRef(convertedColor);
  648. return convertedColor;
  649. };
  650. /**
  651. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  652. * Returns the unmodified Color4.
  653. */
  654. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  655. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  656. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  657. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  658. convertedColor.a = this.a;
  659. return this;
  660. };
  661. // Statics
  662. /**
  663. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  664. */
  665. Color4.FromHexString = function (hex) {
  666. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  667. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  668. return new Color4(0.0, 0.0, 0.0, 0.0);
  669. }
  670. var r = parseInt(hex.substring(1, 3), 16);
  671. var g = parseInt(hex.substring(3, 5), 16);
  672. var b = parseInt(hex.substring(5, 7), 16);
  673. var a = parseInt(hex.substring(7, 9), 16);
  674. return Color4.FromInts(r, g, b, a);
  675. };
  676. /**
  677. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  678. */
  679. Color4.Lerp = function (left, right, amount) {
  680. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  681. Color4.LerpToRef(left, right, amount, result);
  682. return result;
  683. };
  684. /**
  685. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  686. */
  687. Color4.LerpToRef = function (left, right, amount, result) {
  688. result.r = left.r + (right.r - left.r) * amount;
  689. result.g = left.g + (right.g - left.g) * amount;
  690. result.b = left.b + (right.b - left.b) * amount;
  691. result.a = left.a + (right.a - left.a) * amount;
  692. };
  693. /**
  694. * Creates a new Color4 from the starting index element of the passed array.
  695. */
  696. Color4.FromArray = function (array, offset) {
  697. if (offset === void 0) { offset = 0; }
  698. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  699. };
  700. /**
  701. * Creates a new Color4 from the passed integers ( < 256 ).
  702. */
  703. Color4.FromInts = function (r, g, b, a) {
  704. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  705. };
  706. Color4.CheckColors4 = function (colors, count) {
  707. // Check if color3 was used
  708. if (colors.length === count * 3) {
  709. var colors4 = [];
  710. for (var index = 0; index < colors.length; index += 3) {
  711. var newIndex = (index / 3) * 4;
  712. colors4[newIndex] = colors[index];
  713. colors4[newIndex + 1] = colors[index + 1];
  714. colors4[newIndex + 2] = colors[index + 2];
  715. colors4[newIndex + 3] = 1.0;
  716. }
  717. return colors4;
  718. }
  719. return colors;
  720. };
  721. return Color4;
  722. }());
  723. BABYLON.Color4 = Color4;
  724. var Vector2 = (function () {
  725. /**
  726. * Creates a new Vector2 from the passed x and y coordinates.
  727. */
  728. function Vector2(x, y) {
  729. this.x = x;
  730. this.y = y;
  731. }
  732. /**
  733. * Returns a string with the Vector2 coordinates.
  734. */
  735. Vector2.prototype.toString = function () {
  736. return "{X: " + this.x + " Y:" + this.y + "}";
  737. };
  738. /**
  739. * Returns the string "Vector2"
  740. */
  741. Vector2.prototype.getClassName = function () {
  742. return "Vector2";
  743. };
  744. /**
  745. * Returns the Vector2 hash code as a number.
  746. */
  747. Vector2.prototype.getHashCode = function () {
  748. var hash = this.x || 0;
  749. hash = (hash * 397) ^ (this.y || 0);
  750. return hash;
  751. };
  752. // Operators
  753. /**
  754. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  755. * Returns the Vector2.
  756. */
  757. Vector2.prototype.toArray = function (array, index) {
  758. if (index === void 0) { index = 0; }
  759. array[index] = this.x;
  760. array[index + 1] = this.y;
  761. return this;
  762. };
  763. /**
  764. * Returns a new array with 2 elements : the Vector2 coordinates.
  765. */
  766. Vector2.prototype.asArray = function () {
  767. var result = [];
  768. this.toArray(result, 0);
  769. return result;
  770. };
  771. /**
  772. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  773. * Returns the updated Vector2.
  774. */
  775. Vector2.prototype.copyFrom = function (source) {
  776. this.x = source.x;
  777. this.y = source.y;
  778. return this;
  779. };
  780. /**
  781. * Sets the Vector2 coordinates with the passed floats.
  782. * Returns the updated Vector2.
  783. */
  784. Vector2.prototype.copyFromFloats = function (x, y) {
  785. this.x = x;
  786. this.y = y;
  787. return this;
  788. };
  789. /**
  790. * Sets the Vector2 coordinates with the passed floats.
  791. * Returns the updated Vector2.
  792. */
  793. Vector2.prototype.set = function (x, y) {
  794. return this.copyFromFloats(x, y);
  795. };
  796. /**
  797. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  798. */
  799. Vector2.prototype.add = function (otherVector) {
  800. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  801. };
  802. /**
  803. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  804. * Returns the Vector2.
  805. */
  806. Vector2.prototype.addToRef = function (otherVector, result) {
  807. result.x = this.x + otherVector.x;
  808. result.y = this.y + otherVector.y;
  809. return this;
  810. };
  811. /**
  812. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  813. * Returns the updated Vector2.
  814. */
  815. Vector2.prototype.addInPlace = function (otherVector) {
  816. this.x += otherVector.x;
  817. this.y += otherVector.y;
  818. return this;
  819. };
  820. /**
  821. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  822. */
  823. Vector2.prototype.addVector3 = function (otherVector) {
  824. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  825. };
  826. /**
  827. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  828. */
  829. Vector2.prototype.subtract = function (otherVector) {
  830. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  831. };
  832. /**
  833. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  834. * Returns the Vector2.
  835. */
  836. Vector2.prototype.subtractToRef = function (otherVector, result) {
  837. result.x = this.x - otherVector.x;
  838. result.y = this.y - otherVector.y;
  839. return this;
  840. };
  841. /**
  842. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  843. * Returns the updated Vector2.
  844. */
  845. Vector2.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. return this;
  849. };
  850. /**
  851. * Multiplies in place the current Vector2 coordinates by the passed ones.
  852. * Returns the updated Vector2.
  853. */
  854. Vector2.prototype.multiplyInPlace = function (otherVector) {
  855. this.x *= otherVector.x;
  856. this.y *= otherVector.y;
  857. return this;
  858. };
  859. /**
  860. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  861. */
  862. Vector2.prototype.multiply = function (otherVector) {
  863. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  864. };
  865. /**
  866. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  867. * Returns the Vector2.
  868. */
  869. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  870. result.x = this.x * otherVector.x;
  871. result.y = this.y * otherVector.y;
  872. return this;
  873. };
  874. /**
  875. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  876. */
  877. Vector2.prototype.multiplyByFloats = function (x, y) {
  878. return new Vector2(this.x * x, this.y * y);
  879. };
  880. /**
  881. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  882. */
  883. Vector2.prototype.divide = function (otherVector) {
  884. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  885. };
  886. /**
  887. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  888. * Returns the Vector2.
  889. */
  890. Vector2.prototype.divideToRef = function (otherVector, result) {
  891. result.x = this.x / otherVector.x;
  892. result.y = this.y / otherVector.y;
  893. return this;
  894. };
  895. /**
  896. * Returns a new Vector2 with current Vector2 negated coordinates.
  897. */
  898. Vector2.prototype.negate = function () {
  899. return new Vector2(-this.x, -this.y);
  900. };
  901. /**
  902. * Multiply the Vector2 coordinates by scale.
  903. * Returns the updated Vector2.
  904. */
  905. Vector2.prototype.scaleInPlace = function (scale) {
  906. this.x *= scale;
  907. this.y *= scale;
  908. return this;
  909. };
  910. /**
  911. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  912. */
  913. Vector2.prototype.scale = function (scale) {
  914. return new Vector2(this.x * scale, this.y * scale);
  915. };
  916. /**
  917. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  918. */
  919. Vector2.prototype.equals = function (otherVector) {
  920. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  921. };
  922. /**
  923. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  924. */
  925. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  926. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  927. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  928. };
  929. // Properties
  930. /**
  931. * Returns the vector length (float).
  932. */
  933. Vector2.prototype.length = function () {
  934. return Math.sqrt(this.x * this.x + this.y * this.y);
  935. };
  936. /**
  937. * Returns the vector squared length (float);
  938. */
  939. Vector2.prototype.lengthSquared = function () {
  940. return (this.x * this.x + this.y * this.y);
  941. };
  942. // Methods
  943. /**
  944. * Normalize the vector.
  945. * Returns the updated Vector2.
  946. */
  947. Vector2.prototype.normalize = function () {
  948. var len = this.length();
  949. if (len === 0)
  950. return this;
  951. var num = 1.0 / len;
  952. this.x *= num;
  953. this.y *= num;
  954. return this;
  955. };
  956. /**
  957. * Returns a new Vector2 copied from the Vector2.
  958. */
  959. Vector2.prototype.clone = function () {
  960. return new Vector2(this.x, this.y);
  961. };
  962. // Statics
  963. /**
  964. * Returns a new Vector2(0, 0)
  965. */
  966. Vector2.Zero = function () {
  967. return new Vector2(0, 0);
  968. };
  969. /**
  970. * Returns a new Vector2(1, 1)
  971. */
  972. Vector2.One = function () {
  973. return new Vector2(1, 1);
  974. };
  975. /**
  976. * Returns a new Vector2 set from the passed index element of the passed array.
  977. */
  978. Vector2.FromArray = function (array, offset) {
  979. if (offset === void 0) { offset = 0; }
  980. return new Vector2(array[offset], array[offset + 1]);
  981. };
  982. /**
  983. * Sets "result" from the passed index element of the passed array.
  984. */
  985. Vector2.FromArrayToRef = function (array, offset, result) {
  986. result.x = array[offset];
  987. result.y = array[offset + 1];
  988. };
  989. /**
  990. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  991. */
  992. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  993. var squared = amount * amount;
  994. var cubed = amount * squared;
  995. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  996. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  997. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  998. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  999. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1000. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1001. return new Vector2(x, y);
  1002. };
  1003. /**
  1004. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1005. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1006. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1007. */
  1008. Vector2.Clamp = function (value, min, max) {
  1009. var x = value.x;
  1010. x = (x > max.x) ? max.x : x;
  1011. x = (x < min.x) ? min.x : x;
  1012. var y = value.y;
  1013. y = (y > max.y) ? max.y : y;
  1014. y = (y < min.y) ? min.y : y;
  1015. return new Vector2(x, y);
  1016. };
  1017. /**
  1018. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1019. */
  1020. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1021. var squared = amount * amount;
  1022. var cubed = amount * squared;
  1023. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1024. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1025. var part3 = (cubed - (2.0 * squared)) + amount;
  1026. var part4 = cubed - squared;
  1027. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1028. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1029. return new Vector2(x, y);
  1030. };
  1031. /**
  1032. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1033. */
  1034. Vector2.Lerp = function (start, end, amount) {
  1035. var x = start.x + ((end.x - start.x) * amount);
  1036. var y = start.y + ((end.y - start.y) * amount);
  1037. return new Vector2(x, y);
  1038. };
  1039. /**
  1040. * Returns the dot product (float) of the vector "left" and the vector "right".
  1041. */
  1042. Vector2.Dot = function (left, right) {
  1043. return left.x * right.x + left.y * right.y;
  1044. };
  1045. /**
  1046. * Returns a new Vector2 equal to the normalized passed vector.
  1047. */
  1048. Vector2.Normalize = function (vector) {
  1049. var newVector = vector.clone();
  1050. newVector.normalize();
  1051. return newVector;
  1052. };
  1053. /**
  1054. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1055. */
  1056. Vector2.Minimize = function (left, right) {
  1057. var x = (left.x < right.x) ? left.x : right.x;
  1058. var y = (left.y < right.y) ? left.y : right.y;
  1059. return new Vector2(x, y);
  1060. };
  1061. /**
  1062. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1063. */
  1064. Vector2.Maximize = function (left, right) {
  1065. var x = (left.x > right.x) ? left.x : right.x;
  1066. var y = (left.y > right.y) ? left.y : right.y;
  1067. return new Vector2(x, y);
  1068. };
  1069. /**
  1070. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1071. */
  1072. Vector2.Transform = function (vector, transformation) {
  1073. var r = Vector2.Zero();
  1074. Vector2.TransformToRef(vector, transformation, r);
  1075. return r;
  1076. };
  1077. /**
  1078. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1079. */
  1080. Vector2.TransformToRef = function (vector, transformation, result) {
  1081. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1082. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1083. result.x = x;
  1084. result.y = y;
  1085. };
  1086. /**
  1087. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1088. */
  1089. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1090. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1091. var sign = a < 0 ? -1 : 1;
  1092. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1093. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1094. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1095. };
  1096. /**
  1097. * Returns the distance (float) between the vectors "value1" and "value2".
  1098. */
  1099. Vector2.Distance = function (value1, value2) {
  1100. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1101. };
  1102. /**
  1103. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1104. */
  1105. Vector2.DistanceSquared = function (value1, value2) {
  1106. var x = value1.x - value2.x;
  1107. var y = value1.y - value2.y;
  1108. return (x * x) + (y * y);
  1109. };
  1110. /**
  1111. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1112. */
  1113. Vector2.Center = function (value1, value2) {
  1114. var center = value1.add(value2);
  1115. center.scaleInPlace(0.5);
  1116. return center;
  1117. };
  1118. /**
  1119. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1120. */
  1121. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1122. var l2 = Vector2.DistanceSquared(segA, segB);
  1123. if (l2 === 0.0) {
  1124. return Vector2.Distance(p, segA);
  1125. }
  1126. var v = segB.subtract(segA);
  1127. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1128. var proj = segA.add(v.multiplyByFloats(t, t));
  1129. return Vector2.Distance(p, proj);
  1130. };
  1131. return Vector2;
  1132. }());
  1133. BABYLON.Vector2 = Vector2;
  1134. var Vector3 = (function () {
  1135. /**
  1136. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1137. * A Vector3 is the main object used in 3D geometry.
  1138. * It can represent etiher the coordinates of a point the space, either a direction.
  1139. */
  1140. function Vector3(x, y, z) {
  1141. this.x = x;
  1142. this.y = y;
  1143. this.z = z;
  1144. }
  1145. /**
  1146. * Returns a string with the Vector3 coordinates.
  1147. */
  1148. Vector3.prototype.toString = function () {
  1149. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1150. };
  1151. /**
  1152. * Returns the string "Vector3"
  1153. */
  1154. Vector3.prototype.getClassName = function () {
  1155. return "Vector3";
  1156. };
  1157. /**
  1158. * Returns the Vector hash code.
  1159. */
  1160. Vector3.prototype.getHashCode = function () {
  1161. var hash = this.x || 0;
  1162. hash = (hash * 397) ^ (this.y || 0);
  1163. hash = (hash * 397) ^ (this.z || 0);
  1164. return hash;
  1165. };
  1166. // Operators
  1167. /**
  1168. * Returns a new array with three elements : the coordinates the Vector3.
  1169. */
  1170. Vector3.prototype.asArray = function () {
  1171. var result = [];
  1172. this.toArray(result, 0);
  1173. return result;
  1174. };
  1175. /**
  1176. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1177. * Returns the Vector3.
  1178. */
  1179. Vector3.prototype.toArray = function (array, index) {
  1180. if (index === void 0) { index = 0; }
  1181. array[index] = this.x;
  1182. array[index + 1] = this.y;
  1183. array[index + 2] = this.z;
  1184. return this;
  1185. };
  1186. /**
  1187. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1188. */
  1189. Vector3.prototype.toQuaternion = function () {
  1190. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1191. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1192. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1193. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1194. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1195. var cosy = Math.cos(this.y * 0.5);
  1196. var siny = Math.sin(this.y * 0.5);
  1197. result.x = coszMinusx * siny;
  1198. result.y = -sinzMinusx * siny;
  1199. result.z = sinxPlusz * cosy;
  1200. result.w = cosxPlusz * cosy;
  1201. return result;
  1202. };
  1203. /**
  1204. * Adds the passed vector to the current Vector3.
  1205. * Returns the updated Vector3.
  1206. */
  1207. Vector3.prototype.addInPlace = function (otherVector) {
  1208. this.x += otherVector.x;
  1209. this.y += otherVector.y;
  1210. this.z += otherVector.z;
  1211. return this;
  1212. };
  1213. /**
  1214. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1215. */
  1216. Vector3.prototype.add = function (otherVector) {
  1217. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1218. };
  1219. /**
  1220. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1221. * Returns the current Vector3.
  1222. */
  1223. Vector3.prototype.addToRef = function (otherVector, result) {
  1224. result.x = this.x + otherVector.x;
  1225. result.y = this.y + otherVector.y;
  1226. result.z = this.z + otherVector.z;
  1227. return this;
  1228. };
  1229. /**
  1230. * Subtract the passed vector from the current Vector3.
  1231. * Returns the updated Vector3.
  1232. */
  1233. Vector3.prototype.subtractInPlace = function (otherVector) {
  1234. this.x -= otherVector.x;
  1235. this.y -= otherVector.y;
  1236. this.z -= otherVector.z;
  1237. return this;
  1238. };
  1239. /**
  1240. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1241. */
  1242. Vector3.prototype.subtract = function (otherVector) {
  1243. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1244. };
  1245. /**
  1246. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1247. * Returns the current Vector3.
  1248. */
  1249. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1250. result.x = this.x - otherVector.x;
  1251. result.y = this.y - otherVector.y;
  1252. result.z = this.z - otherVector.z;
  1253. return this;
  1254. };
  1255. /**
  1256. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1257. */
  1258. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1259. return new Vector3(this.x - x, this.y - y, this.z - z);
  1260. };
  1261. /**
  1262. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1263. * Returns the current Vector3.
  1264. */
  1265. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1266. result.x = this.x - x;
  1267. result.y = this.y - y;
  1268. result.z = this.z - z;
  1269. return this;
  1270. };
  1271. /**
  1272. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1273. */
  1274. Vector3.prototype.negate = function () {
  1275. return new Vector3(-this.x, -this.y, -this.z);
  1276. };
  1277. /**
  1278. * Multiplies the Vector3 coordinates by the float "scale".
  1279. * Returns the updated Vector3.
  1280. */
  1281. Vector3.prototype.scaleInPlace = function (scale) {
  1282. this.x *= scale;
  1283. this.y *= scale;
  1284. this.z *= scale;
  1285. return this;
  1286. };
  1287. /**
  1288. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1289. */
  1290. Vector3.prototype.scale = function (scale) {
  1291. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1292. };
  1293. /**
  1294. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1295. * Returns the current Vector3.
  1296. */
  1297. Vector3.prototype.scaleToRef = function (scale, result) {
  1298. result.x = this.x * scale;
  1299. result.y = this.y * scale;
  1300. result.z = this.z * scale;
  1301. return this;
  1302. };
  1303. /**
  1304. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1305. */
  1306. Vector3.prototype.equals = function (otherVector) {
  1307. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1308. };
  1309. /**
  1310. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1311. */
  1312. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1313. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1314. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1315. };
  1316. /**
  1317. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1318. */
  1319. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1320. return this.x === x && this.y === y && this.z === z;
  1321. };
  1322. /**
  1323. * Muliplies the current Vector3 coordinates by the passed ones.
  1324. * Returns the updated Vector3.
  1325. */
  1326. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1327. this.x *= otherVector.x;
  1328. this.y *= otherVector.y;
  1329. this.z *= otherVector.z;
  1330. return this;
  1331. };
  1332. /**
  1333. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1334. */
  1335. Vector3.prototype.multiply = function (otherVector) {
  1336. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1337. };
  1338. /**
  1339. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1340. * Returns the current Vector3.
  1341. */
  1342. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1343. result.x = this.x * otherVector.x;
  1344. result.y = this.y * otherVector.y;
  1345. result.z = this.z * otherVector.z;
  1346. return this;
  1347. };
  1348. /**
  1349. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1350. */
  1351. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1352. return new Vector3(this.x * x, this.y * y, this.z * z);
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1356. */
  1357. Vector3.prototype.divide = function (otherVector) {
  1358. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1359. };
  1360. /**
  1361. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1362. * Returns the current Vector3.
  1363. */
  1364. Vector3.prototype.divideToRef = function (otherVector, result) {
  1365. result.x = this.x / otherVector.x;
  1366. result.y = this.y / otherVector.y;
  1367. result.z = this.z / otherVector.z;
  1368. return this;
  1369. };
  1370. /**
  1371. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1372. * Returns the updated Vector3.
  1373. */
  1374. Vector3.prototype.MinimizeInPlace = function (other) {
  1375. if (other.x < this.x)
  1376. this.x = other.x;
  1377. if (other.y < this.y)
  1378. this.y = other.y;
  1379. if (other.z < this.z)
  1380. this.z = other.z;
  1381. return this;
  1382. };
  1383. /**
  1384. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1385. * Returns the updated Vector3.
  1386. */
  1387. Vector3.prototype.MaximizeInPlace = function (other) {
  1388. if (other.x > this.x)
  1389. this.x = other.x;
  1390. if (other.y > this.y)
  1391. this.y = other.y;
  1392. if (other.z > this.z)
  1393. this.z = other.z;
  1394. return this;
  1395. };
  1396. // Properties
  1397. /**
  1398. * Returns the length of the Vector3 (float).
  1399. */
  1400. Vector3.prototype.length = function () {
  1401. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1402. };
  1403. /**
  1404. * Returns the squared length of the Vector3 (float).
  1405. */
  1406. Vector3.prototype.lengthSquared = function () {
  1407. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1408. };
  1409. // Methods
  1410. /**
  1411. * Normalize the current Vector3.
  1412. * Returns the updated Vector3.
  1413. */
  1414. Vector3.prototype.normalize = function () {
  1415. var len = this.length();
  1416. if (len === 0 || len === 1.0)
  1417. return this;
  1418. var num = 1.0 / len;
  1419. this.x *= num;
  1420. this.y *= num;
  1421. this.z *= num;
  1422. return this;
  1423. };
  1424. /**
  1425. * Returns a new Vector3 copied from the current Vector3.
  1426. */
  1427. Vector3.prototype.clone = function () {
  1428. return new Vector3(this.x, this.y, this.z);
  1429. };
  1430. /**
  1431. * Copies the passed vector coordinates to the current Vector3 ones.
  1432. * Returns the updated Vector3.
  1433. */
  1434. Vector3.prototype.copyFrom = function (source) {
  1435. this.x = source.x;
  1436. this.y = source.y;
  1437. this.z = source.z;
  1438. return this;
  1439. };
  1440. /**
  1441. * Copies the passed floats to the current Vector3 coordinates.
  1442. * Returns the updated Vector3.
  1443. */
  1444. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1445. this.x = x;
  1446. this.y = y;
  1447. this.z = z;
  1448. return this;
  1449. };
  1450. /**
  1451. * Copies the passed floats to the current Vector3 coordinates.
  1452. * Returns the updated Vector3.
  1453. */
  1454. Vector3.prototype.set = function (x, y, z) {
  1455. return this.copyFromFloats(x, y, z);
  1456. };
  1457. // Statics
  1458. /**
  1459. *
  1460. */
  1461. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1462. var d0 = Vector3.Dot(vector0, axis) - size;
  1463. var d1 = Vector3.Dot(vector1, axis) - size;
  1464. var s = d0 / (d0 - d1);
  1465. return s;
  1466. };
  1467. /**
  1468. * Returns a new Vector3 set from the index "offset" of the passed array.
  1469. */
  1470. Vector3.FromArray = function (array, offset) {
  1471. if (!offset) {
  1472. offset = 0;
  1473. }
  1474. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1475. };
  1476. /**
  1477. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1478. * This function is deprecated. Use FromArray instead.
  1479. */
  1480. Vector3.FromFloatArray = function (array, offset) {
  1481. return Vector3.FromArray(array, offset);
  1482. };
  1483. /**
  1484. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1485. */
  1486. Vector3.FromArrayToRef = function (array, offset, result) {
  1487. result.x = array[offset];
  1488. result.y = array[offset + 1];
  1489. result.z = array[offset + 2];
  1490. };
  1491. /**
  1492. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1493. * This function is deprecated. Use FromArrayToRef instead.
  1494. */
  1495. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1496. return Vector3.FromArrayToRef(array, offset, result);
  1497. };
  1498. /**
  1499. * Sets the passed vector "result" with the passed floats.
  1500. */
  1501. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1502. result.x = x;
  1503. result.y = y;
  1504. result.z = z;
  1505. };
  1506. /**
  1507. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1508. */
  1509. Vector3.Zero = function () {
  1510. return new Vector3(0.0, 0.0, 0.0);
  1511. };
  1512. /**
  1513. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1514. */
  1515. Vector3.One = function () {
  1516. return new Vector3(1.0, 1.0, 1.0);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1520. */
  1521. Vector3.Up = function () {
  1522. return new Vector3(0.0, 1.0, 0.0);
  1523. };
  1524. /**
  1525. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1526. */
  1527. Vector3.Forward = function () {
  1528. return new Vector3(0.0, 0.0, 1.0);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1532. */
  1533. Vector3.Right = function () {
  1534. return new Vector3(1.0, 0.0, 0.0);
  1535. };
  1536. /**
  1537. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1538. */
  1539. Vector3.Left = function () {
  1540. return new Vector3(-1.0, 0.0, 0.0);
  1541. };
  1542. /**
  1543. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1544. * This method computes tranformed coordinates only, not transformed direction vectors.
  1545. */
  1546. Vector3.TransformCoordinates = function (vector, transformation) {
  1547. var result = Vector3.Zero();
  1548. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1549. return result;
  1550. };
  1551. /**
  1552. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1553. * This method computes tranformed coordinates only, not transformed direction vectors.
  1554. */
  1555. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1556. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1557. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1558. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1559. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1560. result.x = x / w;
  1561. result.y = y / w;
  1562. result.z = z / w;
  1563. };
  1564. /**
  1565. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1566. * This method computes tranformed coordinates only, not transformed direction vectors.
  1567. */
  1568. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1569. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1570. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1571. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1572. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1573. result.x = rx / rw;
  1574. result.y = ry / rw;
  1575. result.z = rz / rw;
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1579. * This methods computes transformed normalized direction vectors only.
  1580. */
  1581. Vector3.TransformNormal = function (vector, transformation) {
  1582. var result = Vector3.Zero();
  1583. Vector3.TransformNormalToRef(vector, transformation, result);
  1584. return result;
  1585. };
  1586. /**
  1587. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1588. * This methods computes transformed normalized direction vectors only.
  1589. */
  1590. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1591. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1592. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1593. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1594. result.x = x;
  1595. result.y = y;
  1596. result.z = z;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1600. * This methods computes transformed normalized direction vectors only.
  1601. */
  1602. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1603. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1604. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1605. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1606. };
  1607. /**
  1608. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1609. */
  1610. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1611. var squared = amount * amount;
  1612. var cubed = amount * squared;
  1613. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1614. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1615. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1616. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1617. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1618. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1619. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1620. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1621. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1622. return new Vector3(x, y, z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1626. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1627. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1628. */
  1629. Vector3.Clamp = function (value, min, max) {
  1630. var x = value.x;
  1631. x = (x > max.x) ? max.x : x;
  1632. x = (x < min.x) ? min.x : x;
  1633. var y = value.y;
  1634. y = (y > max.y) ? max.y : y;
  1635. y = (y < min.y) ? min.y : y;
  1636. var z = value.z;
  1637. z = (z > max.z) ? max.z : z;
  1638. z = (z < min.z) ? min.z : z;
  1639. return new Vector3(x, y, z);
  1640. };
  1641. /**
  1642. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1643. */
  1644. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1645. var squared = amount * amount;
  1646. var cubed = amount * squared;
  1647. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1648. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1649. var part3 = (cubed - (2.0 * squared)) + amount;
  1650. var part4 = cubed - squared;
  1651. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1652. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1653. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1654. return new Vector3(x, y, z);
  1655. };
  1656. /**
  1657. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1658. */
  1659. Vector3.Lerp = function (start, end, amount) {
  1660. var result = new Vector3(0, 0, 0);
  1661. Vector3.LerpToRef(start, end, amount, result);
  1662. return result;
  1663. };
  1664. /**
  1665. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1666. */
  1667. Vector3.LerpToRef = function (start, end, amount, result) {
  1668. result.x = start.x + ((end.x - start.x) * amount);
  1669. result.y = start.y + ((end.y - start.y) * amount);
  1670. result.z = start.z + ((end.z - start.z) * amount);
  1671. };
  1672. /**
  1673. * Returns the dot product (float) between the vectors "left" and "right".
  1674. */
  1675. Vector3.Dot = function (left, right) {
  1676. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1677. };
  1678. /**
  1679. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1680. * The cross product is then orthogonal to both "left" and "right".
  1681. */
  1682. Vector3.Cross = function (left, right) {
  1683. var result = Vector3.Zero();
  1684. Vector3.CrossToRef(left, right, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the cross product of "left" and "right".
  1689. * The cross product is then orthogonal to both "left" and "right".
  1690. */
  1691. Vector3.CrossToRef = function (left, right, result) {
  1692. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1693. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1694. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1695. result.copyFrom(MathTmp.Vector3[0]);
  1696. };
  1697. /**
  1698. * Returns a new Vector3 as the normalization of the passed vector.
  1699. */
  1700. Vector3.Normalize = function (vector) {
  1701. var result = Vector3.Zero();
  1702. Vector3.NormalizeToRef(vector, result);
  1703. return result;
  1704. };
  1705. /**
  1706. * Sets the passed vector "result" with the normalization of the passed first vector.
  1707. */
  1708. Vector3.NormalizeToRef = function (vector, result) {
  1709. result.copyFrom(vector);
  1710. result.normalize();
  1711. };
  1712. Vector3.Project = function (vector, world, transform, viewport) {
  1713. var cw = viewport.width;
  1714. var ch = viewport.height;
  1715. var cx = viewport.x;
  1716. var cy = viewport.y;
  1717. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1718. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1719. var matrix = MathTmp.Matrix[0];
  1720. world.multiplyToRef(transform, matrix);
  1721. matrix.multiplyToRef(viewportMatrix, matrix);
  1722. return Vector3.TransformCoordinates(vector, matrix);
  1723. };
  1724. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1725. var matrix = MathTmp.Matrix[0];
  1726. world.multiplyToRef(transform, matrix);
  1727. matrix.invert();
  1728. source.x = source.x / viewportWidth * 2 - 1;
  1729. source.y = -(source.y / viewportHeight * 2 - 1);
  1730. var vector = Vector3.TransformCoordinates(source, matrix);
  1731. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1732. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1733. vector = vector.scale(1.0 / num);
  1734. }
  1735. return vector;
  1736. };
  1737. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1738. var matrix = MathTmp.Matrix[0];
  1739. world.multiplyToRef(view, matrix);
  1740. matrix.multiplyToRef(projection, matrix);
  1741. matrix.invert();
  1742. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1743. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1744. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1745. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1746. vector = vector.scale(1.0 / num);
  1747. }
  1748. return vector;
  1749. };
  1750. Vector3.Minimize = function (left, right) {
  1751. var min = left.clone();
  1752. min.MinimizeInPlace(right);
  1753. return min;
  1754. };
  1755. Vector3.Maximize = function (left, right) {
  1756. var max = left.clone();
  1757. max.MaximizeInPlace(right);
  1758. return max;
  1759. };
  1760. /**
  1761. * Returns the distance (float) between the vectors "value1" and "value2".
  1762. */
  1763. Vector3.Distance = function (value1, value2) {
  1764. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1765. };
  1766. /**
  1767. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1768. */
  1769. Vector3.DistanceSquared = function (value1, value2) {
  1770. var x = value1.x - value2.x;
  1771. var y = value1.y - value2.y;
  1772. var z = value1.z - value2.z;
  1773. return (x * x) + (y * y) + (z * z);
  1774. };
  1775. /**
  1776. * Returns a new Vector3 located at the center between "value1" and "value2".
  1777. */
  1778. Vector3.Center = function (value1, value2) {
  1779. var center = value1.add(value2);
  1780. center.scaleInPlace(0.5);
  1781. return center;
  1782. };
  1783. /**
  1784. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1785. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1786. * to something in order to rotate it from its local system to the given target system.
  1787. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1788. * Returns a new Vector3.
  1789. */
  1790. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1791. var rotation = Vector3.Zero();
  1792. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1793. return rotation;
  1794. };
  1795. /**
  1796. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1797. */
  1798. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1799. var quat = MathTmp.Quaternion[0];
  1800. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1801. quat.toEulerAnglesToRef(ref);
  1802. };
  1803. return Vector3;
  1804. }());
  1805. BABYLON.Vector3 = Vector3;
  1806. //Vector4 class created for EulerAngle class conversion to Quaternion
  1807. var Vector4 = (function () {
  1808. /**
  1809. * Creates a Vector4 object from the passed floats.
  1810. */
  1811. function Vector4(x, y, z, w) {
  1812. this.x = x;
  1813. this.y = y;
  1814. this.z = z;
  1815. this.w = w;
  1816. }
  1817. /**
  1818. * Returns the string with the Vector4 coordinates.
  1819. */
  1820. Vector4.prototype.toString = function () {
  1821. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1822. };
  1823. /**
  1824. * Returns the string "Vector4".
  1825. */
  1826. Vector4.prototype.getClassName = function () {
  1827. return "Vector4";
  1828. };
  1829. /**
  1830. * Returns the Vector4 hash code.
  1831. */
  1832. Vector4.prototype.getHashCode = function () {
  1833. var hash = this.x || 0;
  1834. hash = (hash * 397) ^ (this.y || 0);
  1835. hash = (hash * 397) ^ (this.z || 0);
  1836. hash = (hash * 397) ^ (this.w || 0);
  1837. return hash;
  1838. };
  1839. // Operators
  1840. /**
  1841. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.asArray = function () {
  1844. var result = [];
  1845. this.toArray(result, 0);
  1846. return result;
  1847. };
  1848. /**
  1849. * Populates the passed array from the passed index with the Vector4 coordinates.
  1850. * Returns the Vector4.
  1851. */
  1852. Vector4.prototype.toArray = function (array, index) {
  1853. if (index === undefined) {
  1854. index = 0;
  1855. }
  1856. array[index] = this.x;
  1857. array[index + 1] = this.y;
  1858. array[index + 2] = this.z;
  1859. array[index + 3] = this.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Adds the passed vector to the current Vector4.
  1864. * Returns the updated Vector4.
  1865. */
  1866. Vector4.prototype.addInPlace = function (otherVector) {
  1867. this.x += otherVector.x;
  1868. this.y += otherVector.y;
  1869. this.z += otherVector.z;
  1870. this.w += otherVector.w;
  1871. return this;
  1872. };
  1873. /**
  1874. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1875. */
  1876. Vector4.prototype.add = function (otherVector) {
  1877. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1878. };
  1879. /**
  1880. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1881. * Returns the current Vector4.
  1882. */
  1883. Vector4.prototype.addToRef = function (otherVector, result) {
  1884. result.x = this.x + otherVector.x;
  1885. result.y = this.y + otherVector.y;
  1886. result.z = this.z + otherVector.z;
  1887. result.w = this.w + otherVector.w;
  1888. return this;
  1889. };
  1890. /**
  1891. * Subtract in place the passed vector from the current Vector4.
  1892. * Returns the updated Vector4.
  1893. */
  1894. Vector4.prototype.subtractInPlace = function (otherVector) {
  1895. this.x -= otherVector.x;
  1896. this.y -= otherVector.y;
  1897. this.z -= otherVector.z;
  1898. this.w -= otherVector.w;
  1899. return this;
  1900. };
  1901. /**
  1902. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1903. */
  1904. Vector4.prototype.subtract = function (otherVector) {
  1905. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1906. };
  1907. /**
  1908. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1909. * Returns the current Vector4.
  1910. */
  1911. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1912. result.x = this.x - otherVector.x;
  1913. result.y = this.y - otherVector.y;
  1914. result.z = this.z - otherVector.z;
  1915. result.w = this.w - otherVector.w;
  1916. return this;
  1917. };
  1918. /**
  1919. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1920. */
  1921. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1922. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1923. };
  1924. /**
  1925. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1926. * Returns the current Vector4.
  1927. */
  1928. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1929. result.x = this.x - x;
  1930. result.y = this.y - y;
  1931. result.z = this.z - z;
  1932. result.w = this.w - w;
  1933. return this;
  1934. };
  1935. /**
  1936. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1937. */
  1938. Vector4.prototype.negate = function () {
  1939. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1940. };
  1941. /**
  1942. * Multiplies the current Vector4 coordinates by scale (float).
  1943. * Returns the updated Vector4.
  1944. */
  1945. Vector4.prototype.scaleInPlace = function (scale) {
  1946. this.x *= scale;
  1947. this.y *= scale;
  1948. this.z *= scale;
  1949. this.w *= scale;
  1950. return this;
  1951. };
  1952. /**
  1953. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1954. */
  1955. Vector4.prototype.scale = function (scale) {
  1956. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1957. };
  1958. /**
  1959. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1960. * Returns the current Vector4.
  1961. */
  1962. Vector4.prototype.scaleToRef = function (scale, result) {
  1963. result.x = this.x * scale;
  1964. result.y = this.y * scale;
  1965. result.z = this.z * scale;
  1966. result.w = this.w * scale;
  1967. return this;
  1968. };
  1969. /**
  1970. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1971. */
  1972. Vector4.prototype.equals = function (otherVector) {
  1973. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1974. };
  1975. /**
  1976. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1977. */
  1978. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1979. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1980. return otherVector
  1981. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1982. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1983. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1984. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1985. };
  1986. /**
  1987. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1988. */
  1989. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1990. return this.x === x && this.y === y && this.z === z && this.w === w;
  1991. };
  1992. /**
  1993. * Multiplies in place the current Vector4 by the passed one.
  1994. * Returns the updated Vector4.
  1995. */
  1996. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1997. this.x *= otherVector.x;
  1998. this.y *= otherVector.y;
  1999. this.z *= otherVector.z;
  2000. this.w *= otherVector.w;
  2001. return this;
  2002. };
  2003. /**
  2004. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2005. */
  2006. Vector4.prototype.multiply = function (otherVector) {
  2007. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2011. * Returns the current Vector4.
  2012. */
  2013. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2014. result.x = this.x * otherVector.x;
  2015. result.y = this.y * otherVector.y;
  2016. result.z = this.z * otherVector.z;
  2017. result.w = this.w * otherVector.w;
  2018. return this;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2022. */
  2023. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2024. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2028. */
  2029. Vector4.prototype.divide = function (otherVector) {
  2030. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.divideToRef = function (otherVector, result) {
  2037. result.x = this.x / otherVector.x;
  2038. result.y = this.y / otherVector.y;
  2039. result.z = this.z / otherVector.z;
  2040. result.w = this.w / otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2045. */
  2046. Vector4.prototype.MinimizeInPlace = function (other) {
  2047. if (other.x < this.x)
  2048. this.x = other.x;
  2049. if (other.y < this.y)
  2050. this.y = other.y;
  2051. if (other.z < this.z)
  2052. this.z = other.z;
  2053. if (other.w < this.w)
  2054. this.w = other.w;
  2055. return this;
  2056. };
  2057. /**
  2058. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2059. */
  2060. Vector4.prototype.MaximizeInPlace = function (other) {
  2061. if (other.x > this.x)
  2062. this.x = other.x;
  2063. if (other.y > this.y)
  2064. this.y = other.y;
  2065. if (other.z > this.z)
  2066. this.z = other.z;
  2067. if (other.w > this.w)
  2068. this.w = other.w;
  2069. return this;
  2070. };
  2071. // Properties
  2072. /**
  2073. * Returns the Vector4 length (float).
  2074. */
  2075. Vector4.prototype.length = function () {
  2076. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2077. };
  2078. /**
  2079. * Returns the Vector4 squared length (float).
  2080. */
  2081. Vector4.prototype.lengthSquared = function () {
  2082. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2083. };
  2084. // Methods
  2085. /**
  2086. * Normalizes in place the Vector4.
  2087. * Returns the updated Vector4.
  2088. */
  2089. Vector4.prototype.normalize = function () {
  2090. var len = this.length();
  2091. if (len === 0)
  2092. return this;
  2093. var num = 1.0 / len;
  2094. this.x *= num;
  2095. this.y *= num;
  2096. this.z *= num;
  2097. this.w *= num;
  2098. return this;
  2099. };
  2100. /**
  2101. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2102. */
  2103. Vector4.prototype.toVector3 = function () {
  2104. return new Vector3(this.x, this.y, this.z);
  2105. };
  2106. /**
  2107. * Returns a new Vector4 copied from the current one.
  2108. */
  2109. Vector4.prototype.clone = function () {
  2110. return new Vector4(this.x, this.y, this.z, this.w);
  2111. };
  2112. /**
  2113. * Updates the current Vector4 with the passed one coordinates.
  2114. * Returns the updated Vector4.
  2115. */
  2116. Vector4.prototype.copyFrom = function (source) {
  2117. this.x = source.x;
  2118. this.y = source.y;
  2119. this.z = source.z;
  2120. this.w = source.w;
  2121. return this;
  2122. };
  2123. /**
  2124. * Updates the current Vector4 coordinates with the passed floats.
  2125. * Returns the updated Vector4.
  2126. */
  2127. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2128. this.x = x;
  2129. this.y = y;
  2130. this.z = z;
  2131. this.w = w;
  2132. return this;
  2133. };
  2134. /**
  2135. * Updates the current Vector4 coordinates with the passed floats.
  2136. * Returns the updated Vector4.
  2137. */
  2138. Vector4.prototype.set = function (x, y, z, w) {
  2139. return this.copyFromFloats(x, y, z, w);
  2140. };
  2141. // Statics
  2142. /**
  2143. * Returns a new Vector4 set from the starting index of the passed array.
  2144. */
  2145. Vector4.FromArray = function (array, offset) {
  2146. if (!offset) {
  2147. offset = 0;
  2148. }
  2149. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2150. };
  2151. /**
  2152. * Updates the passed vector "result" from the starting index of the passed array.
  2153. */
  2154. Vector4.FromArrayToRef = function (array, offset, result) {
  2155. result.x = array[offset];
  2156. result.y = array[offset + 1];
  2157. result.z = array[offset + 2];
  2158. result.w = array[offset + 3];
  2159. };
  2160. /**
  2161. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2162. */
  2163. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2164. Vector4.FromArrayToRef(array, offset, result);
  2165. };
  2166. /**
  2167. * Updates the passed vector "result" coordinates from the passed floats.
  2168. */
  2169. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2170. result.x = x;
  2171. result.y = y;
  2172. result.z = z;
  2173. result.w = w;
  2174. };
  2175. /**
  2176. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2177. */
  2178. Vector4.Zero = function () {
  2179. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2180. };
  2181. /**
  2182. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2183. */
  2184. Vector4.One = function () {
  2185. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2186. };
  2187. /**
  2188. * Returns a new normalized Vector4 from the passed one.
  2189. */
  2190. Vector4.Normalize = function (vector) {
  2191. var result = Vector4.Zero();
  2192. Vector4.NormalizeToRef(vector, result);
  2193. return result;
  2194. };
  2195. /**
  2196. * Updates the passed vector "result" from the normalization of the passed one.
  2197. */
  2198. Vector4.NormalizeToRef = function (vector, result) {
  2199. result.copyFrom(vector);
  2200. result.normalize();
  2201. };
  2202. Vector4.Minimize = function (left, right) {
  2203. var min = left.clone();
  2204. min.MinimizeInPlace(right);
  2205. return min;
  2206. };
  2207. Vector4.Maximize = function (left, right) {
  2208. var max = left.clone();
  2209. max.MaximizeInPlace(right);
  2210. return max;
  2211. };
  2212. /**
  2213. * Returns the distance (float) between the vectors "value1" and "value2".
  2214. */
  2215. Vector4.Distance = function (value1, value2) {
  2216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2217. };
  2218. /**
  2219. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2220. */
  2221. Vector4.DistanceSquared = function (value1, value2) {
  2222. var x = value1.x - value2.x;
  2223. var y = value1.y - value2.y;
  2224. var z = value1.z - value2.z;
  2225. var w = value1.w - value2.w;
  2226. return (x * x) + (y * y) + (z * z) + (w * w);
  2227. };
  2228. /**
  2229. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2230. */
  2231. Vector4.Center = function (value1, value2) {
  2232. var center = value1.add(value2);
  2233. center.scaleInPlace(0.5);
  2234. return center;
  2235. };
  2236. /**
  2237. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2238. * This methods computes transformed normalized direction vectors only.
  2239. */
  2240. Vector4.TransformNormal = function (vector, transformation) {
  2241. var result = Vector4.Zero();
  2242. Vector4.TransformNormalToRef(vector, transformation, result);
  2243. return result;
  2244. };
  2245. /**
  2246. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2247. * This methods computes transformed normalized direction vectors only.
  2248. */
  2249. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2250. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2251. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2252. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2253. result.x = x;
  2254. result.y = y;
  2255. result.z = z;
  2256. result.w = vector.w;
  2257. };
  2258. /**
  2259. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2260. * This methods computes transformed normalized direction vectors only.
  2261. */
  2262. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2263. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2264. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2265. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2266. result.w = w;
  2267. };
  2268. return Vector4;
  2269. }());
  2270. BABYLON.Vector4 = Vector4;
  2271. var Size = (function () {
  2272. /**
  2273. * Creates a Size object from the passed width and height (floats).
  2274. */
  2275. function Size(width, height) {
  2276. this.width = width;
  2277. this.height = height;
  2278. }
  2279. // Returns a string with the Size width and height.
  2280. Size.prototype.toString = function () {
  2281. return "{W: " + this.width + ", H: " + this.height + "}";
  2282. };
  2283. /**
  2284. * Returns the string "Size"
  2285. */
  2286. Size.prototype.getClassName = function () {
  2287. return "Size";
  2288. };
  2289. /**
  2290. * Returns the Size hash code.
  2291. */
  2292. Size.prototype.getHashCode = function () {
  2293. var hash = this.width || 0;
  2294. hash = (hash * 397) ^ (this.height || 0);
  2295. return hash;
  2296. };
  2297. /**
  2298. * Updates the current size from the passed one.
  2299. * Returns the updated Size.
  2300. */
  2301. Size.prototype.copyFrom = function (src) {
  2302. this.width = src.width;
  2303. this.height = src.height;
  2304. };
  2305. /**
  2306. * Updates in place the current Size from the passed floats.
  2307. * Returns the updated Size.
  2308. */
  2309. Size.prototype.copyFromFloats = function (width, height) {
  2310. this.width = width;
  2311. this.height = height;
  2312. return this;
  2313. };
  2314. /**
  2315. * Updates in place the current Size from the passed floats.
  2316. * Returns the updated Size.
  2317. */
  2318. Size.prototype.set = function (width, height) {
  2319. return this.copyFromFloats(width, height);
  2320. };
  2321. /**
  2322. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2323. */
  2324. Size.prototype.multiplyByFloats = function (w, h) {
  2325. return new Size(this.width * w, this.height * h);
  2326. };
  2327. /**
  2328. * Returns a new Size copied from the passed one.
  2329. */
  2330. Size.prototype.clone = function () {
  2331. return new Size(this.width, this.height);
  2332. };
  2333. /**
  2334. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2335. */
  2336. Size.prototype.equals = function (other) {
  2337. if (!other) {
  2338. return false;
  2339. }
  2340. return (this.width === other.width) && (this.height === other.height);
  2341. };
  2342. Object.defineProperty(Size.prototype, "surface", {
  2343. /**
  2344. * Returns the surface of the Size : width * height (float).
  2345. */
  2346. get: function () {
  2347. return this.width * this.height;
  2348. },
  2349. enumerable: true,
  2350. configurable: true
  2351. });
  2352. /**
  2353. * Returns a new Size set to (0.0, 0.0)
  2354. */
  2355. Size.Zero = function () {
  2356. return new Size(0.0, 0.0);
  2357. };
  2358. /**
  2359. * Returns a new Size set as the addition result of the current Size and the passed one.
  2360. */
  2361. Size.prototype.add = function (otherSize) {
  2362. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2363. return r;
  2364. };
  2365. /**
  2366. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2367. */
  2368. Size.prototype.subtract = function (otherSize) {
  2369. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2370. return r;
  2371. };
  2372. /**
  2373. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2374. */
  2375. Size.Lerp = function (start, end, amount) {
  2376. var w = start.width + ((end.width - start.width) * amount);
  2377. var h = start.height + ((end.height - start.height) * amount);
  2378. return new Size(w, h);
  2379. };
  2380. return Size;
  2381. }());
  2382. BABYLON.Size = Size;
  2383. var Quaternion = (function () {
  2384. /**
  2385. * Creates a new Quaternion from the passed floats.
  2386. */
  2387. function Quaternion(x, y, z, w) {
  2388. if (x === void 0) { x = 0.0; }
  2389. if (y === void 0) { y = 0.0; }
  2390. if (z === void 0) { z = 0.0; }
  2391. if (w === void 0) { w = 1.0; }
  2392. this.x = x;
  2393. this.y = y;
  2394. this.z = z;
  2395. this.w = w;
  2396. }
  2397. /**
  2398. * Returns a string with the Quaternion coordinates.
  2399. */
  2400. Quaternion.prototype.toString = function () {
  2401. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2402. };
  2403. /**
  2404. * Returns the string "Quaternion".
  2405. */
  2406. Quaternion.prototype.getClassName = function () {
  2407. return "Quaternion";
  2408. };
  2409. /**
  2410. * Returns the Quaternion hash code.
  2411. */
  2412. Quaternion.prototype.getHashCode = function () {
  2413. var hash = this.x || 0;
  2414. hash = (hash * 397) ^ (this.y || 0);
  2415. hash = (hash * 397) ^ (this.z || 0);
  2416. hash = (hash * 397) ^ (this.w || 0);
  2417. return hash;
  2418. };
  2419. /**
  2420. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2421. */
  2422. Quaternion.prototype.asArray = function () {
  2423. return [this.x, this.y, this.z, this.w];
  2424. };
  2425. /**
  2426. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2427. */
  2428. Quaternion.prototype.equals = function (otherQuaternion) {
  2429. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2430. };
  2431. /**
  2432. * Returns a new Quaternion copied from the current one.
  2433. */
  2434. Quaternion.prototype.clone = function () {
  2435. return new Quaternion(this.x, this.y, this.z, this.w);
  2436. };
  2437. /**
  2438. * Updates the current Quaternion from the passed one coordinates.
  2439. * Returns the updated Quaterion.
  2440. */
  2441. Quaternion.prototype.copyFrom = function (other) {
  2442. this.x = other.x;
  2443. this.y = other.y;
  2444. this.z = other.z;
  2445. this.w = other.w;
  2446. return this;
  2447. };
  2448. /**
  2449. * Updates the current Quaternion from the passed float coordinates.
  2450. * Returns the updated Quaterion.
  2451. */
  2452. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2453. this.x = x;
  2454. this.y = y;
  2455. this.z = z;
  2456. this.w = w;
  2457. return this;
  2458. };
  2459. /**
  2460. * Updates the current Quaternion from the passed float coordinates.
  2461. * Returns the updated Quaterion.
  2462. */
  2463. Quaternion.prototype.set = function (x, y, z, w) {
  2464. return this.copyFromFloats(x, y, z, w);
  2465. };
  2466. /**
  2467. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2468. */
  2469. Quaternion.prototype.add = function (other) {
  2470. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2471. };
  2472. /**
  2473. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2474. */
  2475. Quaternion.prototype.subtract = function (other) {
  2476. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2477. };
  2478. /**
  2479. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2480. */
  2481. Quaternion.prototype.scale = function (value) {
  2482. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2483. };
  2484. /**
  2485. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2486. */
  2487. Quaternion.prototype.multiply = function (q1) {
  2488. var result = new Quaternion(0, 0, 0, 1.0);
  2489. this.multiplyToRef(q1, result);
  2490. return result;
  2491. };
  2492. /**
  2493. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2494. * Returns the current Quaternion.
  2495. */
  2496. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2497. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2498. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2499. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2500. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2501. result.copyFromFloats(x, y, z, w);
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.multiplyInPlace = function (q1) {
  2509. this.multiplyToRef(q1, this);
  2510. return this;
  2511. };
  2512. /**
  2513. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2514. * Returns the current Quaternion.
  2515. */
  2516. Quaternion.prototype.conjugateToRef = function (ref) {
  2517. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2518. return this;
  2519. };
  2520. /**
  2521. * Conjugates in place the current Quaternion.
  2522. * Returns the updated Quaternion.
  2523. */
  2524. Quaternion.prototype.conjugateInPlace = function () {
  2525. this.x *= -1;
  2526. this.y *= -1;
  2527. this.z *= -1;
  2528. return this;
  2529. };
  2530. /**
  2531. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2532. */
  2533. Quaternion.prototype.conjugate = function () {
  2534. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2535. return result;
  2536. };
  2537. /**
  2538. * Returns the Quaternion length (float).
  2539. */
  2540. Quaternion.prototype.length = function () {
  2541. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2542. };
  2543. /**
  2544. * Normalize in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.normalize = function () {
  2548. var length = 1.0 / this.length();
  2549. this.x *= length;
  2550. this.y *= length;
  2551. this.z *= length;
  2552. this.w *= length;
  2553. return this;
  2554. };
  2555. /**
  2556. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2557. */
  2558. Quaternion.prototype.toEulerAngles = function (order) {
  2559. if (order === void 0) { order = "YZX"; }
  2560. var result = Vector3.Zero();
  2561. this.toEulerAnglesToRef(result, order);
  2562. return result;
  2563. };
  2564. /**
  2565. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2566. * Returns the current Quaternion.
  2567. */
  2568. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2569. if (order === void 0) { order = "YZX"; }
  2570. var qz = this.z;
  2571. var qx = this.x;
  2572. var qy = this.y;
  2573. var qw = this.w;
  2574. var sqw = qw * qw;
  2575. var sqz = qz * qz;
  2576. var sqx = qx * qx;
  2577. var sqy = qy * qy;
  2578. var zAxisY = qy * qz - qx * qw;
  2579. var limit = .4999999;
  2580. if (zAxisY < -limit) {
  2581. result.y = 2 * Math.atan2(qy, qw);
  2582. result.x = Math.PI / 2;
  2583. result.z = 0;
  2584. }
  2585. else if (zAxisY > limit) {
  2586. result.y = 2 * Math.atan2(qy, qw);
  2587. result.x = -Math.PI / 2;
  2588. result.z = 0;
  2589. }
  2590. else {
  2591. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2592. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2593. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2594. }
  2595. return this;
  2596. };
  2597. /**
  2598. * Updates the passed rotation matrix with the current Quaternion values.
  2599. * Returns the current Quaternion.
  2600. */
  2601. Quaternion.prototype.toRotationMatrix = function (result) {
  2602. var xx = this.x * this.x;
  2603. var yy = this.y * this.y;
  2604. var zz = this.z * this.z;
  2605. var xy = this.x * this.y;
  2606. var zw = this.z * this.w;
  2607. var zx = this.z * this.x;
  2608. var yw = this.y * this.w;
  2609. var yz = this.y * this.z;
  2610. var xw = this.x * this.w;
  2611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2612. result.m[1] = 2.0 * (xy + zw);
  2613. result.m[2] = 2.0 * (zx - yw);
  2614. result.m[3] = 0;
  2615. result.m[4] = 2.0 * (xy - zw);
  2616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2617. result.m[6] = 2.0 * (yz + xw);
  2618. result.m[7] = 0;
  2619. result.m[8] = 2.0 * (zx + yw);
  2620. result.m[9] = 2.0 * (yz - xw);
  2621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2622. result.m[11] = 0;
  2623. result.m[12] = 0;
  2624. result.m[13] = 0;
  2625. result.m[14] = 0;
  2626. result.m[15] = 1.0;
  2627. result._markAsUpdated();
  2628. return this;
  2629. };
  2630. /**
  2631. * Updates the current Quaternion from the passed rotation matrix values.
  2632. * Returns the updated Quaternion.
  2633. */
  2634. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2635. Quaternion.FromRotationMatrixToRef(matrix, this);
  2636. return this;
  2637. };
  2638. // Statics
  2639. /**
  2640. * Returns a new Quaternion set from the passed rotation matrix values.
  2641. */
  2642. Quaternion.FromRotationMatrix = function (matrix) {
  2643. var result = new Quaternion();
  2644. Quaternion.FromRotationMatrixToRef(matrix, result);
  2645. return result;
  2646. };
  2647. /**
  2648. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2649. */
  2650. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2651. var data = matrix.m;
  2652. var m11 = data[0], m12 = data[4], m13 = data[8];
  2653. var m21 = data[1], m22 = data[5], m23 = data[9];
  2654. var m31 = data[2], m32 = data[6], m33 = data[10];
  2655. var trace = m11 + m22 + m33;
  2656. var s;
  2657. if (trace > 0) {
  2658. s = 0.5 / Math.sqrt(trace + 1.0);
  2659. result.w = 0.25 / s;
  2660. result.x = (m32 - m23) * s;
  2661. result.y = (m13 - m31) * s;
  2662. result.z = (m21 - m12) * s;
  2663. }
  2664. else if (m11 > m22 && m11 > m33) {
  2665. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2666. result.w = (m32 - m23) / s;
  2667. result.x = 0.25 * s;
  2668. result.y = (m12 + m21) / s;
  2669. result.z = (m13 + m31) / s;
  2670. }
  2671. else if (m22 > m33) {
  2672. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2673. result.w = (m13 - m31) / s;
  2674. result.x = (m12 + m21) / s;
  2675. result.y = 0.25 * s;
  2676. result.z = (m23 + m32) / s;
  2677. }
  2678. else {
  2679. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2680. result.w = (m21 - m12) / s;
  2681. result.x = (m13 + m31) / s;
  2682. result.y = (m23 + m32) / s;
  2683. result.z = 0.25 * s;
  2684. }
  2685. };
  2686. /**
  2687. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2688. */
  2689. Quaternion.Zero = function () {
  2690. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2691. };
  2692. /**
  2693. * Returns a new Quaternion as the inverted current Quaternion.
  2694. */
  2695. Quaternion.Inverse = function (q) {
  2696. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2697. };
  2698. /**
  2699. * Returns the identity Quaternion.
  2700. */
  2701. Quaternion.Identity = function () {
  2702. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2703. };
  2704. Quaternion.IsIdentity = function (quaternion) {
  2705. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2706. };
  2707. /**
  2708. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2709. */
  2710. Quaternion.RotationAxis = function (axis, angle) {
  2711. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2712. };
  2713. /**
  2714. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2715. */
  2716. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2717. var sin = Math.sin(angle / 2);
  2718. axis.normalize();
  2719. result.w = Math.cos(angle / 2);
  2720. result.x = axis.x * sin;
  2721. result.y = axis.y * sin;
  2722. result.z = axis.z * sin;
  2723. return result;
  2724. };
  2725. /**
  2726. * Retuns a new Quaternion set from the starting index of the passed array.
  2727. */
  2728. Quaternion.FromArray = function (array, offset) {
  2729. if (!offset) {
  2730. offset = 0;
  2731. }
  2732. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2733. };
  2734. /**
  2735. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2736. */
  2737. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2738. var q = new Quaternion();
  2739. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2740. return q;
  2741. };
  2742. /**
  2743. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2744. */
  2745. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2746. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2747. var halfRoll = roll * 0.5;
  2748. var halfPitch = pitch * 0.5;
  2749. var halfYaw = yaw * 0.5;
  2750. var sinRoll = Math.sin(halfRoll);
  2751. var cosRoll = Math.cos(halfRoll);
  2752. var sinPitch = Math.sin(halfPitch);
  2753. var cosPitch = Math.cos(halfPitch);
  2754. var sinYaw = Math.sin(halfYaw);
  2755. var cosYaw = Math.cos(halfYaw);
  2756. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2757. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2758. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2759. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2760. };
  2761. /**
  2762. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2763. */
  2764. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2765. var result = new Quaternion();
  2766. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2767. return result;
  2768. };
  2769. /**
  2770. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2771. */
  2772. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2773. // Produces a quaternion from Euler angles in the z-x-z orientation
  2774. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2775. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2776. var halfBeta = beta * 0.5;
  2777. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2778. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2779. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2780. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2781. };
  2782. /**
  2783. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2784. * cf to Vector3.RotationFromAxis() documentation.
  2785. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2786. */
  2787. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2788. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2789. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2790. return quat;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2794. * cf to Vector3.RotationFromAxis() documentation.
  2795. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2796. */
  2797. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2798. var rotMat = MathTmp.Matrix[0];
  2799. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2800. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2801. };
  2802. Quaternion.Slerp = function (left, right, amount) {
  2803. var result = Quaternion.Identity();
  2804. Quaternion.SlerpToRef(left, right, amount, result);
  2805. return result;
  2806. };
  2807. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2808. var num2;
  2809. var num3;
  2810. var num = amount;
  2811. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2812. var flag = false;
  2813. if (num4 < 0) {
  2814. flag = true;
  2815. num4 = -num4;
  2816. }
  2817. if (num4 > 0.999999) {
  2818. num3 = 1 - num;
  2819. num2 = flag ? -num : num;
  2820. }
  2821. else {
  2822. var num5 = Math.acos(num4);
  2823. var num6 = (1.0 / Math.sin(num5));
  2824. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2825. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2826. }
  2827. result.x = (num3 * left.x) + (num2 * right.x);
  2828. result.y = (num3 * left.y) + (num2 * right.y);
  2829. result.z = (num3 * left.z) + (num2 * right.z);
  2830. result.w = (num3 * left.w) + (num2 * right.w);
  2831. };
  2832. /**
  2833. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2834. */
  2835. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2836. var squared = amount * amount;
  2837. var cubed = amount * squared;
  2838. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2839. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2840. var part3 = (cubed - (2.0 * squared)) + amount;
  2841. var part4 = cubed - squared;
  2842. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2843. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2844. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2845. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2846. return new Quaternion(x, y, z, w);
  2847. };
  2848. return Quaternion;
  2849. }());
  2850. BABYLON.Quaternion = Quaternion;
  2851. var Matrix = (function () {
  2852. function Matrix() {
  2853. this._isIdentity = false;
  2854. this._isIdentityDirty = true;
  2855. this.m = new Float32Array(16);
  2856. this._markAsUpdated();
  2857. }
  2858. Matrix.prototype._markAsUpdated = function () {
  2859. this.updateFlag = Matrix._updateFlagSeed++;
  2860. this._isIdentityDirty = true;
  2861. };
  2862. // Properties
  2863. /**
  2864. * Boolean : True is the matrix is the identity matrix
  2865. */
  2866. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2867. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2868. if (this._isIdentityDirty) {
  2869. this._isIdentityDirty = false;
  2870. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2871. this._isIdentity = false;
  2872. }
  2873. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2874. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2875. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2876. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2877. this._isIdentity = false;
  2878. }
  2879. else {
  2880. this._isIdentity = true;
  2881. }
  2882. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2883. this._isIdentity = false;
  2884. }
  2885. }
  2886. return this._isIdentity;
  2887. };
  2888. /**
  2889. * Returns the matrix determinant (float).
  2890. */
  2891. Matrix.prototype.determinant = function () {
  2892. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2893. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2894. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2895. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2896. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2897. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2898. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2899. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2900. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2901. };
  2902. // Methods
  2903. /**
  2904. * Returns the matrix underlying array.
  2905. */
  2906. Matrix.prototype.toArray = function () {
  2907. return this.m;
  2908. };
  2909. /**
  2910. * Returns the matrix underlying array.
  2911. */
  2912. Matrix.prototype.asArray = function () {
  2913. return this.toArray();
  2914. };
  2915. /**
  2916. * Inverts in place the Matrix.
  2917. * Returns the Matrix inverted.
  2918. */
  2919. Matrix.prototype.invert = function () {
  2920. this.invertToRef(this);
  2921. return this;
  2922. };
  2923. /**
  2924. * Sets all the matrix elements to zero.
  2925. * Returns the Matrix.
  2926. */
  2927. Matrix.prototype.reset = function () {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = 0.0;
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2936. */
  2937. Matrix.prototype.add = function (other) {
  2938. var result = new Matrix();
  2939. this.addToRef(other, result);
  2940. return result;
  2941. };
  2942. /**
  2943. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.addToRef = function (other, result) {
  2947. for (var index = 0; index < 16; index++) {
  2948. result.m[index] = this.m[index] + other.m[index];
  2949. }
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Adds in place the passed matrix to the current Matrix.
  2955. * Returns the updated Matrix.
  2956. */
  2957. Matrix.prototype.addToSelf = function (other) {
  2958. for (var index = 0; index < 16; index++) {
  2959. this.m[index] += other.m[index];
  2960. }
  2961. this._markAsUpdated();
  2962. return this;
  2963. };
  2964. /**
  2965. * Sets the passed matrix with the current inverted Matrix.
  2966. * Returns the unmodified current Matrix.
  2967. */
  2968. Matrix.prototype.invertToRef = function (other) {
  2969. var l1 = this.m[0];
  2970. var l2 = this.m[1];
  2971. var l3 = this.m[2];
  2972. var l4 = this.m[3];
  2973. var l5 = this.m[4];
  2974. var l6 = this.m[5];
  2975. var l7 = this.m[6];
  2976. var l8 = this.m[7];
  2977. var l9 = this.m[8];
  2978. var l10 = this.m[9];
  2979. var l11 = this.m[10];
  2980. var l12 = this.m[11];
  2981. var l13 = this.m[12];
  2982. var l14 = this.m[13];
  2983. var l15 = this.m[14];
  2984. var l16 = this.m[15];
  2985. var l17 = (l11 * l16) - (l12 * l15);
  2986. var l18 = (l10 * l16) - (l12 * l14);
  2987. var l19 = (l10 * l15) - (l11 * l14);
  2988. var l20 = (l9 * l16) - (l12 * l13);
  2989. var l21 = (l9 * l15) - (l11 * l13);
  2990. var l22 = (l9 * l14) - (l10 * l13);
  2991. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2992. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2993. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2994. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2995. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2996. var l28 = (l7 * l16) - (l8 * l15);
  2997. var l29 = (l6 * l16) - (l8 * l14);
  2998. var l30 = (l6 * l15) - (l7 * l14);
  2999. var l31 = (l5 * l16) - (l8 * l13);
  3000. var l32 = (l5 * l15) - (l7 * l13);
  3001. var l33 = (l5 * l14) - (l6 * l13);
  3002. var l34 = (l7 * l12) - (l8 * l11);
  3003. var l35 = (l6 * l12) - (l8 * l10);
  3004. var l36 = (l6 * l11) - (l7 * l10);
  3005. var l37 = (l5 * l12) - (l8 * l9);
  3006. var l38 = (l5 * l11) - (l7 * l9);
  3007. var l39 = (l5 * l10) - (l6 * l9);
  3008. other.m[0] = l23 * l27;
  3009. other.m[4] = l24 * l27;
  3010. other.m[8] = l25 * l27;
  3011. other.m[12] = l26 * l27;
  3012. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3013. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3014. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3015. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3016. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3017. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3018. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3019. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3020. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3021. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3022. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3023. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3024. other._markAsUpdated();
  3025. return this;
  3026. };
  3027. /**
  3028. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3029. * Returns the updated Matrix.
  3030. */
  3031. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3032. this.m[12] = x;
  3033. this.m[13] = y;
  3034. this.m[14] = z;
  3035. this._markAsUpdated();
  3036. return this;
  3037. };
  3038. /**
  3039. * Inserts the translation vector in the current Matrix.
  3040. * Returns the updated Matrix.
  3041. */
  3042. Matrix.prototype.setTranslation = function (vector3) {
  3043. this.m[12] = vector3.x;
  3044. this.m[13] = vector3.y;
  3045. this.m[14] = vector3.z;
  3046. this._markAsUpdated();
  3047. return this;
  3048. };
  3049. /**
  3050. * Returns a new Vector3 as the extracted translation from the Matrix.
  3051. */
  3052. Matrix.prototype.getTranslation = function () {
  3053. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3054. };
  3055. /**
  3056. * Fill a Vector3 with the extracted translation from the Matrix.
  3057. */
  3058. Matrix.prototype.getTranslationToRef = function (result) {
  3059. result.x = this.m[12];
  3060. result.y = this.m[13];
  3061. result.z = this.m[14];
  3062. return this;
  3063. };
  3064. /**
  3065. * Remove rotation and scaling part from the Matrix.
  3066. * Returns the updated Matrix.
  3067. */
  3068. Matrix.prototype.removeRotationAndScaling = function () {
  3069. this.setRowFromFloats(0, 1, 0, 0, 0);
  3070. this.setRowFromFloats(1, 0, 1, 0, 0);
  3071. this.setRowFromFloats(2, 0, 0, 1, 0);
  3072. return this;
  3073. };
  3074. /**
  3075. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3076. */
  3077. Matrix.prototype.multiply = function (other) {
  3078. var result = new Matrix();
  3079. this.multiplyToRef(other, result);
  3080. return result;
  3081. };
  3082. /**
  3083. * Updates the current Matrix from the passed one values.
  3084. * Returns the updated Matrix.
  3085. */
  3086. Matrix.prototype.copyFrom = function (other) {
  3087. for (var index = 0; index < 16; index++) {
  3088. this.m[index] = other.m[index];
  3089. }
  3090. this._markAsUpdated();
  3091. return this;
  3092. };
  3093. /**
  3094. * Populates the passed array from the starting index with the Matrix values.
  3095. * Returns the Matrix.
  3096. */
  3097. Matrix.prototype.copyToArray = function (array, offset) {
  3098. if (offset === void 0) { offset = 0; }
  3099. for (var index = 0; index < 16; index++) {
  3100. array[offset + index] = this.m[index];
  3101. }
  3102. return this;
  3103. };
  3104. /**
  3105. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3106. */
  3107. Matrix.prototype.multiplyToRef = function (other, result) {
  3108. this.multiplyToArray(other, result.m, 0);
  3109. result._markAsUpdated();
  3110. return this;
  3111. };
  3112. /**
  3113. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3114. */
  3115. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3116. var tm0 = this.m[0];
  3117. var tm1 = this.m[1];
  3118. var tm2 = this.m[2];
  3119. var tm3 = this.m[3];
  3120. var tm4 = this.m[4];
  3121. var tm5 = this.m[5];
  3122. var tm6 = this.m[6];
  3123. var tm7 = this.m[7];
  3124. var tm8 = this.m[8];
  3125. var tm9 = this.m[9];
  3126. var tm10 = this.m[10];
  3127. var tm11 = this.m[11];
  3128. var tm12 = this.m[12];
  3129. var tm13 = this.m[13];
  3130. var tm14 = this.m[14];
  3131. var tm15 = this.m[15];
  3132. var om0 = other.m[0];
  3133. var om1 = other.m[1];
  3134. var om2 = other.m[2];
  3135. var om3 = other.m[3];
  3136. var om4 = other.m[4];
  3137. var om5 = other.m[5];
  3138. var om6 = other.m[6];
  3139. var om7 = other.m[7];
  3140. var om8 = other.m[8];
  3141. var om9 = other.m[9];
  3142. var om10 = other.m[10];
  3143. var om11 = other.m[11];
  3144. var om12 = other.m[12];
  3145. var om13 = other.m[13];
  3146. var om14 = other.m[14];
  3147. var om15 = other.m[15];
  3148. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3149. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3150. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3151. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3152. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3153. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3154. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3155. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3156. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3157. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3158. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3159. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3160. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3161. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3162. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3163. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3164. return this;
  3165. };
  3166. /**
  3167. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3168. */
  3169. Matrix.prototype.equals = function (value) {
  3170. return value &&
  3171. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3172. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3173. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3174. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3175. };
  3176. /**
  3177. * Returns a new Matrix from the current Matrix.
  3178. */
  3179. Matrix.prototype.clone = function () {
  3180. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3181. };
  3182. /**
  3183. * Returns the string "Matrix"
  3184. */
  3185. Matrix.prototype.getClassName = function () {
  3186. return "Matrix";
  3187. };
  3188. /**
  3189. * Returns the Matrix hash code.
  3190. */
  3191. Matrix.prototype.getHashCode = function () {
  3192. var hash = this.m[0] || 0;
  3193. for (var i = 1; i < 16; i++) {
  3194. hash = (hash * 397) ^ (this.m[i] || 0);
  3195. }
  3196. return hash;
  3197. };
  3198. /**
  3199. * Decomposes the current Matrix into :
  3200. * - a scale vector3 passed as a reference to update,
  3201. * - a rotation quaternion passed as a reference to update,
  3202. * - a translation vector3 passed as a reference to update.
  3203. * Returns the boolean `true`.
  3204. */
  3205. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3206. translation.x = this.m[12];
  3207. translation.y = this.m[13];
  3208. translation.z = this.m[14];
  3209. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3210. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3211. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3212. if (this.determinant() <= 0) {
  3213. scale.y *= -1;
  3214. }
  3215. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3216. rotation.x = 0;
  3217. rotation.y = 0;
  3218. rotation.z = 0;
  3219. rotation.w = 1;
  3220. return false;
  3221. }
  3222. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3223. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3224. return true;
  3225. };
  3226. /**
  3227. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3228. */
  3229. Matrix.prototype.getRotationMatrix = function () {
  3230. var result = Matrix.Identity();
  3231. this.getRotationMatrixToRef(result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3236. * Returns the current Matrix.
  3237. */
  3238. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3239. var m = this.m;
  3240. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3241. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3242. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3243. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3244. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3245. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3246. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3247. return this;
  3248. };
  3249. // Statics
  3250. /**
  3251. * Returns a new Matrix set from the starting index of the passed array.
  3252. */
  3253. Matrix.FromArray = function (array, offset) {
  3254. var result = new Matrix();
  3255. if (!offset) {
  3256. offset = 0;
  3257. }
  3258. Matrix.FromArrayToRef(array, offset, result);
  3259. return result;
  3260. };
  3261. /**
  3262. * Sets the passed "result" matrix from the starting index of the passed array.
  3263. */
  3264. Matrix.FromArrayToRef = function (array, offset, result) {
  3265. for (var index = 0; index < 16; index++) {
  3266. result.m[index] = array[index + offset];
  3267. }
  3268. result._markAsUpdated();
  3269. };
  3270. /**
  3271. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3272. */
  3273. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3274. for (var index = 0; index < 16; index++) {
  3275. result.m[index] = array[index + offset] * scale;
  3276. }
  3277. result._markAsUpdated();
  3278. };
  3279. /**
  3280. * Sets the passed matrix "result" with the 16 passed floats.
  3281. */
  3282. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3283. result.m[0] = initialM11;
  3284. result.m[1] = initialM12;
  3285. result.m[2] = initialM13;
  3286. result.m[3] = initialM14;
  3287. result.m[4] = initialM21;
  3288. result.m[5] = initialM22;
  3289. result.m[6] = initialM23;
  3290. result.m[7] = initialM24;
  3291. result.m[8] = initialM31;
  3292. result.m[9] = initialM32;
  3293. result.m[10] = initialM33;
  3294. result.m[11] = initialM34;
  3295. result.m[12] = initialM41;
  3296. result.m[13] = initialM42;
  3297. result.m[14] = initialM43;
  3298. result.m[15] = initialM44;
  3299. result._markAsUpdated();
  3300. };
  3301. /**
  3302. * Returns the index-th row of the current matrix as a new Vector4.
  3303. */
  3304. Matrix.prototype.getRow = function (index) {
  3305. if (index < 0 || index > 3) {
  3306. return null;
  3307. }
  3308. var i = index * 4;
  3309. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3310. };
  3311. /**
  3312. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3313. * Returns the updated Matrix.
  3314. */
  3315. Matrix.prototype.setRow = function (index, row) {
  3316. if (index < 0 || index > 3) {
  3317. return this;
  3318. }
  3319. var i = index * 4;
  3320. this.m[i + 0] = row.x;
  3321. this.m[i + 1] = row.y;
  3322. this.m[i + 2] = row.z;
  3323. this.m[i + 3] = row.w;
  3324. this._markAsUpdated();
  3325. return this;
  3326. };
  3327. /**
  3328. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3329. * Returns the updated Matrix.
  3330. */
  3331. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3332. if (index < 0 || index > 3) {
  3333. return this;
  3334. }
  3335. var i = index * 4;
  3336. this.m[i + 0] = x;
  3337. this.m[i + 1] = y;
  3338. this.m[i + 2] = z;
  3339. this.m[i + 3] = w;
  3340. this._markAsUpdated();
  3341. return this;
  3342. };
  3343. /**
  3344. * Returns a new Matrix set from the 16 passed floats.
  3345. */
  3346. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3347. var result = new Matrix();
  3348. result.m[0] = initialM11;
  3349. result.m[1] = initialM12;
  3350. result.m[2] = initialM13;
  3351. result.m[3] = initialM14;
  3352. result.m[4] = initialM21;
  3353. result.m[5] = initialM22;
  3354. result.m[6] = initialM23;
  3355. result.m[7] = initialM24;
  3356. result.m[8] = initialM31;
  3357. result.m[9] = initialM32;
  3358. result.m[10] = initialM33;
  3359. result.m[11] = initialM34;
  3360. result.m[12] = initialM41;
  3361. result.m[13] = initialM42;
  3362. result.m[14] = initialM43;
  3363. result.m[15] = initialM44;
  3364. return result;
  3365. };
  3366. /**
  3367. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3368. */
  3369. Matrix.Compose = function (scale, rotation, translation) {
  3370. var result = Matrix.Identity();
  3371. Matrix.ComposeToRef(scale, rotation, translation, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3376. */
  3377. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3378. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3379. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3380. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3381. result.setTranslation(translation);
  3382. };
  3383. /**
  3384. * Returns a new indentity Matrix.
  3385. */
  3386. Matrix.Identity = function () {
  3387. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3388. };
  3389. /**
  3390. * Sets the passed "result" as an identity matrix.
  3391. */
  3392. Matrix.IdentityToRef = function (result) {
  3393. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3394. };
  3395. /**
  3396. * Returns a new zero Matrix.
  3397. */
  3398. Matrix.Zero = function () {
  3399. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3400. };
  3401. /**
  3402. * Returns a new rotation matrix for "angle" radians around the X axis.
  3403. */
  3404. Matrix.RotationX = function (angle) {
  3405. var result = new Matrix();
  3406. Matrix.RotationXToRef(angle, result);
  3407. return result;
  3408. };
  3409. /**
  3410. * Returns a new Matrix as the passed inverted one.
  3411. */
  3412. Matrix.Invert = function (source) {
  3413. var result = new Matrix();
  3414. source.invertToRef(result);
  3415. return result;
  3416. };
  3417. /**
  3418. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3419. */
  3420. Matrix.RotationXToRef = function (angle, result) {
  3421. var s = Math.sin(angle);
  3422. var c = Math.cos(angle);
  3423. result.m[0] = 1.0;
  3424. result.m[15] = 1.0;
  3425. result.m[5] = c;
  3426. result.m[10] = c;
  3427. result.m[9] = -s;
  3428. result.m[6] = s;
  3429. result.m[1] = 0.0;
  3430. result.m[2] = 0.0;
  3431. result.m[3] = 0.0;
  3432. result.m[4] = 0.0;
  3433. result.m[7] = 0.0;
  3434. result.m[8] = 0.0;
  3435. result.m[11] = 0.0;
  3436. result.m[12] = 0.0;
  3437. result.m[13] = 0.0;
  3438. result.m[14] = 0.0;
  3439. result._markAsUpdated();
  3440. };
  3441. /**
  3442. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3443. */
  3444. Matrix.RotationY = function (angle) {
  3445. var result = new Matrix();
  3446. Matrix.RotationYToRef(angle, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3451. */
  3452. Matrix.RotationYToRef = function (angle, result) {
  3453. var s = Math.sin(angle);
  3454. var c = Math.cos(angle);
  3455. result.m[5] = 1.0;
  3456. result.m[15] = 1.0;
  3457. result.m[0] = c;
  3458. result.m[2] = -s;
  3459. result.m[8] = s;
  3460. result.m[10] = c;
  3461. result.m[1] = 0.0;
  3462. result.m[3] = 0.0;
  3463. result.m[4] = 0.0;
  3464. result.m[6] = 0.0;
  3465. result.m[7] = 0.0;
  3466. result.m[9] = 0.0;
  3467. result.m[11] = 0.0;
  3468. result.m[12] = 0.0;
  3469. result.m[13] = 0.0;
  3470. result.m[14] = 0.0;
  3471. result._markAsUpdated();
  3472. };
  3473. /**
  3474. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3475. */
  3476. Matrix.RotationZ = function (angle) {
  3477. var result = new Matrix();
  3478. Matrix.RotationZToRef(angle, result);
  3479. return result;
  3480. };
  3481. /**
  3482. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3483. */
  3484. Matrix.RotationZToRef = function (angle, result) {
  3485. var s = Math.sin(angle);
  3486. var c = Math.cos(angle);
  3487. result.m[10] = 1.0;
  3488. result.m[15] = 1.0;
  3489. result.m[0] = c;
  3490. result.m[1] = s;
  3491. result.m[4] = -s;
  3492. result.m[5] = c;
  3493. result.m[2] = 0.0;
  3494. result.m[3] = 0.0;
  3495. result.m[6] = 0.0;
  3496. result.m[7] = 0.0;
  3497. result.m[8] = 0.0;
  3498. result.m[9] = 0.0;
  3499. result.m[11] = 0.0;
  3500. result.m[12] = 0.0;
  3501. result.m[13] = 0.0;
  3502. result.m[14] = 0.0;
  3503. result._markAsUpdated();
  3504. };
  3505. /**
  3506. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3507. */
  3508. Matrix.RotationAxis = function (axis, angle) {
  3509. var result = Matrix.Zero();
  3510. Matrix.RotationAxisToRef(axis, angle, result);
  3511. return result;
  3512. };
  3513. /**
  3514. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3515. */
  3516. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3517. var s = Math.sin(-angle);
  3518. var c = Math.cos(-angle);
  3519. var c1 = 1 - c;
  3520. axis.normalize();
  3521. result.m[0] = (axis.x * axis.x) * c1 + c;
  3522. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3523. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3524. result.m[3] = 0.0;
  3525. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3526. result.m[5] = (axis.y * axis.y) * c1 + c;
  3527. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3528. result.m[7] = 0.0;
  3529. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3530. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3531. result.m[10] = (axis.z * axis.z) * c1 + c;
  3532. result.m[11] = 0.0;
  3533. result.m[15] = 1.0;
  3534. result._markAsUpdated();
  3535. };
  3536. /**
  3537. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3538. */
  3539. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3540. var result = new Matrix();
  3541. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3546. */
  3547. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3548. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3549. this._tempQuaternion.toRotationMatrix(result);
  3550. };
  3551. /**
  3552. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3553. */
  3554. Matrix.Scaling = function (x, y, z) {
  3555. var result = Matrix.Zero();
  3556. Matrix.ScalingToRef(x, y, z, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3561. */
  3562. Matrix.ScalingToRef = function (x, y, z, result) {
  3563. result.m[0] = x;
  3564. result.m[1] = 0.0;
  3565. result.m[2] = 0.0;
  3566. result.m[3] = 0.0;
  3567. result.m[4] = 0.0;
  3568. result.m[5] = y;
  3569. result.m[6] = 0.0;
  3570. result.m[7] = 0.0;
  3571. result.m[8] = 0.0;
  3572. result.m[9] = 0.0;
  3573. result.m[10] = z;
  3574. result.m[11] = 0.0;
  3575. result.m[12] = 0.0;
  3576. result.m[13] = 0.0;
  3577. result.m[14] = 0.0;
  3578. result.m[15] = 1.0;
  3579. result._markAsUpdated();
  3580. };
  3581. /**
  3582. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3583. */
  3584. Matrix.Translation = function (x, y, z) {
  3585. var result = Matrix.Identity();
  3586. Matrix.TranslationToRef(x, y, z, result);
  3587. return result;
  3588. };
  3589. /**
  3590. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3591. */
  3592. Matrix.TranslationToRef = function (x, y, z, result) {
  3593. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3594. };
  3595. /**
  3596. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3597. */
  3598. Matrix.Lerp = function (startValue, endValue, gradient) {
  3599. var result = Matrix.Zero();
  3600. for (var index = 0; index < 16; index++) {
  3601. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3602. }
  3603. result._markAsUpdated();
  3604. return result;
  3605. };
  3606. /**
  3607. * Returns a new Matrix whose values are computed by :
  3608. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3609. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3610. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3611. */
  3612. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3613. var startScale = new Vector3(0, 0, 0);
  3614. var startRotation = new Quaternion();
  3615. var startTranslation = new Vector3(0, 0, 0);
  3616. startValue.decompose(startScale, startRotation, startTranslation);
  3617. var endScale = new Vector3(0, 0, 0);
  3618. var endRotation = new Quaternion();
  3619. var endTranslation = new Vector3(0, 0, 0);
  3620. endValue.decompose(endScale, endRotation, endTranslation);
  3621. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3622. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3623. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3624. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3625. };
  3626. /**
  3627. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3628. * This methods works for a Left-Handed system.
  3629. */
  3630. Matrix.LookAtLH = function (eye, target, up) {
  3631. var result = Matrix.Zero();
  3632. Matrix.LookAtLHToRef(eye, target, up, result);
  3633. return result;
  3634. };
  3635. /**
  3636. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3637. * This methods works for a Left-Handed system.
  3638. */
  3639. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3640. // Z axis
  3641. target.subtractToRef(eye, this._zAxis);
  3642. this._zAxis.normalize();
  3643. // X axis
  3644. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3645. if (this._xAxis.lengthSquared() === 0) {
  3646. this._xAxis.x = 1.0;
  3647. }
  3648. else {
  3649. this._xAxis.normalize();
  3650. }
  3651. // Y axis
  3652. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3653. this._yAxis.normalize();
  3654. // Eye angles
  3655. var ex = -Vector3.Dot(this._xAxis, eye);
  3656. var ey = -Vector3.Dot(this._yAxis, eye);
  3657. var ez = -Vector3.Dot(this._zAxis, eye);
  3658. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3659. };
  3660. /**
  3661. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3662. * This methods works for a Right-Handed system.
  3663. */
  3664. Matrix.LookAtRH = function (eye, target, up) {
  3665. var result = Matrix.Zero();
  3666. Matrix.LookAtRHToRef(eye, target, up, result);
  3667. return result;
  3668. };
  3669. /**
  3670. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3671. * This methods works for a Left-Handed system.
  3672. */
  3673. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3674. // Z axis
  3675. eye.subtractToRef(target, this._zAxis);
  3676. this._zAxis.normalize();
  3677. // X axis
  3678. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3679. if (this._xAxis.lengthSquared() === 0) {
  3680. this._xAxis.x = 1.0;
  3681. }
  3682. else {
  3683. this._xAxis.normalize();
  3684. }
  3685. // Y axis
  3686. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3687. this._yAxis.normalize();
  3688. // Eye angles
  3689. var ex = -Vector3.Dot(this._xAxis, eye);
  3690. var ey = -Vector3.Dot(this._yAxis, eye);
  3691. var ez = -Vector3.Dot(this._zAxis, eye);
  3692. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3693. };
  3694. /**
  3695. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3696. */
  3697. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3698. var matrix = Matrix.Zero();
  3699. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3700. return matrix;
  3701. };
  3702. /**
  3703. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3704. */
  3705. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3706. var n = znear;
  3707. var f = zfar;
  3708. var a = 2.0 / width;
  3709. var b = 2.0 / height;
  3710. var c = 2.0 / (f - n);
  3711. var d = -(f + n) / (f - n);
  3712. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3713. };
  3714. /**
  3715. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3716. */
  3717. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3718. var matrix = Matrix.Zero();
  3719. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3720. return matrix;
  3721. };
  3722. /**
  3723. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3724. */
  3725. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3726. var n = znear;
  3727. var f = zfar;
  3728. var a = 2.0 / (right - left);
  3729. var b = 2.0 / (top - bottom);
  3730. var c = 2.0 / (f - n);
  3731. var d = -(f + n) / (f - n);
  3732. var i0 = (left + right) / (left - right);
  3733. var i1 = (top + bottom) / (bottom - top);
  3734. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3735. };
  3736. /**
  3737. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3738. */
  3739. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3740. var matrix = Matrix.Zero();
  3741. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3742. return matrix;
  3743. };
  3744. /**
  3745. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3746. */
  3747. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3748. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3749. result.m[10] *= -1.0;
  3750. };
  3751. /**
  3752. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3753. */
  3754. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3755. var matrix = Matrix.Zero();
  3756. var n = znear;
  3757. var f = zfar;
  3758. var a = 2.0 * n / width;
  3759. var b = 2.0 * n / height;
  3760. var c = (f + n) / (f - n);
  3761. var d = -2.0 * f * n / (f - n);
  3762. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3763. return matrix;
  3764. };
  3765. /**
  3766. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3767. */
  3768. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3769. var matrix = Matrix.Zero();
  3770. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3771. return matrix;
  3772. };
  3773. /**
  3774. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3775. */
  3776. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3777. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3778. var n = znear;
  3779. var f = zfar;
  3780. var t = 1.0 / (Math.tan(fov * 0.5));
  3781. var a = isVerticalFovFixed ? (t / aspect) : t;
  3782. var b = isVerticalFovFixed ? t : (t * aspect);
  3783. var c = (f + n) / (f - n);
  3784. var d = -2.0 * f * n / (f - n);
  3785. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3786. };
  3787. /**
  3788. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3789. */
  3790. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3791. var matrix = Matrix.Zero();
  3792. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3793. return matrix;
  3794. };
  3795. /**
  3796. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3797. */
  3798. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3799. //alternatively this could be expressed as:
  3800. // m = PerspectiveFovLHToRef
  3801. // m[10] *= -1.0;
  3802. // m[11] *= -1.0;
  3803. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3804. var n = znear;
  3805. var f = zfar;
  3806. var t = 1.0 / (Math.tan(fov * 0.5));
  3807. var a = isVerticalFovFixed ? (t / aspect) : t;
  3808. var b = isVerticalFovFixed ? t : (t * aspect);
  3809. var c = -(f + n) / (f - n);
  3810. var d = -2 * f * n / (f - n);
  3811. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3812. };
  3813. /**
  3814. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3815. */
  3816. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3817. if (rightHanded === void 0) { rightHanded = false; }
  3818. var rightHandedFactor = rightHanded ? -1 : 1;
  3819. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3820. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3821. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3822. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3823. var xScale = 2.0 / (leftTan + rightTan);
  3824. var yScale = 2.0 / (upTan + downTan);
  3825. result.m[0] = xScale;
  3826. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3827. result.m[5] = yScale;
  3828. result.m[6] = result.m[7] = 0.0;
  3829. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3830. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3831. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3832. result.m[10] = -zfar / (znear - zfar);
  3833. result.m[11] = 1.0 * rightHandedFactor;
  3834. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3835. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3836. // result.m[14] = (znear * zfar) / (znear - zfar);
  3837. result._markAsUpdated();
  3838. };
  3839. /**
  3840. * Returns the final transformation matrix : world * view * projection * viewport
  3841. */
  3842. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3843. var cw = viewport.width;
  3844. var ch = viewport.height;
  3845. var cx = viewport.x;
  3846. var cy = viewport.y;
  3847. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3848. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3849. };
  3850. /**
  3851. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3852. */
  3853. Matrix.GetAsMatrix2x2 = function (matrix) {
  3854. return new Float32Array([
  3855. matrix.m[0], matrix.m[1],
  3856. matrix.m[4], matrix.m[5]
  3857. ]);
  3858. };
  3859. /**
  3860. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3861. */
  3862. Matrix.GetAsMatrix3x3 = function (matrix) {
  3863. return new Float32Array([
  3864. matrix.m[0], matrix.m[1], matrix.m[2],
  3865. matrix.m[4], matrix.m[5], matrix.m[6],
  3866. matrix.m[8], matrix.m[9], matrix.m[10]
  3867. ]);
  3868. };
  3869. /**
  3870. * Compute the transpose of the passed Matrix.
  3871. * Returns a new Matrix.
  3872. */
  3873. Matrix.Transpose = function (matrix) {
  3874. var result = new Matrix();
  3875. result.m[0] = matrix.m[0];
  3876. result.m[1] = matrix.m[4];
  3877. result.m[2] = matrix.m[8];
  3878. result.m[3] = matrix.m[12];
  3879. result.m[4] = matrix.m[1];
  3880. result.m[5] = matrix.m[5];
  3881. result.m[6] = matrix.m[9];
  3882. result.m[7] = matrix.m[13];
  3883. result.m[8] = matrix.m[2];
  3884. result.m[9] = matrix.m[6];
  3885. result.m[10] = matrix.m[10];
  3886. result.m[11] = matrix.m[14];
  3887. result.m[12] = matrix.m[3];
  3888. result.m[13] = matrix.m[7];
  3889. result.m[14] = matrix.m[11];
  3890. result.m[15] = matrix.m[15];
  3891. return result;
  3892. };
  3893. /**
  3894. * Returns a new Matrix as the reflection matrix across the passed plane.
  3895. */
  3896. Matrix.Reflection = function (plane) {
  3897. var matrix = new Matrix();
  3898. Matrix.ReflectionToRef(plane, matrix);
  3899. return matrix;
  3900. };
  3901. /**
  3902. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3903. */
  3904. Matrix.ReflectionToRef = function (plane, result) {
  3905. plane.normalize();
  3906. var x = plane.normal.x;
  3907. var y = plane.normal.y;
  3908. var z = plane.normal.z;
  3909. var temp = -2 * x;
  3910. var temp2 = -2 * y;
  3911. var temp3 = -2 * z;
  3912. result.m[0] = (temp * x) + 1;
  3913. result.m[1] = temp2 * x;
  3914. result.m[2] = temp3 * x;
  3915. result.m[3] = 0.0;
  3916. result.m[4] = temp * y;
  3917. result.m[5] = (temp2 * y) + 1;
  3918. result.m[6] = temp3 * y;
  3919. result.m[7] = 0.0;
  3920. result.m[8] = temp * z;
  3921. result.m[9] = temp2 * z;
  3922. result.m[10] = (temp3 * z) + 1;
  3923. result.m[11] = 0.0;
  3924. result.m[12] = temp * plane.d;
  3925. result.m[13] = temp2 * plane.d;
  3926. result.m[14] = temp3 * plane.d;
  3927. result.m[15] = 1.0;
  3928. result._markAsUpdated();
  3929. };
  3930. /**
  3931. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3932. */
  3933. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3934. result.m[0] = xaxis.x;
  3935. result.m[1] = xaxis.y;
  3936. result.m[2] = xaxis.z;
  3937. result.m[3] = 0.0;
  3938. result.m[4] = yaxis.x;
  3939. result.m[5] = yaxis.y;
  3940. result.m[6] = yaxis.z;
  3941. result.m[7] = 0.0;
  3942. result.m[8] = zaxis.x;
  3943. result.m[9] = zaxis.y;
  3944. result.m[10] = zaxis.z;
  3945. result.m[11] = 0.0;
  3946. result.m[12] = 0.0;
  3947. result.m[13] = 0.0;
  3948. result.m[14] = 0.0;
  3949. result.m[15] = 1.0;
  3950. result._markAsUpdated();
  3951. };
  3952. /**
  3953. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3954. */
  3955. Matrix.FromQuaternionToRef = function (quat, result) {
  3956. var xx = quat.x * quat.x;
  3957. var yy = quat.y * quat.y;
  3958. var zz = quat.z * quat.z;
  3959. var xy = quat.x * quat.y;
  3960. var zw = quat.z * quat.w;
  3961. var zx = quat.z * quat.x;
  3962. var yw = quat.y * quat.w;
  3963. var yz = quat.y * quat.z;
  3964. var xw = quat.x * quat.w;
  3965. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3966. result.m[1] = 2.0 * (xy + zw);
  3967. result.m[2] = 2.0 * (zx - yw);
  3968. result.m[3] = 0.0;
  3969. result.m[4] = 2.0 * (xy - zw);
  3970. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3971. result.m[6] = 2.0 * (yz + xw);
  3972. result.m[7] = 0.0;
  3973. result.m[8] = 2.0 * (zx + yw);
  3974. result.m[9] = 2.0 * (yz - xw);
  3975. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3976. result.m[11] = 0.0;
  3977. result.m[12] = 0.0;
  3978. result.m[13] = 0.0;
  3979. result.m[14] = 0.0;
  3980. result.m[15] = 1.0;
  3981. result._markAsUpdated();
  3982. };
  3983. Matrix._tempQuaternion = new Quaternion();
  3984. Matrix._xAxis = Vector3.Zero();
  3985. Matrix._yAxis = Vector3.Zero();
  3986. Matrix._zAxis = Vector3.Zero();
  3987. Matrix._updateFlagSeed = 0;
  3988. return Matrix;
  3989. }());
  3990. BABYLON.Matrix = Matrix;
  3991. var Plane = (function () {
  3992. /**
  3993. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3994. */
  3995. function Plane(a, b, c, d) {
  3996. this.normal = new Vector3(a, b, c);
  3997. this.d = d;
  3998. }
  3999. /**
  4000. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4001. */
  4002. Plane.prototype.asArray = function () {
  4003. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4004. };
  4005. // Methods
  4006. /**
  4007. * Returns a new plane copied from the current Plane.
  4008. */
  4009. Plane.prototype.clone = function () {
  4010. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4011. };
  4012. /**
  4013. * Returns the string "Plane".
  4014. */
  4015. Plane.prototype.getClassName = function () {
  4016. return "Plane";
  4017. };
  4018. /**
  4019. * Returns the Plane hash code.
  4020. */
  4021. Plane.prototype.getHashCode = function () {
  4022. var hash = this.normal.getHashCode();
  4023. hash = (hash * 397) ^ (this.d || 0);
  4024. return hash;
  4025. };
  4026. /**
  4027. * Normalize the current Plane in place.
  4028. * Returns the updated Plane.
  4029. */
  4030. Plane.prototype.normalize = function () {
  4031. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4032. var magnitude = 0.0;
  4033. if (norm !== 0) {
  4034. magnitude = 1.0 / norm;
  4035. }
  4036. this.normal.x *= magnitude;
  4037. this.normal.y *= magnitude;
  4038. this.normal.z *= magnitude;
  4039. this.d *= magnitude;
  4040. return this;
  4041. };
  4042. /**
  4043. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4044. */
  4045. Plane.prototype.transform = function (transformation) {
  4046. var transposedMatrix = Matrix.Transpose(transformation);
  4047. var x = this.normal.x;
  4048. var y = this.normal.y;
  4049. var z = this.normal.z;
  4050. var d = this.d;
  4051. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4052. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4053. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4054. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4055. return new Plane(normalX, normalY, normalZ, finalD);
  4056. };
  4057. /**
  4058. * Returns the dot product (float) of the point coordinates and the plane normal.
  4059. */
  4060. Plane.prototype.dotCoordinate = function (point) {
  4061. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4062. };
  4063. /**
  4064. * Updates the current Plane from the plane defined by the three passed points.
  4065. * Returns the updated Plane.
  4066. */
  4067. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4068. var x1 = point2.x - point1.x;
  4069. var y1 = point2.y - point1.y;
  4070. var z1 = point2.z - point1.z;
  4071. var x2 = point3.x - point1.x;
  4072. var y2 = point3.y - point1.y;
  4073. var z2 = point3.z - point1.z;
  4074. var yz = (y1 * z2) - (z1 * y2);
  4075. var xz = (z1 * x2) - (x1 * z2);
  4076. var xy = (x1 * y2) - (y1 * x2);
  4077. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4078. var invPyth;
  4079. if (pyth !== 0) {
  4080. invPyth = 1.0 / pyth;
  4081. }
  4082. else {
  4083. invPyth = 0.0;
  4084. }
  4085. this.normal.x = yz * invPyth;
  4086. this.normal.y = xz * invPyth;
  4087. this.normal.z = xy * invPyth;
  4088. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4089. return this;
  4090. };
  4091. /**
  4092. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4093. */
  4094. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4095. var dot = Vector3.Dot(this.normal, direction);
  4096. return (dot <= epsilon);
  4097. };
  4098. /**
  4099. * Returns the signed distance (float) from the passed point to the Plane.
  4100. */
  4101. Plane.prototype.signedDistanceTo = function (point) {
  4102. return Vector3.Dot(point, this.normal) + this.d;
  4103. };
  4104. // Statics
  4105. /**
  4106. * Returns a new Plane from the passed array.
  4107. */
  4108. Plane.FromArray = function (array) {
  4109. return new Plane(array[0], array[1], array[2], array[3]);
  4110. };
  4111. /**
  4112. * Returns a new Plane defined by the three passed points.
  4113. */
  4114. Plane.FromPoints = function (point1, point2, point3) {
  4115. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4116. result.copyFromPoints(point1, point2, point3);
  4117. return result;
  4118. };
  4119. /**
  4120. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4121. * Note : the vector "normal" is updated because normalized.
  4122. */
  4123. Plane.FromPositionAndNormal = function (origin, normal) {
  4124. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4125. normal.normalize();
  4126. result.normal = normal;
  4127. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4128. return result;
  4129. };
  4130. /**
  4131. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4132. */
  4133. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4134. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4135. return Vector3.Dot(point, normal) + d;
  4136. };
  4137. return Plane;
  4138. }());
  4139. BABYLON.Plane = Plane;
  4140. var Viewport = (function () {
  4141. /**
  4142. * Creates a Viewport object located at (x, y) and sized (width, height).
  4143. */
  4144. function Viewport(x, y, width, height) {
  4145. this.x = x;
  4146. this.y = y;
  4147. this.width = width;
  4148. this.height = height;
  4149. }
  4150. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4151. if (renderWidthOrEngine.getRenderWidth) {
  4152. var engine = renderWidthOrEngine;
  4153. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4154. }
  4155. var renderWidth = renderWidthOrEngine;
  4156. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4157. };
  4158. /**
  4159. * Returns a new Viewport copied from the current one.
  4160. */
  4161. Viewport.prototype.clone = function () {
  4162. return new Viewport(this.x, this.y, this.width, this.height);
  4163. };
  4164. return Viewport;
  4165. }());
  4166. BABYLON.Viewport = Viewport;
  4167. var Frustum = (function () {
  4168. function Frustum() {
  4169. }
  4170. /**
  4171. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4172. */
  4173. Frustum.GetPlanes = function (transform) {
  4174. var frustumPlanes = [];
  4175. for (var index = 0; index < 6; index++) {
  4176. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4177. }
  4178. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4179. return frustumPlanes;
  4180. };
  4181. /**
  4182. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4183. */
  4184. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4185. // Near
  4186. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4187. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4188. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4189. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4190. frustumPlanes[0].normalize();
  4191. // Far
  4192. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4193. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4194. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4195. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4196. frustumPlanes[1].normalize();
  4197. // Left
  4198. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4199. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4200. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4201. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4202. frustumPlanes[2].normalize();
  4203. // Right
  4204. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4205. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4206. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4207. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4208. frustumPlanes[3].normalize();
  4209. // Top
  4210. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4211. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4212. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4213. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4214. frustumPlanes[4].normalize();
  4215. // Bottom
  4216. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4217. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4218. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4219. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4220. frustumPlanes[5].normalize();
  4221. };
  4222. return Frustum;
  4223. }());
  4224. BABYLON.Frustum = Frustum;
  4225. var Space;
  4226. (function (Space) {
  4227. Space[Space["LOCAL"] = 0] = "LOCAL";
  4228. Space[Space["WORLD"] = 1] = "WORLD";
  4229. Space[Space["BONE"] = 2] = "BONE";
  4230. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4231. var Axis = (function () {
  4232. function Axis() {
  4233. }
  4234. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4235. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4236. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4237. return Axis;
  4238. }());
  4239. BABYLON.Axis = Axis;
  4240. ;
  4241. var BezierCurve = (function () {
  4242. function BezierCurve() {
  4243. }
  4244. /**
  4245. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4246. */
  4247. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4248. // Extract X (which is equal to time here)
  4249. var f0 = 1 - 3 * x2 + 3 * x1;
  4250. var f1 = 3 * x2 - 6 * x1;
  4251. var f2 = 3 * x1;
  4252. var refinedT = t;
  4253. for (var i = 0; i < 5; i++) {
  4254. var refinedT2 = refinedT * refinedT;
  4255. var refinedT3 = refinedT2 * refinedT;
  4256. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4257. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4258. refinedT -= (x - t) * slope;
  4259. refinedT = Math.min(1, Math.max(0, refinedT));
  4260. }
  4261. // Resolve cubic bezier for the given x
  4262. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4263. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4264. Math.pow(refinedT, 3);
  4265. };
  4266. return BezierCurve;
  4267. }());
  4268. BABYLON.BezierCurve = BezierCurve;
  4269. var Orientation;
  4270. (function (Orientation) {
  4271. Orientation[Orientation["CW"] = 0] = "CW";
  4272. Orientation[Orientation["CCW"] = 1] = "CCW";
  4273. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4274. var Angle = (function () {
  4275. /**
  4276. * Creates an Angle object of "radians" radians (float).
  4277. */
  4278. function Angle(radians) {
  4279. var _this = this;
  4280. /**
  4281. * Returns the Angle value in degrees (float).
  4282. */
  4283. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4284. /**
  4285. * Returns the Angle value in radians (float).
  4286. */
  4287. this.radians = function () { return _this._radians; };
  4288. this._radians = radians;
  4289. if (this._radians < 0.0)
  4290. this._radians += (2.0 * Math.PI);
  4291. }
  4292. /**
  4293. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4294. */
  4295. Angle.BetweenTwoPoints = function (a, b) {
  4296. var delta = b.subtract(a);
  4297. var theta = Math.atan2(delta.y, delta.x);
  4298. return new Angle(theta);
  4299. };
  4300. /**
  4301. * Returns a new Angle object from the passed float in radians.
  4302. */
  4303. Angle.FromRadians = function (radians) {
  4304. return new Angle(radians);
  4305. };
  4306. /**
  4307. * Returns a new Angle object from the passed float in degrees.
  4308. */
  4309. Angle.FromDegrees = function (degrees) {
  4310. return new Angle(degrees * Math.PI / 180.0);
  4311. };
  4312. return Angle;
  4313. }());
  4314. BABYLON.Angle = Angle;
  4315. var Arc2 = (function () {
  4316. /**
  4317. * Creates an Arc object from the three passed points : start, middle and end.
  4318. */
  4319. function Arc2(startPoint, midPoint, endPoint) {
  4320. this.startPoint = startPoint;
  4321. this.midPoint = midPoint;
  4322. this.endPoint = endPoint;
  4323. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4324. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4325. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4326. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4327. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4328. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4329. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4330. var a1 = this.startAngle.degrees();
  4331. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4332. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4333. // angles correction
  4334. if (a2 - a1 > +180.0)
  4335. a2 -= 360.0;
  4336. if (a2 - a1 < -180.0)
  4337. a2 += 360.0;
  4338. if (a3 - a2 > +180.0)
  4339. a3 -= 360.0;
  4340. if (a3 - a2 < -180.0)
  4341. a3 += 360.0;
  4342. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4343. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4344. }
  4345. return Arc2;
  4346. }());
  4347. BABYLON.Arc2 = Arc2;
  4348. var Path2 = (function () {
  4349. /**
  4350. * Creates a Path2 object from the starting 2D coordinates x and y.
  4351. */
  4352. function Path2(x, y) {
  4353. this._points = new Array();
  4354. this._length = 0.0;
  4355. this.closed = false;
  4356. this._points.push(new Vector2(x, y));
  4357. }
  4358. /**
  4359. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4360. * Returns the updated Path2.
  4361. */
  4362. Path2.prototype.addLineTo = function (x, y) {
  4363. if (closed) {
  4364. //Tools.Error("cannot add lines to closed paths");
  4365. return this;
  4366. }
  4367. var newPoint = new Vector2(x, y);
  4368. var previousPoint = this._points[this._points.length - 1];
  4369. this._points.push(newPoint);
  4370. this._length += newPoint.subtract(previousPoint).length();
  4371. return this;
  4372. };
  4373. /**
  4374. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4375. * Returns the updated Path2.
  4376. */
  4377. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4378. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4379. if (closed) {
  4380. //Tools.Error("cannot add arcs to closed paths");
  4381. return this;
  4382. }
  4383. var startPoint = this._points[this._points.length - 1];
  4384. var midPoint = new Vector2(midX, midY);
  4385. var endPoint = new Vector2(endX, endY);
  4386. var arc = new Arc2(startPoint, midPoint, endPoint);
  4387. var increment = arc.angle.radians() / numberOfSegments;
  4388. if (arc.orientation === Orientation.CW)
  4389. increment *= -1;
  4390. var currentAngle = arc.startAngle.radians() + increment;
  4391. for (var i = 0; i < numberOfSegments; i++) {
  4392. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4393. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4394. this.addLineTo(x, y);
  4395. currentAngle += increment;
  4396. }
  4397. return this;
  4398. };
  4399. /**
  4400. * Closes the Path2.
  4401. * Returns the Path2.
  4402. */
  4403. Path2.prototype.close = function () {
  4404. this.closed = true;
  4405. return this;
  4406. };
  4407. /**
  4408. * Returns the Path2 total length (float).
  4409. */
  4410. Path2.prototype.length = function () {
  4411. var result = this._length;
  4412. if (!this.closed) {
  4413. var lastPoint = this._points[this._points.length - 1];
  4414. var firstPoint = this._points[0];
  4415. result += (firstPoint.subtract(lastPoint).length());
  4416. }
  4417. return result;
  4418. };
  4419. /**
  4420. * Returns the Path2 internal array of points.
  4421. */
  4422. Path2.prototype.getPoints = function () {
  4423. return this._points;
  4424. };
  4425. /**
  4426. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4427. */
  4428. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4429. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4430. //Tools.Error("normalized length position should be between 0 and 1.");
  4431. return Vector2.Zero();
  4432. }
  4433. var lengthPosition = normalizedLengthPosition * this.length();
  4434. var previousOffset = 0;
  4435. for (var i = 0; i < this._points.length; i++) {
  4436. var j = (i + 1) % this._points.length;
  4437. var a = this._points[i];
  4438. var b = this._points[j];
  4439. var bToA = b.subtract(a);
  4440. var nextOffset = (bToA.length() + previousOffset);
  4441. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4442. var dir = bToA.normalize();
  4443. var localOffset = lengthPosition - previousOffset;
  4444. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4445. }
  4446. previousOffset = nextOffset;
  4447. }
  4448. //Tools.Error("internal error");
  4449. return Vector2.Zero();
  4450. };
  4451. /**
  4452. * Returns a new Path2 starting at the coordinates (x, y).
  4453. */
  4454. Path2.StartingAt = function (x, y) {
  4455. return new Path2(x, y);
  4456. };
  4457. return Path2;
  4458. }());
  4459. BABYLON.Path2 = Path2;
  4460. var Path3D = (function () {
  4461. /**
  4462. * new Path3D(path, normal, raw)
  4463. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4464. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4465. * path : an array of Vector3, the curve axis of the Path3D
  4466. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4467. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4468. */
  4469. function Path3D(path, firstNormal, raw) {
  4470. this.path = path;
  4471. this._curve = new Array();
  4472. this._distances = new Array();
  4473. this._tangents = new Array();
  4474. this._normals = new Array();
  4475. this._binormals = new Array();
  4476. for (var p = 0; p < path.length; p++) {
  4477. this._curve[p] = path[p].clone(); // hard copy
  4478. }
  4479. this._raw = raw || false;
  4480. this._compute(firstNormal);
  4481. }
  4482. /**
  4483. * Returns the Path3D array of successive Vector3 designing its curve.
  4484. */
  4485. Path3D.prototype.getCurve = function () {
  4486. return this._curve;
  4487. };
  4488. /**
  4489. * Returns an array populated with tangent vectors on each Path3D curve point.
  4490. */
  4491. Path3D.prototype.getTangents = function () {
  4492. return this._tangents;
  4493. };
  4494. /**
  4495. * Returns an array populated with normal vectors on each Path3D curve point.
  4496. */
  4497. Path3D.prototype.getNormals = function () {
  4498. return this._normals;
  4499. };
  4500. /**
  4501. * Returns an array populated with binormal vectors on each Path3D curve point.
  4502. */
  4503. Path3D.prototype.getBinormals = function () {
  4504. return this._binormals;
  4505. };
  4506. /**
  4507. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4508. */
  4509. Path3D.prototype.getDistances = function () {
  4510. return this._distances;
  4511. };
  4512. /**
  4513. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4514. * Returns the same object updated.
  4515. */
  4516. Path3D.prototype.update = function (path, firstNormal) {
  4517. for (var p = 0; p < path.length; p++) {
  4518. this._curve[p].x = path[p].x;
  4519. this._curve[p].y = path[p].y;
  4520. this._curve[p].z = path[p].z;
  4521. }
  4522. this._compute(firstNormal);
  4523. return this;
  4524. };
  4525. // private function compute() : computes tangents, normals and binormals
  4526. Path3D.prototype._compute = function (firstNormal) {
  4527. var l = this._curve.length;
  4528. // first and last tangents
  4529. this._tangents[0] = this._getFirstNonNullVector(0);
  4530. if (!this._raw) {
  4531. this._tangents[0].normalize();
  4532. }
  4533. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4534. if (!this._raw) {
  4535. this._tangents[l - 1].normalize();
  4536. }
  4537. // normals and binormals at first point : arbitrary vector with _normalVector()
  4538. var tg0 = this._tangents[0];
  4539. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4540. this._normals[0] = pp0;
  4541. if (!this._raw) {
  4542. this._normals[0].normalize();
  4543. }
  4544. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4545. if (!this._raw) {
  4546. this._binormals[0].normalize();
  4547. }
  4548. this._distances[0] = 0.0;
  4549. // normals and binormals : next points
  4550. var prev; // previous vector (segment)
  4551. var cur; // current vector (segment)
  4552. var curTang; // current tangent
  4553. // previous normal
  4554. var prevBinor; // previous binormal
  4555. for (var i = 1; i < l; i++) {
  4556. // tangents
  4557. prev = this._getLastNonNullVector(i);
  4558. if (i < l - 1) {
  4559. cur = this._getFirstNonNullVector(i);
  4560. this._tangents[i] = prev.add(cur);
  4561. this._tangents[i].normalize();
  4562. }
  4563. this._distances[i] = this._distances[i - 1] + prev.length();
  4564. // normals and binormals
  4565. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4566. curTang = this._tangents[i];
  4567. prevBinor = this._binormals[i - 1];
  4568. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4569. if (!this._raw) {
  4570. this._normals[i].normalize();
  4571. }
  4572. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4573. if (!this._raw) {
  4574. this._binormals[i].normalize();
  4575. }
  4576. }
  4577. };
  4578. // private function getFirstNonNullVector(index)
  4579. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4580. Path3D.prototype._getFirstNonNullVector = function (index) {
  4581. var i = 1;
  4582. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4583. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4584. i++;
  4585. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4586. }
  4587. return nNVector;
  4588. };
  4589. // private function getLastNonNullVector(index)
  4590. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4591. Path3D.prototype._getLastNonNullVector = function (index) {
  4592. var i = 1;
  4593. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4594. while (nLVector.length() === 0 && index > i + 1) {
  4595. i++;
  4596. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4597. }
  4598. return nLVector;
  4599. };
  4600. // private function normalVector(v0, vt, va) :
  4601. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4602. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4603. Path3D.prototype._normalVector = function (v0, vt, va) {
  4604. var normal0;
  4605. var tgl = vt.length();
  4606. if (tgl === 0.0) {
  4607. tgl = 1.0;
  4608. }
  4609. if (va === undefined || va === null) {
  4610. var point;
  4611. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4612. point = new Vector3(0.0, -1.0, 0.0);
  4613. }
  4614. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4615. point = new Vector3(1.0, 0.0, 0.0);
  4616. }
  4617. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4618. point = new Vector3(0.0, 0.0, 1.0);
  4619. }
  4620. normal0 = Vector3.Cross(vt, point);
  4621. }
  4622. else {
  4623. normal0 = Vector3.Cross(vt, va);
  4624. Vector3.CrossToRef(normal0, vt, normal0);
  4625. }
  4626. normal0.normalize();
  4627. return normal0;
  4628. };
  4629. return Path3D;
  4630. }());
  4631. BABYLON.Path3D = Path3D;
  4632. var Curve3 = (function () {
  4633. /**
  4634. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4635. * A Curve3 is designed from a series of successive Vector3.
  4636. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4637. */
  4638. function Curve3(points) {
  4639. this._length = 0.0;
  4640. this._points = points;
  4641. this._length = this._computeLength(points);
  4642. }
  4643. /**
  4644. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4645. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4646. * @param v1 (Vector3) the control point
  4647. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4648. * @param nbPoints (integer) the wanted number of points in the curve
  4649. */
  4650. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4651. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4652. var bez = new Array();
  4653. var equation = function (t, val0, val1, val2) {
  4654. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4655. return res;
  4656. };
  4657. for (var i = 0; i <= nbPoints; i++) {
  4658. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4659. }
  4660. return new Curve3(bez);
  4661. };
  4662. /**
  4663. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4664. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4665. * @param v1 (Vector3) the first control point
  4666. * @param v2 (Vector3) the second control point
  4667. * @param v3 (Vector3) the end point of the Cubic Bezier
  4668. * @param nbPoints (integer) the wanted number of points in the curve
  4669. */
  4670. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4671. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4672. var bez = new Array();
  4673. var equation = function (t, val0, val1, val2, val3) {
  4674. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4675. return res;
  4676. };
  4677. for (var i = 0; i <= nbPoints; i++) {
  4678. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4679. }
  4680. return new Curve3(bez);
  4681. };
  4682. /**
  4683. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4684. * @param p1 (Vector3) the origin point of the Hermite Spline
  4685. * @param t1 (Vector3) the tangent vector at the origin point
  4686. * @param p2 (Vector3) the end point of the Hermite Spline
  4687. * @param t2 (Vector3) the tangent vector at the end point
  4688. * @param nbPoints (integer) the wanted number of points in the curve
  4689. */
  4690. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4691. var hermite = new Array();
  4692. var step = 1.0 / nbPoints;
  4693. for (var i = 0; i <= nbPoints; i++) {
  4694. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4695. }
  4696. return new Curve3(hermite);
  4697. };
  4698. /**
  4699. * Returns a Curve3 object along a CatmullRom Spline curve :
  4700. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4701. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4702. */
  4703. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4704. var totalPoints = new Array();
  4705. totalPoints.push(points[0].clone());
  4706. Array.prototype.push.apply(totalPoints, points);
  4707. totalPoints.push(points[points.length - 1].clone());
  4708. var catmullRom = new Array();
  4709. var step = 1.0 / nbPoints;
  4710. for (var i = 0; i < totalPoints.length - 3; i++) {
  4711. var amount = 0.0;
  4712. for (var c = 0; c < nbPoints; c++) {
  4713. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4714. amount += step;
  4715. }
  4716. }
  4717. i--;
  4718. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4719. return new Curve3(catmullRom);
  4720. };
  4721. /**
  4722. * Returns the Curve3 stored array of successive Vector3
  4723. */
  4724. Curve3.prototype.getPoints = function () {
  4725. return this._points;
  4726. };
  4727. /**
  4728. * Returns the computed length (float) of the curve.
  4729. */
  4730. Curve3.prototype.length = function () {
  4731. return this._length;
  4732. };
  4733. /**
  4734. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4735. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4736. * curveA and curveB keep unchanged.
  4737. */
  4738. Curve3.prototype.continue = function (curve) {
  4739. var lastPoint = this._points[this._points.length - 1];
  4740. var continuedPoints = this._points.slice();
  4741. var curvePoints = curve.getPoints();
  4742. for (var i = 1; i < curvePoints.length; i++) {
  4743. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4744. }
  4745. var continuedCurve = new Curve3(continuedPoints);
  4746. return continuedCurve;
  4747. };
  4748. Curve3.prototype._computeLength = function (path) {
  4749. var l = 0;
  4750. for (var i = 1; i < path.length; i++) {
  4751. l += (path[i].subtract(path[i - 1])).length();
  4752. }
  4753. return l;
  4754. };
  4755. return Curve3;
  4756. }());
  4757. BABYLON.Curve3 = Curve3;
  4758. // Vertex formats
  4759. var PositionNormalVertex = (function () {
  4760. function PositionNormalVertex(position, normal) {
  4761. if (position === void 0) { position = Vector3.Zero(); }
  4762. if (normal === void 0) { normal = Vector3.Up(); }
  4763. this.position = position;
  4764. this.normal = normal;
  4765. }
  4766. PositionNormalVertex.prototype.clone = function () {
  4767. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4768. };
  4769. return PositionNormalVertex;
  4770. }());
  4771. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4772. var PositionNormalTextureVertex = (function () {
  4773. function PositionNormalTextureVertex(position, normal, uv) {
  4774. if (position === void 0) { position = Vector3.Zero(); }
  4775. if (normal === void 0) { normal = Vector3.Up(); }
  4776. if (uv === void 0) { uv = Vector2.Zero(); }
  4777. this.position = position;
  4778. this.normal = normal;
  4779. this.uv = uv;
  4780. }
  4781. PositionNormalTextureVertex.prototype.clone = function () {
  4782. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4783. };
  4784. return PositionNormalTextureVertex;
  4785. }());
  4786. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4787. // Temporary pre-allocated objects for engine internal use
  4788. // usage in any internal function :
  4789. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4790. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4791. var Tmp = (function () {
  4792. function Tmp() {
  4793. }
  4794. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4795. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4796. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4797. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4798. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4799. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4800. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4801. Matrix.Zero(), Matrix.Zero(),
  4802. Matrix.Zero(), Matrix.Zero(),
  4803. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4804. return Tmp;
  4805. }());
  4806. BABYLON.Tmp = Tmp;
  4807. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4808. var MathTmp = (function () {
  4809. function MathTmp() {
  4810. }
  4811. MathTmp.Vector3 = [Vector3.Zero()];
  4812. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4813. MathTmp.Quaternion = [Quaternion.Zero()];
  4814. return MathTmp;
  4815. }());
  4816. })(BABYLON || (BABYLON = {}));
  4817. //# sourceMappingURL=babylon.math.js.map
  4818. var BABYLON;
  4819. (function (BABYLON) {
  4820. var Scalar = (function () {
  4821. function Scalar() {
  4822. }
  4823. /**
  4824. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4825. */
  4826. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4827. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4828. var num = a - b;
  4829. return -epsilon <= num && num <= epsilon;
  4830. };
  4831. /**
  4832. * Returns a string : the upper case translation of the number i to hexadecimal.
  4833. */
  4834. Scalar.ToHex = function (i) {
  4835. var str = i.toString(16);
  4836. if (i <= 15) {
  4837. return ("0" + str).toUpperCase();
  4838. }
  4839. return str.toUpperCase();
  4840. };
  4841. /**
  4842. * Returns -1 if value is negative and +1 is value is positive.
  4843. * Returns the value itself if it's equal to zero.
  4844. */
  4845. Scalar.Sign = function (value) {
  4846. value = +value; // convert to a number
  4847. if (value === 0 || isNaN(value))
  4848. return value;
  4849. return value > 0 ? 1 : -1;
  4850. };
  4851. /**
  4852. * Returns the value itself if it's between min and max.
  4853. * Returns min if the value is lower than min.
  4854. * Returns max if the value is greater than max.
  4855. */
  4856. Scalar.Clamp = function (value, min, max) {
  4857. if (min === void 0) { min = 0; }
  4858. if (max === void 0) { max = 1; }
  4859. return Math.min(max, Math.max(min, value));
  4860. };
  4861. /**
  4862. * Returns the log2 of value.
  4863. */
  4864. Scalar.Log2 = function (value) {
  4865. return Math.log(value) * Math.LOG2E;
  4866. };
  4867. /**
  4868. * Loops the value, so that it is never larger than length and never smaller than 0.
  4869. *
  4870. * This is similar to the modulo operator but it works with floating point numbers.
  4871. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4872. * With t = 5 and length = 2.5, the result would be 0.0.
  4873. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4874. */
  4875. Scalar.Repeat = function (value, length) {
  4876. return value - Math.floor(value / length) * length;
  4877. };
  4878. /**
  4879. * Normalize the value between 0.0 and 1.0 using min and max values
  4880. */
  4881. Scalar.Normalize = function (value, min, max) {
  4882. return (value - min) / (max - min);
  4883. };
  4884. /**
  4885. * Denormalize the value from 0.0 and 1.0 using min and max values
  4886. */
  4887. Scalar.Denormalize = function (normalized, min, max) {
  4888. return (normalized * (max - min) + min);
  4889. };
  4890. /**
  4891. * Calculates the shortest difference between two given angles given in degrees.
  4892. */
  4893. Scalar.DeltaAngle = function (current, target) {
  4894. var num = Scalar.Repeat(target - current, 360.0);
  4895. if (num > 180.0) {
  4896. num -= 360.0;
  4897. }
  4898. return num;
  4899. };
  4900. /**
  4901. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4902. *
  4903. * The returned value will move back and forth between 0 and length
  4904. */
  4905. Scalar.PingPong = function (tx, length) {
  4906. var t = Scalar.Repeat(tx, length * 2.0);
  4907. return length - Math.abs(t - length);
  4908. };
  4909. /**
  4910. * Interpolates between min and max with smoothing at the limits.
  4911. *
  4912. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4913. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4914. */
  4915. Scalar.SmoothStep = function (from, to, tx) {
  4916. var t = Scalar.Clamp(tx);
  4917. t = -2.0 * t * t * t + 3.0 * t * t;
  4918. return to * t + from * (1.0 - t);
  4919. };
  4920. /**
  4921. * Moves a value current towards target.
  4922. *
  4923. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4924. * Negative values of maxDelta pushes the value away from target.
  4925. */
  4926. Scalar.MoveTowards = function (current, target, maxDelta) {
  4927. var result = 0;
  4928. if (Math.abs(target - current) <= maxDelta) {
  4929. result = target;
  4930. }
  4931. else {
  4932. result = current + Scalar.Sign(target - current) * maxDelta;
  4933. }
  4934. return result;
  4935. };
  4936. /**
  4937. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4938. *
  4939. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4940. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4941. */
  4942. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4943. var num = Scalar.DeltaAngle(current, target);
  4944. var result = 0;
  4945. if (-maxDelta < num && num < maxDelta) {
  4946. result = target;
  4947. }
  4948. else {
  4949. target = current + num;
  4950. result = Scalar.MoveTowards(current, target, maxDelta);
  4951. }
  4952. return result;
  4953. };
  4954. /**
  4955. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4956. */
  4957. Scalar.Lerp = function (start, end, amount) {
  4958. return start + ((end - start) * amount);
  4959. };
  4960. /**
  4961. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4962. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4963. */
  4964. Scalar.LerpAngle = function (start, end, amount) {
  4965. var num = Scalar.Repeat(end - start, 360.0);
  4966. if (num > 180.0) {
  4967. num -= 360.0;
  4968. }
  4969. return start + num * Scalar.Clamp(amount);
  4970. };
  4971. /**
  4972. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4973. */
  4974. Scalar.InverseLerp = function (a, b, value) {
  4975. var result = 0;
  4976. if (a != b) {
  4977. result = Scalar.Clamp((value - a) / (b - a));
  4978. }
  4979. else {
  4980. result = 0.0;
  4981. }
  4982. return result;
  4983. };
  4984. /**
  4985. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4986. */
  4987. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4988. var squared = amount * amount;
  4989. var cubed = amount * squared;
  4990. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4991. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4992. var part3 = (cubed - (2.0 * squared)) + amount;
  4993. var part4 = cubed - squared;
  4994. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4995. };
  4996. /**
  4997. * Returns a random float number between and min and max values
  4998. */
  4999. Scalar.RandomRange = function (min, max) {
  5000. if (min === max)
  5001. return min;
  5002. return ((Math.random() * (max - min)) + min);
  5003. };
  5004. /**
  5005. * This function returns percentage of a number in a given range.
  5006. *
  5007. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5008. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5009. */
  5010. Scalar.RangeToPercent = function (number, min, max) {
  5011. return ((number - min) / (max - min));
  5012. };
  5013. /**
  5014. * This function returns number that corresponds to the percentage in a given range.
  5015. *
  5016. * PercentToRange(0.34,0,100) will return 34.
  5017. */
  5018. Scalar.PercentToRange = function (percent, min, max) {
  5019. return ((max - min) * percent + min);
  5020. };
  5021. return Scalar;
  5022. }());
  5023. BABYLON.Scalar = Scalar;
  5024. })(BABYLON || (BABYLON = {}));
  5025. //# sourceMappingURL=babylon.math.scalar.js.map
  5026. //# sourceMappingURL=babylon.mixins.js.map
  5027. var BABYLON;
  5028. (function (BABYLON) {
  5029. var __decoratorInitialStore = {};
  5030. var __mergedStore = {};
  5031. var _copySource = function (creationFunction, source, instanciate) {
  5032. var destination = creationFunction();
  5033. // Tags
  5034. if (BABYLON.Tags) {
  5035. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5036. }
  5037. var classStore = getMergedStore(destination);
  5038. // Properties
  5039. for (var property in classStore) {
  5040. var propertyDescriptor = classStore[property];
  5041. var sourceProperty = source[property];
  5042. var propertyType = propertyDescriptor.type;
  5043. if (sourceProperty !== undefined && sourceProperty !== null) {
  5044. switch (propertyType) {
  5045. case 0: // Value
  5046. case 6:// Mesh reference
  5047. destination[property] = sourceProperty;
  5048. break;
  5049. case 1: // Texture
  5050. case 2: // Color3
  5051. case 3: // FresnelParameters
  5052. case 4: // Vector2
  5053. case 5: // Vector3
  5054. case 7:// Color Curves
  5055. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5056. break;
  5057. }
  5058. }
  5059. }
  5060. return destination;
  5061. };
  5062. function getDirectStore(target) {
  5063. var classKey = target.getClassName();
  5064. if (!__decoratorInitialStore[classKey]) {
  5065. __decoratorInitialStore[classKey] = {};
  5066. }
  5067. return __decoratorInitialStore[classKey];
  5068. }
  5069. /**
  5070. * Return the list of properties flagged as serializable
  5071. * @param target: host object
  5072. */
  5073. function getMergedStore(target) {
  5074. var classKey = target.getClassName();
  5075. if (__mergedStore[classKey]) {
  5076. return __mergedStore[classKey];
  5077. }
  5078. __mergedStore[classKey] = {};
  5079. var store = __mergedStore[classKey];
  5080. var currentTarget = target;
  5081. var currentKey = classKey;
  5082. while (currentKey) {
  5083. var initialStore = __decoratorInitialStore[currentKey];
  5084. for (var property in initialStore) {
  5085. store[property] = initialStore[property];
  5086. }
  5087. var parent_1 = void 0;
  5088. var done = false;
  5089. do {
  5090. parent_1 = Object.getPrototypeOf(currentTarget);
  5091. if (!parent_1.getClassName) {
  5092. done = true;
  5093. break;
  5094. }
  5095. if (parent_1.getClassName() !== currentKey) {
  5096. break;
  5097. }
  5098. currentTarget = parent_1;
  5099. } while (parent_1);
  5100. if (done) {
  5101. break;
  5102. }
  5103. currentKey = parent_1.getClassName();
  5104. currentTarget = parent_1;
  5105. }
  5106. return store;
  5107. }
  5108. function generateSerializableMember(type, sourceName) {
  5109. return function (target, propertyKey) {
  5110. var classStore = getDirectStore(target);
  5111. if (!classStore[propertyKey]) {
  5112. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5113. }
  5114. };
  5115. }
  5116. function generateExpandMember(setCallback, targetKey) {
  5117. return function (target, propertyKey) {
  5118. var key = targetKey || ("_" + propertyKey);
  5119. Object.defineProperty(target, propertyKey, {
  5120. get: function () {
  5121. return this[key];
  5122. },
  5123. set: function (value) {
  5124. if (this[key] === value) {
  5125. return;
  5126. }
  5127. this[key] = value;
  5128. target[setCallback].apply(this);
  5129. },
  5130. enumerable: true,
  5131. configurable: true
  5132. });
  5133. };
  5134. }
  5135. function expandToProperty(callback, targetKey) {
  5136. return generateExpandMember(callback, targetKey);
  5137. }
  5138. BABYLON.expandToProperty = expandToProperty;
  5139. function serialize(sourceName) {
  5140. return generateSerializableMember(0, sourceName); // value member
  5141. }
  5142. BABYLON.serialize = serialize;
  5143. function serializeAsTexture(sourceName) {
  5144. return generateSerializableMember(1, sourceName); // texture member
  5145. }
  5146. BABYLON.serializeAsTexture = serializeAsTexture;
  5147. function serializeAsColor3(sourceName) {
  5148. return generateSerializableMember(2, sourceName); // color3 member
  5149. }
  5150. BABYLON.serializeAsColor3 = serializeAsColor3;
  5151. function serializeAsFresnelParameters(sourceName) {
  5152. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5153. }
  5154. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5155. function serializeAsVector2(sourceName) {
  5156. return generateSerializableMember(4, sourceName); // vector2 member
  5157. }
  5158. BABYLON.serializeAsVector2 = serializeAsVector2;
  5159. function serializeAsVector3(sourceName) {
  5160. return generateSerializableMember(5, sourceName); // vector3 member
  5161. }
  5162. BABYLON.serializeAsVector3 = serializeAsVector3;
  5163. function serializeAsMeshReference(sourceName) {
  5164. return generateSerializableMember(6, sourceName); // mesh reference member
  5165. }
  5166. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5167. function serializeAsColorCurves(sourceName) {
  5168. return generateSerializableMember(7, sourceName); // color curves
  5169. }
  5170. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5171. function serializeAsColor4(sourceName) {
  5172. return generateSerializableMember(8, sourceName); // color 4
  5173. }
  5174. BABYLON.serializeAsColor4 = serializeAsColor4;
  5175. function serializeAsImageProcessingConfiguration(sourceName) {
  5176. return generateSerializableMember(9, sourceName); // image processing
  5177. }
  5178. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5179. var SerializationHelper = (function () {
  5180. function SerializationHelper() {
  5181. }
  5182. SerializationHelper.Serialize = function (entity, serializationObject) {
  5183. if (!serializationObject) {
  5184. serializationObject = {};
  5185. }
  5186. // Tags
  5187. if (BABYLON.Tags) {
  5188. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5189. }
  5190. var serializedProperties = getMergedStore(entity);
  5191. // Properties
  5192. for (var property in serializedProperties) {
  5193. var propertyDescriptor = serializedProperties[property];
  5194. var targetPropertyName = propertyDescriptor.sourceName || property;
  5195. var propertyType = propertyDescriptor.type;
  5196. var sourceProperty = entity[property];
  5197. if (sourceProperty !== undefined && sourceProperty !== null) {
  5198. switch (propertyType) {
  5199. case 0:// Value
  5200. serializationObject[targetPropertyName] = sourceProperty;
  5201. break;
  5202. case 1:// Texture
  5203. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5204. break;
  5205. case 2:// Color3
  5206. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5207. break;
  5208. case 3:// FresnelParameters
  5209. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5210. break;
  5211. case 4:// Vector2
  5212. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5213. break;
  5214. case 5:// Vector3
  5215. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5216. break;
  5217. case 6:// Mesh reference
  5218. serializationObject[targetPropertyName] = sourceProperty.id;
  5219. break;
  5220. case 7:// Color Curves
  5221. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5222. break;
  5223. case 8:// Color 4
  5224. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5225. break;
  5226. case 9:// Image Processing
  5227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5228. break;
  5229. }
  5230. }
  5231. }
  5232. return serializationObject;
  5233. };
  5234. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5235. var destination = creationFunction();
  5236. // Tags
  5237. if (BABYLON.Tags) {
  5238. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5239. }
  5240. var classStore = getMergedStore(destination);
  5241. // Properties
  5242. for (var property in classStore) {
  5243. var propertyDescriptor = classStore[property];
  5244. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5245. var propertyType = propertyDescriptor.type;
  5246. if (sourceProperty !== undefined && sourceProperty !== null) {
  5247. switch (propertyType) {
  5248. case 0:// Value
  5249. destination[property] = sourceProperty;
  5250. break;
  5251. case 1:// Texture
  5252. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5253. break;
  5254. case 2:// Color3
  5255. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5256. break;
  5257. case 3:// FresnelParameters
  5258. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5259. break;
  5260. case 4:// Vector2
  5261. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5262. break;
  5263. case 5:// Vector3
  5264. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5265. break;
  5266. case 6:// Mesh reference
  5267. destination[property] = scene.getLastMeshByID(sourceProperty);
  5268. break;
  5269. case 7:// Color Curves
  5270. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5271. break;
  5272. case 8:// Color 4
  5273. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5274. break;
  5275. case 9:// Image Processing
  5276. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5277. break;
  5278. }
  5279. }
  5280. }
  5281. return destination;
  5282. };
  5283. SerializationHelper.Clone = function (creationFunction, source) {
  5284. return _copySource(creationFunction, source, false);
  5285. };
  5286. SerializationHelper.Instanciate = function (creationFunction, source) {
  5287. return _copySource(creationFunction, source, true);
  5288. };
  5289. return SerializationHelper;
  5290. }());
  5291. BABYLON.SerializationHelper = SerializationHelper;
  5292. })(BABYLON || (BABYLON = {}));
  5293. //# sourceMappingURL=babylon.decorators.js.map
  5294. var BABYLON;
  5295. (function (BABYLON) {
  5296. /**
  5297. * A class serves as a medium between the observable and its observers
  5298. */
  5299. var EventState = (function () {
  5300. /**
  5301. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5302. */
  5303. function EventState(mask, skipNextObservers) {
  5304. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5305. this.initalize(mask, skipNextObservers);
  5306. }
  5307. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5308. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5309. this.mask = mask;
  5310. this.skipNextObservers = skipNextObservers;
  5311. return this;
  5312. };
  5313. return EventState;
  5314. }());
  5315. BABYLON.EventState = EventState;
  5316. /**
  5317. * Represent an Observer registered to a given Observable object.
  5318. */
  5319. var Observer = (function () {
  5320. function Observer(callback, mask) {
  5321. this.callback = callback;
  5322. this.mask = mask;
  5323. }
  5324. return Observer;
  5325. }());
  5326. BABYLON.Observer = Observer;
  5327. /**
  5328. * The Observable class is a simple implementation of the Observable pattern.
  5329. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  5330. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5331. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  5332. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  5333. */
  5334. var Observable = (function () {
  5335. function Observable(onObserverAdded) {
  5336. this._observers = new Array();
  5337. this._eventState = new EventState(0);
  5338. this._onObserverAdded = onObserverAdded;
  5339. }
  5340. /**
  5341. * Create a new Observer with the specified callback
  5342. * @param callback the callback that will be executed for that Observer
  5343. * @param mask the mask used to filter observers
  5344. * @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.
  5345. */
  5346. Observable.prototype.add = function (callback, mask, insertFirst) {
  5347. if (mask === void 0) { mask = -1; }
  5348. if (insertFirst === void 0) { insertFirst = false; }
  5349. if (!callback) {
  5350. return null;
  5351. }
  5352. var observer = new Observer(callback, mask);
  5353. if (insertFirst) {
  5354. this._observers.unshift(observer);
  5355. }
  5356. else {
  5357. this._observers.push(observer);
  5358. }
  5359. if (this._onObserverAdded) {
  5360. this._onObserverAdded(observer);
  5361. }
  5362. return observer;
  5363. };
  5364. /**
  5365. * Remove an Observer from the Observable object
  5366. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5367. */
  5368. Observable.prototype.remove = function (observer) {
  5369. var index = this._observers.indexOf(observer);
  5370. if (index !== -1) {
  5371. this._observers.splice(index, 1);
  5372. return true;
  5373. }
  5374. return false;
  5375. };
  5376. /**
  5377. * Remove a callback from the Observable object
  5378. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5379. */
  5380. Observable.prototype.removeCallback = function (callback) {
  5381. for (var index = 0; index < this._observers.length; index++) {
  5382. if (this._observers[index].callback === callback) {
  5383. this._observers.splice(index, 1);
  5384. return true;
  5385. }
  5386. }
  5387. return false;
  5388. };
  5389. /**
  5390. * Notify all Observers by calling their respective callback with the given data
  5391. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5392. * @param eventData
  5393. * @param mask
  5394. */
  5395. Observable.prototype.notifyObservers = function (eventData, mask) {
  5396. if (mask === void 0) { mask = -1; }
  5397. var state = this._eventState;
  5398. state.mask = mask;
  5399. state.skipNextObservers = false;
  5400. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5401. var obs = _a[_i];
  5402. if (obs.mask & mask) {
  5403. obs.callback(eventData, state);
  5404. }
  5405. if (state.skipNextObservers) {
  5406. return false;
  5407. }
  5408. }
  5409. return true;
  5410. };
  5411. /**
  5412. * Notify a specific observer
  5413. * @param eventData
  5414. * @param mask
  5415. */
  5416. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5417. if (mask === void 0) { mask = -1; }
  5418. var state = this._eventState;
  5419. state.mask = mask;
  5420. state.skipNextObservers = false;
  5421. observer.callback(eventData, state);
  5422. };
  5423. /**
  5424. * return true is the Observable has at least one Observer registered
  5425. */
  5426. Observable.prototype.hasObservers = function () {
  5427. return this._observers.length > 0;
  5428. };
  5429. /**
  5430. * Clear the list of observers
  5431. */
  5432. Observable.prototype.clear = function () {
  5433. this._observers = new Array();
  5434. this._onObserverAdded = null;
  5435. };
  5436. /**
  5437. * Clone the current observable
  5438. */
  5439. Observable.prototype.clone = function () {
  5440. var result = new Observable();
  5441. result._observers = this._observers.slice(0);
  5442. return result;
  5443. };
  5444. /**
  5445. * Does this observable handles observer registered with a given mask
  5446. * @param {number} trigger - the mask to be tested
  5447. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5448. **/
  5449. Observable.prototype.hasSpecificMask = function (mask) {
  5450. if (mask === void 0) { mask = -1; }
  5451. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5452. var obs = _a[_i];
  5453. if (obs.mask & mask || obs.mask === mask) {
  5454. return true;
  5455. }
  5456. }
  5457. return false;
  5458. };
  5459. return Observable;
  5460. }());
  5461. BABYLON.Observable = Observable;
  5462. })(BABYLON || (BABYLON = {}));
  5463. //# sourceMappingURL=babylon.observable.js.map
  5464. var BABYLON;
  5465. (function (BABYLON) {
  5466. var SmartArray = (function () {
  5467. function SmartArray(capacity) {
  5468. this.length = 0;
  5469. this._duplicateId = 0;
  5470. this.data = new Array(capacity);
  5471. this._id = SmartArray._GlobalId++;
  5472. }
  5473. SmartArray.prototype.push = function (value) {
  5474. this.data[this.length++] = value;
  5475. if (this.length > this.data.length) {
  5476. this.data.length *= 2;
  5477. }
  5478. if (!value.__smartArrayFlags) {
  5479. value.__smartArrayFlags = {};
  5480. }
  5481. value.__smartArrayFlags[this._id] = this._duplicateId;
  5482. };
  5483. SmartArray.prototype.forEach = function (func) {
  5484. for (var index = 0; index < this.length; index++) {
  5485. func(this.data[index]);
  5486. }
  5487. };
  5488. SmartArray.prototype.pushNoDuplicate = function (value) {
  5489. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5490. return false;
  5491. }
  5492. this.push(value);
  5493. return true;
  5494. };
  5495. SmartArray.prototype.sort = function (compareFn) {
  5496. this.data.sort(compareFn);
  5497. };
  5498. SmartArray.prototype.reset = function () {
  5499. this.length = 0;
  5500. this._duplicateId++;
  5501. };
  5502. SmartArray.prototype.dispose = function () {
  5503. this.reset();
  5504. if (this.data) {
  5505. this.data.length = 0;
  5506. this.data = null;
  5507. }
  5508. };
  5509. SmartArray.prototype.concat = function (array) {
  5510. if (array.length === 0) {
  5511. return;
  5512. }
  5513. if (this.length + array.length > this.data.length) {
  5514. this.data.length = (this.length + array.length) * 2;
  5515. }
  5516. for (var index = 0; index < array.length; index++) {
  5517. this.data[this.length++] = (array.data || array)[index];
  5518. }
  5519. };
  5520. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5521. if (array.length === 0) {
  5522. return;
  5523. }
  5524. if (this.length + array.length > this.data.length) {
  5525. this.data.length = (this.length + array.length) * 2;
  5526. }
  5527. for (var index = 0; index < array.length; index++) {
  5528. var item = (array.data || array)[index];
  5529. this.pushNoDuplicate(item);
  5530. }
  5531. };
  5532. SmartArray.prototype.indexOf = function (value) {
  5533. var position = this.data.indexOf(value);
  5534. if (position >= this.length) {
  5535. return -1;
  5536. }
  5537. return position;
  5538. };
  5539. SmartArray.prototype.contains = function (value) {
  5540. return this.data.indexOf(value) !== -1;
  5541. };
  5542. // Statics
  5543. SmartArray._GlobalId = 0;
  5544. return SmartArray;
  5545. }());
  5546. BABYLON.SmartArray = SmartArray;
  5547. })(BABYLON || (BABYLON = {}));
  5548. //# sourceMappingURL=babylon.smartArray.js.map
  5549. var BABYLON;
  5550. (function (BABYLON) {
  5551. // Screenshots
  5552. var screenshotCanvas;
  5553. var cloneValue = function (source, destinationObject) {
  5554. if (!source)
  5555. return null;
  5556. if (source instanceof BABYLON.Mesh) {
  5557. return null;
  5558. }
  5559. if (source instanceof BABYLON.SubMesh) {
  5560. return source.clone(destinationObject);
  5561. }
  5562. else if (source.clone) {
  5563. return source.clone();
  5564. }
  5565. return null;
  5566. };
  5567. var Tools = (function () {
  5568. function Tools() {
  5569. }
  5570. ;
  5571. /**
  5572. * Interpolates between a and b via alpha
  5573. * @param a The lower value (returned when alpha = 0)
  5574. * @param b The upper value (returned when alpha = 1)
  5575. * @param alpha The interpolation-factor
  5576. * @return The mixed value
  5577. */
  5578. Tools.Mix = function (a, b, alpha) {
  5579. return a * (1 - alpha) + b * alpha;
  5580. };
  5581. Tools.Instantiate = function (className) {
  5582. var arr = className.split(".");
  5583. var fn = (window || this);
  5584. for (var i = 0, len = arr.length; i < len; i++) {
  5585. fn = fn[arr[i]];
  5586. }
  5587. if (typeof fn !== "function") {
  5588. return null;
  5589. }
  5590. return fn;
  5591. };
  5592. Tools.SetImmediate = function (action) {
  5593. if (window.setImmediate) {
  5594. window.setImmediate(action);
  5595. }
  5596. else {
  5597. setTimeout(action, 1);
  5598. }
  5599. };
  5600. Tools.IsExponentOfTwo = function (value) {
  5601. var count = 1;
  5602. do {
  5603. count *= 2;
  5604. } while (count < value);
  5605. return count === value;
  5606. };
  5607. /**
  5608. * Find the next highest power of two.
  5609. * @param x Number to start search from.
  5610. * @return Next highest power of two.
  5611. */
  5612. Tools.CeilingPOT = function (x) {
  5613. x--;
  5614. x |= x >> 1;
  5615. x |= x >> 2;
  5616. x |= x >> 4;
  5617. x |= x >> 8;
  5618. x |= x >> 16;
  5619. x++;
  5620. return x;
  5621. };
  5622. /**
  5623. * Find the next lowest power of two.
  5624. * @param x Number to start search from.
  5625. * @return Next lowest power of two.
  5626. */
  5627. Tools.FloorPOT = function (x) {
  5628. x = x | (x >> 1);
  5629. x = x | (x >> 2);
  5630. x = x | (x >> 4);
  5631. x = x | (x >> 8);
  5632. x = x | (x >> 16);
  5633. return x - (x >> 1);
  5634. };
  5635. /**
  5636. * Find the nearest power of two.
  5637. * @param x Number to start search from.
  5638. * @return Next nearest power of two.
  5639. */
  5640. Tools.NearestPOT = function (x) {
  5641. var c = Tools.CeilingPOT(x);
  5642. var f = Tools.FloorPOT(x);
  5643. return (c - x) > (x - f) ? f : c;
  5644. };
  5645. Tools.GetExponentOfTwo = function (value, max, mode) {
  5646. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5647. var pot;
  5648. switch (mode) {
  5649. case BABYLON.Engine.SCALEMODE_FLOOR:
  5650. pot = Tools.FloorPOT(value);
  5651. break;
  5652. case BABYLON.Engine.SCALEMODE_NEAREST:
  5653. pot = Tools.NearestPOT(value);
  5654. break;
  5655. case BABYLON.Engine.SCALEMODE_CEILING:
  5656. pot = Tools.CeilingPOT(value);
  5657. break;
  5658. }
  5659. return Math.min(pot, max);
  5660. };
  5661. Tools.GetFilename = function (path) {
  5662. var index = path.lastIndexOf("/");
  5663. if (index < 0)
  5664. return path;
  5665. return path.substring(index + 1);
  5666. };
  5667. Tools.GetDOMTextContent = function (element) {
  5668. var result = "";
  5669. var child = element.firstChild;
  5670. while (child) {
  5671. if (child.nodeType === 3) {
  5672. result += child.textContent;
  5673. }
  5674. child = child.nextSibling;
  5675. }
  5676. return result;
  5677. };
  5678. Tools.ToDegrees = function (angle) {
  5679. return angle * 180 / Math.PI;
  5680. };
  5681. Tools.ToRadians = function (angle) {
  5682. return angle * Math.PI / 180;
  5683. };
  5684. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5685. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5686. var output = "";
  5687. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5688. var i = 0;
  5689. var bytes = new Uint8Array(buffer);
  5690. while (i < bytes.length) {
  5691. chr1 = bytes[i++];
  5692. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5693. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5694. enc1 = chr1 >> 2;
  5695. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5696. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5697. enc4 = chr3 & 63;
  5698. if (isNaN(chr2)) {
  5699. enc3 = enc4 = 64;
  5700. }
  5701. else if (isNaN(chr3)) {
  5702. enc4 = 64;
  5703. }
  5704. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5705. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5706. }
  5707. return "data:image/png;base64," + output;
  5708. };
  5709. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5710. if (bias === void 0) { bias = null; }
  5711. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5712. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5713. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5714. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5715. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5716. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5717. }
  5718. if (bias) {
  5719. minimum.x -= minimum.x * bias.x + bias.y;
  5720. minimum.y -= minimum.y * bias.x + bias.y;
  5721. minimum.z -= minimum.z * bias.x + bias.y;
  5722. maximum.x += maximum.x * bias.x + bias.y;
  5723. maximum.y += maximum.y * bias.x + bias.y;
  5724. maximum.z += maximum.z * bias.x + bias.y;
  5725. }
  5726. return {
  5727. minimum: minimum,
  5728. maximum: maximum
  5729. };
  5730. };
  5731. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5732. if (bias === void 0) { bias = null; }
  5733. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5734. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5735. if (!stride) {
  5736. stride = 3;
  5737. }
  5738. for (var index = start; index < start + count; index++) {
  5739. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5740. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5741. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5742. }
  5743. if (bias) {
  5744. minimum.x -= minimum.x * bias.x + bias.y;
  5745. minimum.y -= minimum.y * bias.x + bias.y;
  5746. minimum.z -= minimum.z * bias.x + bias.y;
  5747. maximum.x += maximum.x * bias.x + bias.y;
  5748. maximum.y += maximum.y * bias.x + bias.y;
  5749. maximum.z += maximum.z * bias.x + bias.y;
  5750. }
  5751. return {
  5752. minimum: minimum,
  5753. maximum: maximum
  5754. };
  5755. };
  5756. Tools.Vector2ArrayFeeder = function (array) {
  5757. return function (index) {
  5758. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5759. var length = isFloatArray ? array.length / 2 : array.length;
  5760. if (index >= length) {
  5761. return null;
  5762. }
  5763. if (isFloatArray) {
  5764. var fa = array;
  5765. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5766. }
  5767. var a = array;
  5768. return a[index];
  5769. };
  5770. };
  5771. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5772. if (bias === void 0) { bias = null; }
  5773. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5774. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5775. var i = 0;
  5776. var cur = feeder(i++);
  5777. while (cur) {
  5778. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5779. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5780. cur = feeder(i++);
  5781. }
  5782. if (bias) {
  5783. minimum.x -= minimum.x * bias.x + bias.y;
  5784. minimum.y -= minimum.y * bias.x + bias.y;
  5785. maximum.x += maximum.x * bias.x + bias.y;
  5786. maximum.y += maximum.y * bias.x + bias.y;
  5787. }
  5788. return {
  5789. minimum: minimum,
  5790. maximum: maximum
  5791. };
  5792. };
  5793. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5794. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5795. return undefined;
  5796. return Array.isArray(obj) ? obj : [obj];
  5797. };
  5798. // Misc.
  5799. Tools.GetPointerPrefix = function () {
  5800. var eventPrefix = "pointer";
  5801. // Check if pointer events are supported
  5802. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5803. eventPrefix = "mouse";
  5804. }
  5805. return eventPrefix;
  5806. };
  5807. /**
  5808. * @param func - the function to be called
  5809. * @param requester - the object that will request the next frame. Falls back to window.
  5810. */
  5811. Tools.QueueNewFrame = function (func, requester) {
  5812. if (requester === void 0) { requester = window; }
  5813. if (requester.requestAnimationFrame) {
  5814. return requester.requestAnimationFrame(func);
  5815. }
  5816. else if (requester.msRequestAnimationFrame) {
  5817. return requester.msRequestAnimationFrame(func);
  5818. }
  5819. else if (requester.webkitRequestAnimationFrame) {
  5820. return requester.webkitRequestAnimationFrame(func);
  5821. }
  5822. else if (requester.mozRequestAnimationFrame) {
  5823. return requester.mozRequestAnimationFrame(func);
  5824. }
  5825. else if (requester.oRequestAnimationFrame) {
  5826. return requester.oRequestAnimationFrame(func);
  5827. }
  5828. else {
  5829. return window.setTimeout(func, 16);
  5830. }
  5831. };
  5832. Tools.RequestFullscreen = function (element) {
  5833. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5834. if (!requestFunction)
  5835. return;
  5836. requestFunction.call(element);
  5837. };
  5838. Tools.ExitFullscreen = function () {
  5839. if (document.exitFullscreen) {
  5840. document.exitFullscreen();
  5841. }
  5842. else if (document.mozCancelFullScreen) {
  5843. document.mozCancelFullScreen();
  5844. }
  5845. else if (document.webkitCancelFullScreen) {
  5846. document.webkitCancelFullScreen();
  5847. }
  5848. else if (document.msCancelFullScreen) {
  5849. document.msCancelFullScreen();
  5850. }
  5851. };
  5852. Tools.SetCorsBehavior = function (url, img) {
  5853. if (Tools.CorsBehavior) {
  5854. switch (typeof (Tools.CorsBehavior)) {
  5855. case "function":
  5856. var result = Tools.CorsBehavior(url);
  5857. if (result) {
  5858. img.crossOrigin = result;
  5859. }
  5860. break;
  5861. case "string":
  5862. default:
  5863. img.crossOrigin = Tools.CorsBehavior;
  5864. break;
  5865. }
  5866. }
  5867. };
  5868. // External files
  5869. Tools.CleanUrl = function (url) {
  5870. url = url.replace(/#/mg, "%23");
  5871. return url;
  5872. };
  5873. Tools.LoadImage = function (url, onload, onerror, database) {
  5874. if (url instanceof ArrayBuffer) {
  5875. url = Tools.EncodeArrayBufferTobase64(url);
  5876. }
  5877. url = Tools.CleanUrl(url);
  5878. url = Tools.PreprocessUrl(url);
  5879. var img = new Image();
  5880. if (url.substr(0, 5) !== "data:") {
  5881. Tools.SetCorsBehavior(url, img);
  5882. }
  5883. img.onload = function () {
  5884. onload(img);
  5885. };
  5886. img.onerror = function (err) {
  5887. Tools.Error("Error while trying to load image: " + url);
  5888. if (Tools.UseFallbackTexture) {
  5889. img.src = Tools.fallbackTexture;
  5890. onload(img);
  5891. }
  5892. else {
  5893. onerror();
  5894. }
  5895. };
  5896. var noIndexedDB = function () {
  5897. img.src = url;
  5898. };
  5899. var loadFromIndexedDB = function () {
  5900. database.loadImageFromDB(url, img);
  5901. };
  5902. //ANY database to do!
  5903. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5904. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5905. }
  5906. else {
  5907. if (url.indexOf("file:") !== 0) {
  5908. noIndexedDB();
  5909. }
  5910. else {
  5911. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5912. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5913. try {
  5914. var blobURL;
  5915. try {
  5916. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5917. }
  5918. catch (ex) {
  5919. // Chrome doesn't support oneTimeOnly parameter
  5920. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5921. }
  5922. img.src = blobURL;
  5923. }
  5924. catch (e) {
  5925. img.src = null;
  5926. }
  5927. }
  5928. else {
  5929. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5930. img.src = Tools.fallbackTexture;
  5931. }
  5932. }
  5933. }
  5934. return img;
  5935. };
  5936. //ANY
  5937. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5938. url = Tools.CleanUrl(url);
  5939. url = Tools.PreprocessUrl(url);
  5940. var noIndexedDB = function () {
  5941. var request = new XMLHttpRequest();
  5942. var loadUrl = Tools.BaseUrl + url;
  5943. request.open('GET', loadUrl, true);
  5944. if (useArrayBuffer) {
  5945. request.responseType = "arraybuffer";
  5946. }
  5947. request.onprogress = progressCallBack;
  5948. request.onreadystatechange = function () {
  5949. // In case of undefined state in some browsers.
  5950. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5951. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5952. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5953. callback(!useArrayBuffer ? request.responseText : request.response);
  5954. }
  5955. else {
  5956. if (onError) {
  5957. onError(request);
  5958. }
  5959. else {
  5960. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5961. }
  5962. }
  5963. }
  5964. };
  5965. request.send(null);
  5966. };
  5967. var loadFromIndexedDB = function () {
  5968. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5969. };
  5970. if (url.indexOf("file:") !== -1) {
  5971. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5972. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5973. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5974. }
  5975. else {
  5976. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5977. }
  5978. }
  5979. else {
  5980. // Caching all files
  5981. if (database && database.enableSceneOffline) {
  5982. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5983. }
  5984. else {
  5985. noIndexedDB();
  5986. }
  5987. }
  5988. };
  5989. /**
  5990. * Load a script (identified by an url). When the url returns, the
  5991. * content of this file is added into a new script element, attached to the DOM (body element)
  5992. */
  5993. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5994. var head = document.getElementsByTagName('head')[0];
  5995. var script = document.createElement('script');
  5996. script.type = 'text/javascript';
  5997. script.src = scriptUrl;
  5998. var self = this;
  5999. script.onload = function () {
  6000. if (onSuccess) {
  6001. onSuccess();
  6002. }
  6003. };
  6004. script.onerror = function () {
  6005. if (onError) {
  6006. onError();
  6007. }
  6008. };
  6009. head.appendChild(script);
  6010. };
  6011. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6012. var reader = new FileReader();
  6013. reader.onload = function (e) {
  6014. //target doesn't have result from ts 1.3
  6015. callback(e.target['result']);
  6016. };
  6017. reader.onprogress = progressCallback;
  6018. reader.readAsDataURL(fileToLoad);
  6019. };
  6020. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6021. var reader = new FileReader();
  6022. reader.onerror = function (e) {
  6023. Tools.Log("Error while reading file: " + fileToLoad.name);
  6024. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6025. };
  6026. reader.onload = function (e) {
  6027. //target doesn't have result from ts 1.3
  6028. callback(e.target['result']);
  6029. };
  6030. reader.onprogress = progressCallBack;
  6031. if (!useArrayBuffer) {
  6032. // Asynchronous read
  6033. reader.readAsText(fileToLoad);
  6034. }
  6035. else {
  6036. reader.readAsArrayBuffer(fileToLoad);
  6037. }
  6038. };
  6039. //returns a downloadable url to a file content.
  6040. Tools.FileAsURL = function (content) {
  6041. var fileBlob = new Blob([content]);
  6042. var url = window.URL || window.webkitURL;
  6043. var link = url.createObjectURL(fileBlob);
  6044. return link;
  6045. };
  6046. // Misc.
  6047. Tools.Format = function (value, decimals) {
  6048. if (decimals === void 0) { decimals = 2; }
  6049. return value.toFixed(decimals);
  6050. };
  6051. Tools.CheckExtends = function (v, min, max) {
  6052. if (v.x < min.x)
  6053. min.x = v.x;
  6054. if (v.y < min.y)
  6055. min.y = v.y;
  6056. if (v.z < min.z)
  6057. min.z = v.z;
  6058. if (v.x > max.x)
  6059. max.x = v.x;
  6060. if (v.y > max.y)
  6061. max.y = v.y;
  6062. if (v.z > max.z)
  6063. max.z = v.z;
  6064. };
  6065. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6066. for (var prop in source) {
  6067. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6068. continue;
  6069. }
  6070. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6071. continue;
  6072. }
  6073. var sourceValue = source[prop];
  6074. var typeOfSourceValue = typeof sourceValue;
  6075. if (typeOfSourceValue === "function") {
  6076. continue;
  6077. }
  6078. if (typeOfSourceValue === "object") {
  6079. if (sourceValue instanceof Array) {
  6080. destination[prop] = [];
  6081. if (sourceValue.length > 0) {
  6082. if (typeof sourceValue[0] == "object") {
  6083. for (var index = 0; index < sourceValue.length; index++) {
  6084. var clonedValue = cloneValue(sourceValue[index], destination);
  6085. if (destination[prop].indexOf(clonedValue) === -1) {
  6086. destination[prop].push(clonedValue);
  6087. }
  6088. }
  6089. }
  6090. else {
  6091. destination[prop] = sourceValue.slice(0);
  6092. }
  6093. }
  6094. }
  6095. else {
  6096. destination[prop] = cloneValue(sourceValue, destination);
  6097. }
  6098. }
  6099. else {
  6100. destination[prop] = sourceValue;
  6101. }
  6102. }
  6103. };
  6104. Tools.IsEmpty = function (obj) {
  6105. for (var i in obj) {
  6106. return false;
  6107. }
  6108. return true;
  6109. };
  6110. Tools.RegisterTopRootEvents = function (events) {
  6111. for (var index = 0; index < events.length; index++) {
  6112. var event = events[index];
  6113. window.addEventListener(event.name, event.handler, false);
  6114. try {
  6115. if (window.parent) {
  6116. window.parent.addEventListener(event.name, event.handler, false);
  6117. }
  6118. }
  6119. catch (e) {
  6120. // Silently fails...
  6121. }
  6122. }
  6123. };
  6124. Tools.UnregisterTopRootEvents = function (events) {
  6125. for (var index = 0; index < events.length; index++) {
  6126. var event = events[index];
  6127. window.removeEventListener(event.name, event.handler);
  6128. try {
  6129. if (window.parent) {
  6130. window.parent.removeEventListener(event.name, event.handler);
  6131. }
  6132. }
  6133. catch (e) {
  6134. // Silently fails...
  6135. }
  6136. }
  6137. };
  6138. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6139. if (mimeType === void 0) { mimeType = "image/png"; }
  6140. // Read the contents of the framebuffer
  6141. var numberOfChannelsByLine = width * 4;
  6142. var halfHeight = height / 2;
  6143. //Reading datas from WebGL
  6144. var data = engine.readPixels(0, 0, width, height);
  6145. //To flip image on Y axis.
  6146. for (var i = 0; i < halfHeight; i++) {
  6147. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6148. var currentCell = j + i * numberOfChannelsByLine;
  6149. var targetLine = height - i - 1;
  6150. var targetCell = j + targetLine * numberOfChannelsByLine;
  6151. var temp = data[currentCell];
  6152. data[currentCell] = data[targetCell];
  6153. data[targetCell] = temp;
  6154. }
  6155. }
  6156. // Create a 2D canvas to store the result
  6157. if (!screenshotCanvas) {
  6158. screenshotCanvas = document.createElement('canvas');
  6159. }
  6160. screenshotCanvas.width = width;
  6161. screenshotCanvas.height = height;
  6162. var context = screenshotCanvas.getContext('2d');
  6163. // Copy the pixels to a 2D canvas
  6164. var imageData = context.createImageData(width, height);
  6165. var castData = (imageData.data);
  6166. castData.set(data);
  6167. context.putImageData(imageData, 0, 0);
  6168. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6169. };
  6170. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6171. if (mimeType === void 0) { mimeType = "image/png"; }
  6172. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6173. if (successCallback) {
  6174. successCallback(base64Image);
  6175. }
  6176. else {
  6177. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6178. if (("download" in document.createElement("a"))) {
  6179. var a = window.document.createElement("a");
  6180. a.href = base64Image;
  6181. var date = new Date();
  6182. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6183. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6184. window.document.body.appendChild(a);
  6185. a.addEventListener("click", function () {
  6186. a.parentElement.removeChild(a);
  6187. });
  6188. a.click();
  6189. //Or opening a new tab with the image if it is not possible to automatically start download.
  6190. }
  6191. else {
  6192. var newWindow = window.open("");
  6193. var img = newWindow.document.createElement("img");
  6194. img.src = base64Image;
  6195. newWindow.document.body.appendChild(img);
  6196. }
  6197. }
  6198. };
  6199. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6200. if (mimeType === void 0) { mimeType = "image/png"; }
  6201. var width;
  6202. var height;
  6203. // If a precision value is specified
  6204. if (size.precision) {
  6205. width = Math.round(engine.getRenderWidth() * size.precision);
  6206. height = Math.round(width / engine.getAspectRatio(camera));
  6207. }
  6208. else if (size.width && size.height) {
  6209. width = size.width;
  6210. height = size.height;
  6211. }
  6212. else if (size.width && !size.height) {
  6213. width = size.width;
  6214. height = Math.round(width / engine.getAspectRatio(camera));
  6215. }
  6216. else if (size.height && !size.width) {
  6217. height = size.height;
  6218. width = Math.round(height * engine.getAspectRatio(camera));
  6219. }
  6220. else if (!isNaN(size)) {
  6221. height = size;
  6222. width = size;
  6223. }
  6224. else {
  6225. Tools.Error("Invalid 'size' parameter !");
  6226. return;
  6227. }
  6228. if (!screenshotCanvas) {
  6229. screenshotCanvas = document.createElement('canvas');
  6230. }
  6231. screenshotCanvas.width = width;
  6232. screenshotCanvas.height = height;
  6233. var renderContext = screenshotCanvas.getContext("2d");
  6234. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6235. var newWidth = width;
  6236. var newHeight = newWidth / ratio;
  6237. if (newHeight > height) {
  6238. newHeight = height;
  6239. newWidth = newHeight * ratio;
  6240. }
  6241. var offsetX = Math.max(0, width - newWidth) / 2;
  6242. var offsetY = Math.max(0, height - newHeight) / 2;
  6243. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6244. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6245. };
  6246. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6247. if (mimeType === void 0) { mimeType = "image/png"; }
  6248. if (samples === void 0) { samples = 1; }
  6249. var width;
  6250. var height;
  6251. //If a precision value is specified
  6252. if (size.precision) {
  6253. width = Math.round(engine.getRenderWidth() * size.precision);
  6254. height = Math.round(width / engine.getAspectRatio(camera));
  6255. size = { width: width, height: height };
  6256. }
  6257. else if (size.width && size.height) {
  6258. width = size.width;
  6259. height = size.height;
  6260. }
  6261. else if (size.width && !size.height) {
  6262. width = size.width;
  6263. height = Math.round(width / engine.getAspectRatio(camera));
  6264. size = { width: width, height: height };
  6265. }
  6266. else if (size.height && !size.width) {
  6267. height = size.height;
  6268. width = Math.round(height * engine.getAspectRatio(camera));
  6269. size = { width: width, height: height };
  6270. }
  6271. else if (!isNaN(size)) {
  6272. height = size;
  6273. width = size;
  6274. }
  6275. else {
  6276. Tools.Error("Invalid 'size' parameter !");
  6277. return;
  6278. }
  6279. var scene = camera.getScene();
  6280. var previousCamera = null;
  6281. if (scene.activeCamera !== camera) {
  6282. previousCamera = scene.activeCamera;
  6283. scene.activeCamera = camera;
  6284. }
  6285. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6286. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6287. texture.renderList = null;
  6288. texture.samples = samples;
  6289. texture.onAfterRenderObservable.add(function () {
  6290. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6291. });
  6292. scene.incrementRenderId();
  6293. scene.resetCachedMaterial();
  6294. texture.render(true);
  6295. texture.dispose();
  6296. if (previousCamera) {
  6297. scene.activeCamera = previousCamera;
  6298. }
  6299. camera.getProjectionMatrix(true); // Force cache refresh;
  6300. };
  6301. // XHR response validator for local file scenario
  6302. Tools.ValidateXHRData = function (xhr, dataType) {
  6303. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6304. if (dataType === void 0) { dataType = 7; }
  6305. try {
  6306. if (dataType & 1) {
  6307. if (xhr.responseText && xhr.responseText.length > 0) {
  6308. return true;
  6309. }
  6310. else if (dataType === 1) {
  6311. return false;
  6312. }
  6313. }
  6314. if (dataType & 2) {
  6315. // Check header width and height since there is no "TGA" magic number
  6316. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6317. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6318. return true;
  6319. }
  6320. else if (dataType === 2) {
  6321. return false;
  6322. }
  6323. }
  6324. if (dataType & 4) {
  6325. // Check for the "DDS" magic number
  6326. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6327. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6328. return true;
  6329. }
  6330. else {
  6331. return false;
  6332. }
  6333. }
  6334. }
  6335. catch (e) {
  6336. // Global protection
  6337. }
  6338. return false;
  6339. };
  6340. /**
  6341. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6342. * Be aware Math.random() could cause collisions, but:
  6343. * "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"
  6344. */
  6345. Tools.RandomId = function () {
  6346. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6347. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6348. return v.toString(16);
  6349. });
  6350. };
  6351. Object.defineProperty(Tools, "NoneLogLevel", {
  6352. get: function () {
  6353. return Tools._NoneLogLevel;
  6354. },
  6355. enumerable: true,
  6356. configurable: true
  6357. });
  6358. Object.defineProperty(Tools, "MessageLogLevel", {
  6359. get: function () {
  6360. return Tools._MessageLogLevel;
  6361. },
  6362. enumerable: true,
  6363. configurable: true
  6364. });
  6365. Object.defineProperty(Tools, "WarningLogLevel", {
  6366. get: function () {
  6367. return Tools._WarningLogLevel;
  6368. },
  6369. enumerable: true,
  6370. configurable: true
  6371. });
  6372. Object.defineProperty(Tools, "ErrorLogLevel", {
  6373. get: function () {
  6374. return Tools._ErrorLogLevel;
  6375. },
  6376. enumerable: true,
  6377. configurable: true
  6378. });
  6379. Object.defineProperty(Tools, "AllLogLevel", {
  6380. get: function () {
  6381. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6382. },
  6383. enumerable: true,
  6384. configurable: true
  6385. });
  6386. Tools._AddLogEntry = function (entry) {
  6387. Tools._LogCache = entry + Tools._LogCache;
  6388. if (Tools.OnNewCacheEntry) {
  6389. Tools.OnNewCacheEntry(entry);
  6390. }
  6391. };
  6392. Tools._FormatMessage = function (message) {
  6393. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6394. var date = new Date();
  6395. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6396. };
  6397. Tools._LogDisabled = function (message) {
  6398. // nothing to do
  6399. };
  6400. Tools._LogEnabled = function (message) {
  6401. var formattedMessage = Tools._FormatMessage(message);
  6402. console.log("BJS - " + formattedMessage);
  6403. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6404. Tools._AddLogEntry(entry);
  6405. };
  6406. Tools._WarnDisabled = function (message) {
  6407. // nothing to do
  6408. };
  6409. Tools._WarnEnabled = function (message) {
  6410. var formattedMessage = Tools._FormatMessage(message);
  6411. console.warn("BJS - " + formattedMessage);
  6412. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6413. Tools._AddLogEntry(entry);
  6414. };
  6415. Tools._ErrorDisabled = function (message) {
  6416. // nothing to do
  6417. };
  6418. Tools._ErrorEnabled = function (message) {
  6419. Tools.errorsCount++;
  6420. var formattedMessage = Tools._FormatMessage(message);
  6421. console.error("BJS - " + formattedMessage);
  6422. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6423. Tools._AddLogEntry(entry);
  6424. };
  6425. Object.defineProperty(Tools, "LogCache", {
  6426. get: function () {
  6427. return Tools._LogCache;
  6428. },
  6429. enumerable: true,
  6430. configurable: true
  6431. });
  6432. Tools.ClearLogCache = function () {
  6433. Tools._LogCache = "";
  6434. Tools.errorsCount = 0;
  6435. };
  6436. Object.defineProperty(Tools, "LogLevels", {
  6437. set: function (level) {
  6438. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6439. Tools.Log = Tools._LogEnabled;
  6440. }
  6441. else {
  6442. Tools.Log = Tools._LogDisabled;
  6443. }
  6444. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6445. Tools.Warn = Tools._WarnEnabled;
  6446. }
  6447. else {
  6448. Tools.Warn = Tools._WarnDisabled;
  6449. }
  6450. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6451. Tools.Error = Tools._ErrorEnabled;
  6452. }
  6453. else {
  6454. Tools.Error = Tools._ErrorDisabled;
  6455. }
  6456. },
  6457. enumerable: true,
  6458. configurable: true
  6459. });
  6460. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6461. get: function () {
  6462. return Tools._PerformanceNoneLogLevel;
  6463. },
  6464. enumerable: true,
  6465. configurable: true
  6466. });
  6467. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6468. get: function () {
  6469. return Tools._PerformanceUserMarkLogLevel;
  6470. },
  6471. enumerable: true,
  6472. configurable: true
  6473. });
  6474. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6475. get: function () {
  6476. return Tools._PerformanceConsoleLogLevel;
  6477. },
  6478. enumerable: true,
  6479. configurable: true
  6480. });
  6481. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6482. set: function (level) {
  6483. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6484. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6485. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6486. return;
  6487. }
  6488. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6489. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6490. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6491. return;
  6492. }
  6493. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6494. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6495. },
  6496. enumerable: true,
  6497. configurable: true
  6498. });
  6499. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6500. };
  6501. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6502. };
  6503. Tools._StartUserMark = function (counterName, condition) {
  6504. if (condition === void 0) { condition = true; }
  6505. if (!condition || !Tools._performance.mark) {
  6506. return;
  6507. }
  6508. Tools._performance.mark(counterName + "-Begin");
  6509. };
  6510. Tools._EndUserMark = function (counterName, condition) {
  6511. if (condition === void 0) { condition = true; }
  6512. if (!condition || !Tools._performance.mark) {
  6513. return;
  6514. }
  6515. Tools._performance.mark(counterName + "-End");
  6516. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6517. };
  6518. Tools._StartPerformanceConsole = function (counterName, condition) {
  6519. if (condition === void 0) { condition = true; }
  6520. if (!condition) {
  6521. return;
  6522. }
  6523. Tools._StartUserMark(counterName, condition);
  6524. if (console.time) {
  6525. console.time(counterName);
  6526. }
  6527. };
  6528. Tools._EndPerformanceConsole = function (counterName, condition) {
  6529. if (condition === void 0) { condition = true; }
  6530. if (!condition) {
  6531. return;
  6532. }
  6533. Tools._EndUserMark(counterName, condition);
  6534. if (console.time) {
  6535. console.timeEnd(counterName);
  6536. }
  6537. };
  6538. Object.defineProperty(Tools, "Now", {
  6539. get: function () {
  6540. if (window.performance && window.performance.now) {
  6541. return window.performance.now();
  6542. }
  6543. return new Date().getTime();
  6544. },
  6545. enumerable: true,
  6546. configurable: true
  6547. });
  6548. /**
  6549. * This method will return the name of the class used to create the instance of the given object.
  6550. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6551. * @param object the object to get the class name from
  6552. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6553. */
  6554. Tools.GetClassName = function (object, isType) {
  6555. if (isType === void 0) { isType = false; }
  6556. var name = null;
  6557. if (!isType && object.getClassName) {
  6558. name = object.getClassName();
  6559. }
  6560. else {
  6561. if (object instanceof Object) {
  6562. var classObj = isType ? object : Object.getPrototypeOf(object);
  6563. name = classObj.constructor["__bjsclassName__"];
  6564. }
  6565. if (!name) {
  6566. name = typeof object;
  6567. }
  6568. }
  6569. return name;
  6570. };
  6571. Tools.first = function (array, predicate) {
  6572. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6573. var el = array_1[_i];
  6574. if (predicate(el)) {
  6575. return el;
  6576. }
  6577. }
  6578. };
  6579. /**
  6580. * This method will return the name of the full name of the class, including its owning module (if any).
  6581. * 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).
  6582. * @param object the object to get the class name from
  6583. * @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.
  6584. */
  6585. Tools.getFullClassName = function (object, isType) {
  6586. if (isType === void 0) { isType = false; }
  6587. var className = null;
  6588. var moduleName = null;
  6589. if (!isType && object.getClassName) {
  6590. className = object.getClassName();
  6591. }
  6592. else {
  6593. if (object instanceof Object) {
  6594. var classObj = isType ? object : Object.getPrototypeOf(object);
  6595. className = classObj.constructor["__bjsclassName__"];
  6596. moduleName = classObj.constructor["__bjsmoduleName__"];
  6597. }
  6598. if (!className) {
  6599. className = typeof object;
  6600. }
  6601. }
  6602. if (!className) {
  6603. return null;
  6604. }
  6605. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6606. };
  6607. /**
  6608. * 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.
  6609. * @param array
  6610. */
  6611. Tools.arrayOrStringFeeder = function (array) {
  6612. return function (index) {
  6613. if (index >= array.length) {
  6614. return null;
  6615. }
  6616. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6617. if (val && val.getHashCode) {
  6618. val = val.getHashCode();
  6619. }
  6620. if (typeof val === "string") {
  6621. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6622. }
  6623. return val;
  6624. };
  6625. };
  6626. /**
  6627. * Compute the hashCode of a stream of number
  6628. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6629. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6630. * @return the hash code computed
  6631. */
  6632. Tools.hashCodeFromStream = function (feeder) {
  6633. // Based from here: http://stackoverflow.com/a/7616484/802124
  6634. var hash = 0;
  6635. var index = 0;
  6636. var chr = feeder(index++);
  6637. while (chr != null) {
  6638. hash = ((hash << 5) - hash) + chr;
  6639. hash |= 0; // Convert to 32bit integer
  6640. chr = feeder(index++);
  6641. }
  6642. return hash;
  6643. };
  6644. Tools.BaseUrl = "";
  6645. Tools.CorsBehavior = "anonymous";
  6646. Tools.UseFallbackTexture = true;
  6647. // Used in case of a texture loading problem
  6648. 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";
  6649. Tools.PreprocessUrl = function (url) {
  6650. return url;
  6651. };
  6652. // Logs
  6653. Tools._NoneLogLevel = 0;
  6654. Tools._MessageLogLevel = 1;
  6655. Tools._WarningLogLevel = 2;
  6656. Tools._ErrorLogLevel = 4;
  6657. Tools._LogCache = "";
  6658. Tools.errorsCount = 0;
  6659. Tools.Log = Tools._LogEnabled;
  6660. Tools.Warn = Tools._WarnEnabled;
  6661. Tools.Error = Tools._ErrorEnabled;
  6662. // Performances
  6663. Tools._PerformanceNoneLogLevel = 0;
  6664. Tools._PerformanceUserMarkLogLevel = 1;
  6665. Tools._PerformanceConsoleLogLevel = 2;
  6666. Tools._performance = window.performance;
  6667. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6668. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6669. return Tools;
  6670. }());
  6671. BABYLON.Tools = Tools;
  6672. /**
  6673. * This class is used to track a performance counter which is number based.
  6674. * The user has access to many properties which give statistics of different nature
  6675. *
  6676. * The implementer can track two kinds of Performance Counter: time and count
  6677. * 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.
  6678. * 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.
  6679. */
  6680. var PerfCounter = (function () {
  6681. function PerfCounter() {
  6682. this._startMonitoringTime = 0;
  6683. this._min = 0;
  6684. this._max = 0;
  6685. this._average = 0;
  6686. this._lastSecAverage = 0;
  6687. this._current = 0;
  6688. this._totalValueCount = 0;
  6689. this._totalAccumulated = 0;
  6690. this._lastSecAccumulated = 0;
  6691. this._lastSecTime = 0;
  6692. this._lastSecValueCount = 0;
  6693. }
  6694. Object.defineProperty(PerfCounter.prototype, "min", {
  6695. /**
  6696. * Returns the smallest value ever
  6697. */
  6698. get: function () {
  6699. return this._min;
  6700. },
  6701. enumerable: true,
  6702. configurable: true
  6703. });
  6704. Object.defineProperty(PerfCounter.prototype, "max", {
  6705. /**
  6706. * Returns the biggest value ever
  6707. */
  6708. get: function () {
  6709. return this._max;
  6710. },
  6711. enumerable: true,
  6712. configurable: true
  6713. });
  6714. Object.defineProperty(PerfCounter.prototype, "average", {
  6715. /**
  6716. * Returns the average value since the performance counter is running
  6717. */
  6718. get: function () {
  6719. return this._average;
  6720. },
  6721. enumerable: true,
  6722. configurable: true
  6723. });
  6724. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6725. /**
  6726. * Returns the average value of the last second the counter was monitored
  6727. */
  6728. get: function () {
  6729. return this._lastSecAverage;
  6730. },
  6731. enumerable: true,
  6732. configurable: true
  6733. });
  6734. Object.defineProperty(PerfCounter.prototype, "current", {
  6735. /**
  6736. * Returns the current value
  6737. */
  6738. get: function () {
  6739. return this._current;
  6740. },
  6741. enumerable: true,
  6742. configurable: true
  6743. });
  6744. Object.defineProperty(PerfCounter.prototype, "total", {
  6745. get: function () {
  6746. return this._totalAccumulated;
  6747. },
  6748. enumerable: true,
  6749. configurable: true
  6750. });
  6751. /**
  6752. * Call this method to start monitoring a new frame.
  6753. * 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.
  6754. */
  6755. PerfCounter.prototype.fetchNewFrame = function () {
  6756. this._totalValueCount++;
  6757. this._current = 0;
  6758. this._lastSecValueCount++;
  6759. };
  6760. /**
  6761. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6762. * @param newCount the count value to add to the monitored count
  6763. * @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.
  6764. */
  6765. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6766. if (!PerfCounter.Enabled) {
  6767. return;
  6768. }
  6769. this._current += newCount;
  6770. if (fetchResult) {
  6771. this._fetchResult();
  6772. }
  6773. };
  6774. /**
  6775. * Start monitoring this performance counter
  6776. */
  6777. PerfCounter.prototype.beginMonitoring = function () {
  6778. if (!PerfCounter.Enabled) {
  6779. return;
  6780. }
  6781. this._startMonitoringTime = Tools.Now;
  6782. };
  6783. /**
  6784. * Compute the time lapsed since the previous beginMonitoring() call.
  6785. * @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
  6786. */
  6787. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6788. if (newFrame === void 0) { newFrame = true; }
  6789. if (!PerfCounter.Enabled) {
  6790. return;
  6791. }
  6792. if (newFrame) {
  6793. this.fetchNewFrame();
  6794. }
  6795. var currentTime = Tools.Now;
  6796. this._current = currentTime - this._startMonitoringTime;
  6797. if (newFrame) {
  6798. this._fetchResult();
  6799. }
  6800. };
  6801. PerfCounter.prototype._fetchResult = function () {
  6802. this._totalAccumulated += this._current;
  6803. this._lastSecAccumulated += this._current;
  6804. // Min/Max update
  6805. this._min = Math.min(this._min, this._current);
  6806. this._max = Math.max(this._max, this._current);
  6807. this._average = this._totalAccumulated / this._totalValueCount;
  6808. // Reset last sec?
  6809. var now = Tools.Now;
  6810. if ((now - this._lastSecTime) > 1000) {
  6811. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6812. this._lastSecTime = now;
  6813. this._lastSecAccumulated = 0;
  6814. this._lastSecValueCount = 0;
  6815. }
  6816. };
  6817. PerfCounter.Enabled = true;
  6818. return PerfCounter;
  6819. }());
  6820. BABYLON.PerfCounter = PerfCounter;
  6821. /**
  6822. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6823. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6824. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6825. * @param name The name of the class, case should be preserved
  6826. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6827. */
  6828. function className(name, module) {
  6829. return function (target) {
  6830. target["__bjsclassName__"] = name;
  6831. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6832. };
  6833. }
  6834. BABYLON.className = className;
  6835. /**
  6836. * An implementation of a loop for asynchronous functions.
  6837. */
  6838. var AsyncLoop = (function () {
  6839. /**
  6840. * Constroctor.
  6841. * @param iterations the number of iterations.
  6842. * @param _fn the function to run each iteration
  6843. * @param _successCallback the callback that will be called upon succesful execution
  6844. * @param offset starting offset.
  6845. */
  6846. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6847. if (offset === void 0) { offset = 0; }
  6848. this.iterations = iterations;
  6849. this._fn = _fn;
  6850. this._successCallback = _successCallback;
  6851. this.index = offset - 1;
  6852. this._done = false;
  6853. }
  6854. /**
  6855. * Execute the next iteration. Must be called after the last iteration was finished.
  6856. */
  6857. AsyncLoop.prototype.executeNext = function () {
  6858. if (!this._done) {
  6859. if (this.index + 1 < this.iterations) {
  6860. ++this.index;
  6861. this._fn(this);
  6862. }
  6863. else {
  6864. this.breakLoop();
  6865. }
  6866. }
  6867. };
  6868. /**
  6869. * Break the loop and run the success callback.
  6870. */
  6871. AsyncLoop.prototype.breakLoop = function () {
  6872. this._done = true;
  6873. this._successCallback();
  6874. };
  6875. /**
  6876. * Helper function
  6877. */
  6878. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6879. if (offset === void 0) { offset = 0; }
  6880. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6881. loop.executeNext();
  6882. return loop;
  6883. };
  6884. /**
  6885. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6886. * @param iterations total number of iterations
  6887. * @param syncedIterations number of synchronous iterations in each async iteration.
  6888. * @param fn the function to call each iteration.
  6889. * @param callback a success call back that will be called when iterating stops.
  6890. * @param breakFunction a break condition (optional)
  6891. * @param timeout timeout settings for the setTimeout function. default - 0.
  6892. * @constructor
  6893. */
  6894. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6895. if (timeout === void 0) { timeout = 0; }
  6896. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6897. if (breakFunction && breakFunction())
  6898. loop.breakLoop();
  6899. else {
  6900. setTimeout(function () {
  6901. for (var i = 0; i < syncedIterations; ++i) {
  6902. var iteration = (loop.index * syncedIterations) + i;
  6903. if (iteration >= iterations)
  6904. break;
  6905. fn(iteration);
  6906. if (breakFunction && breakFunction()) {
  6907. loop.breakLoop();
  6908. break;
  6909. }
  6910. }
  6911. loop.executeNext();
  6912. }, timeout);
  6913. }
  6914. }, callback);
  6915. };
  6916. return AsyncLoop;
  6917. }());
  6918. BABYLON.AsyncLoop = AsyncLoop;
  6919. })(BABYLON || (BABYLON = {}));
  6920. //# sourceMappingURL=babylon.tools.js.map
  6921. var BABYLON;
  6922. (function (BABYLON) {
  6923. var Internals;
  6924. (function (Internals) {
  6925. var _AlphaState = (function () {
  6926. /**
  6927. * Initializes the state.
  6928. */
  6929. function _AlphaState() {
  6930. this._isAlphaBlendDirty = false;
  6931. this._isBlendFunctionParametersDirty = false;
  6932. this._isBlendEquationParametersDirty = false;
  6933. this._isBlendConstantsDirty = false;
  6934. this._alphaBlend = false;
  6935. this._blendFunctionParameters = new Array(4);
  6936. this._blendEquationParameters = new Array(2);
  6937. this._blendConstants = new Array(4);
  6938. this.reset();
  6939. }
  6940. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6941. get: function () {
  6942. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6943. },
  6944. enumerable: true,
  6945. configurable: true
  6946. });
  6947. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6948. get: function () {
  6949. return this._alphaBlend;
  6950. },
  6951. set: function (value) {
  6952. if (this._alphaBlend === value) {
  6953. return;
  6954. }
  6955. this._alphaBlend = value;
  6956. this._isAlphaBlendDirty = true;
  6957. },
  6958. enumerable: true,
  6959. configurable: true
  6960. });
  6961. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6962. if (this._blendConstants[0] === r &&
  6963. this._blendConstants[1] === g &&
  6964. this._blendConstants[2] === b &&
  6965. this._blendConstants[3] === a) {
  6966. return;
  6967. }
  6968. this._blendConstants[0] = r;
  6969. this._blendConstants[1] = g;
  6970. this._blendConstants[2] = b;
  6971. this._blendConstants[3] = a;
  6972. this._isBlendConstantsDirty = true;
  6973. };
  6974. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6975. if (this._blendFunctionParameters[0] === value0 &&
  6976. this._blendFunctionParameters[1] === value1 &&
  6977. this._blendFunctionParameters[2] === value2 &&
  6978. this._blendFunctionParameters[3] === value3) {
  6979. return;
  6980. }
  6981. this._blendFunctionParameters[0] = value0;
  6982. this._blendFunctionParameters[1] = value1;
  6983. this._blendFunctionParameters[2] = value2;
  6984. this._blendFunctionParameters[3] = value3;
  6985. this._isBlendFunctionParametersDirty = true;
  6986. };
  6987. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6988. if (this._blendEquationParameters[0] === rgb &&
  6989. this._blendEquationParameters[1] === alpha) {
  6990. return;
  6991. }
  6992. this._blendEquationParameters[0] = rgb;
  6993. this._blendEquationParameters[1] = alpha;
  6994. this._isBlendEquationParametersDirty = true;
  6995. };
  6996. _AlphaState.prototype.reset = function () {
  6997. this._alphaBlend = false;
  6998. this._blendFunctionParameters[0] = null;
  6999. this._blendFunctionParameters[1] = null;
  7000. this._blendFunctionParameters[2] = null;
  7001. this._blendFunctionParameters[3] = null;
  7002. this._blendEquationParameters[0] = null;
  7003. this._blendEquationParameters[1] = null;
  7004. this._blendConstants[0] = null;
  7005. this._blendConstants[1] = null;
  7006. this._blendConstants[2] = null;
  7007. this._blendConstants[3] = null;
  7008. this._isAlphaBlendDirty = true;
  7009. this._isBlendFunctionParametersDirty = false;
  7010. this._isBlendEquationParametersDirty = false;
  7011. this._isBlendConstantsDirty = false;
  7012. };
  7013. _AlphaState.prototype.apply = function (gl) {
  7014. if (!this.isDirty) {
  7015. return;
  7016. }
  7017. // Alpha blend
  7018. if (this._isAlphaBlendDirty) {
  7019. if (this._alphaBlend) {
  7020. gl.enable(gl.BLEND);
  7021. }
  7022. else {
  7023. gl.disable(gl.BLEND);
  7024. }
  7025. this._isAlphaBlendDirty = false;
  7026. }
  7027. // Alpha function
  7028. if (this._isBlendFunctionParametersDirty) {
  7029. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7030. this._isBlendFunctionParametersDirty = false;
  7031. }
  7032. // Alpha equation
  7033. if (this._isBlendEquationParametersDirty) {
  7034. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7035. this._isBlendEquationParametersDirty = false;
  7036. }
  7037. // Constants
  7038. if (this._isBlendConstantsDirty) {
  7039. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7040. this._isBlendConstantsDirty = false;
  7041. }
  7042. };
  7043. return _AlphaState;
  7044. }());
  7045. Internals._AlphaState = _AlphaState;
  7046. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7047. })(BABYLON || (BABYLON = {}));
  7048. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7049. var BABYLON;
  7050. (function (BABYLON) {
  7051. var Internals;
  7052. (function (Internals) {
  7053. var _DepthCullingState = (function () {
  7054. /**
  7055. * Initializes the state.
  7056. */
  7057. function _DepthCullingState() {
  7058. this._isDepthTestDirty = false;
  7059. this._isDepthMaskDirty = false;
  7060. this._isDepthFuncDirty = false;
  7061. this._isCullFaceDirty = false;
  7062. this._isCullDirty = false;
  7063. this._isZOffsetDirty = false;
  7064. this.reset();
  7065. }
  7066. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7067. get: function () {
  7068. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7069. },
  7070. enumerable: true,
  7071. configurable: true
  7072. });
  7073. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7074. get: function () {
  7075. return this._zOffset;
  7076. },
  7077. set: function (value) {
  7078. if (this._zOffset === value) {
  7079. return;
  7080. }
  7081. this._zOffset = value;
  7082. this._isZOffsetDirty = true;
  7083. },
  7084. enumerable: true,
  7085. configurable: true
  7086. });
  7087. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7088. get: function () {
  7089. return this._cullFace;
  7090. },
  7091. set: function (value) {
  7092. if (this._cullFace === value) {
  7093. return;
  7094. }
  7095. this._cullFace = value;
  7096. this._isCullFaceDirty = true;
  7097. },
  7098. enumerable: true,
  7099. configurable: true
  7100. });
  7101. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7102. get: function () {
  7103. return this._cull;
  7104. },
  7105. set: function (value) {
  7106. if (this._cull === value) {
  7107. return;
  7108. }
  7109. this._cull = value;
  7110. this._isCullDirty = true;
  7111. },
  7112. enumerable: true,
  7113. configurable: true
  7114. });
  7115. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7116. get: function () {
  7117. return this._depthFunc;
  7118. },
  7119. set: function (value) {
  7120. if (this._depthFunc === value) {
  7121. return;
  7122. }
  7123. this._depthFunc = value;
  7124. this._isDepthFuncDirty = true;
  7125. },
  7126. enumerable: true,
  7127. configurable: true
  7128. });
  7129. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7130. get: function () {
  7131. return this._depthMask;
  7132. },
  7133. set: function (value) {
  7134. if (this._depthMask === value) {
  7135. return;
  7136. }
  7137. this._depthMask = value;
  7138. this._isDepthMaskDirty = true;
  7139. },
  7140. enumerable: true,
  7141. configurable: true
  7142. });
  7143. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7144. get: function () {
  7145. return this._depthTest;
  7146. },
  7147. set: function (value) {
  7148. if (this._depthTest === value) {
  7149. return;
  7150. }
  7151. this._depthTest = value;
  7152. this._isDepthTestDirty = true;
  7153. },
  7154. enumerable: true,
  7155. configurable: true
  7156. });
  7157. _DepthCullingState.prototype.reset = function () {
  7158. this._depthMask = true;
  7159. this._depthTest = true;
  7160. this._depthFunc = null;
  7161. this._cullFace = null;
  7162. this._cull = null;
  7163. this._zOffset = 0;
  7164. this._isDepthTestDirty = true;
  7165. this._isDepthMaskDirty = true;
  7166. this._isDepthFuncDirty = false;
  7167. this._isCullFaceDirty = false;
  7168. this._isCullDirty = false;
  7169. this._isZOffsetDirty = false;
  7170. };
  7171. _DepthCullingState.prototype.apply = function (gl) {
  7172. if (!this.isDirty) {
  7173. return;
  7174. }
  7175. // Cull
  7176. if (this._isCullDirty) {
  7177. if (this.cull) {
  7178. gl.enable(gl.CULL_FACE);
  7179. }
  7180. else {
  7181. gl.disable(gl.CULL_FACE);
  7182. }
  7183. this._isCullDirty = false;
  7184. }
  7185. // Cull face
  7186. if (this._isCullFaceDirty) {
  7187. gl.cullFace(this.cullFace);
  7188. this._isCullFaceDirty = false;
  7189. }
  7190. // Depth mask
  7191. if (this._isDepthMaskDirty) {
  7192. gl.depthMask(this.depthMask);
  7193. this._isDepthMaskDirty = false;
  7194. }
  7195. // Depth test
  7196. if (this._isDepthTestDirty) {
  7197. if (this.depthTest) {
  7198. gl.enable(gl.DEPTH_TEST);
  7199. }
  7200. else {
  7201. gl.disable(gl.DEPTH_TEST);
  7202. }
  7203. this._isDepthTestDirty = false;
  7204. }
  7205. // Depth func
  7206. if (this._isDepthFuncDirty) {
  7207. gl.depthFunc(this.depthFunc);
  7208. this._isDepthFuncDirty = false;
  7209. }
  7210. // zOffset
  7211. if (this._isZOffsetDirty) {
  7212. if (this.zOffset) {
  7213. gl.enable(gl.POLYGON_OFFSET_FILL);
  7214. gl.polygonOffset(this.zOffset, 0);
  7215. }
  7216. else {
  7217. gl.disable(gl.POLYGON_OFFSET_FILL);
  7218. }
  7219. this._isZOffsetDirty = false;
  7220. }
  7221. };
  7222. return _DepthCullingState;
  7223. }());
  7224. Internals._DepthCullingState = _DepthCullingState;
  7225. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7226. })(BABYLON || (BABYLON = {}));
  7227. //# sourceMappingURL=babylon.depthCullingState.js.map
  7228. var BABYLON;
  7229. (function (BABYLON) {
  7230. var Internals;
  7231. (function (Internals) {
  7232. var _StencilState = (function () {
  7233. function _StencilState() {
  7234. this._isStencilTestDirty = false;
  7235. this._isStencilMaskDirty = false;
  7236. this._isStencilFuncDirty = false;
  7237. this._isStencilOpDirty = false;
  7238. this.reset();
  7239. }
  7240. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7241. get: function () {
  7242. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7243. },
  7244. enumerable: true,
  7245. configurable: true
  7246. });
  7247. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7248. get: function () {
  7249. return this._stencilFunc;
  7250. },
  7251. set: function (value) {
  7252. if (this._stencilFunc === value) {
  7253. return;
  7254. }
  7255. this._stencilFunc = value;
  7256. this._isStencilFuncDirty = true;
  7257. },
  7258. enumerable: true,
  7259. configurable: true
  7260. });
  7261. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7262. get: function () {
  7263. return this._stencilFuncRef;
  7264. },
  7265. set: function (value) {
  7266. if (this._stencilFuncRef === value) {
  7267. return;
  7268. }
  7269. this._stencilFuncRef = value;
  7270. this._isStencilFuncDirty = true;
  7271. },
  7272. enumerable: true,
  7273. configurable: true
  7274. });
  7275. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7276. get: function () {
  7277. return this._stencilFuncMask;
  7278. },
  7279. set: function (value) {
  7280. if (this._stencilFuncMask === value) {
  7281. return;
  7282. }
  7283. this._stencilFuncMask = value;
  7284. this._isStencilFuncDirty = true;
  7285. },
  7286. enumerable: true,
  7287. configurable: true
  7288. });
  7289. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7290. get: function () {
  7291. return this._stencilOpStencilFail;
  7292. },
  7293. set: function (value) {
  7294. if (this._stencilOpStencilFail === value) {
  7295. return;
  7296. }
  7297. this._stencilOpStencilFail = value;
  7298. this._isStencilOpDirty = true;
  7299. },
  7300. enumerable: true,
  7301. configurable: true
  7302. });
  7303. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7304. get: function () {
  7305. return this._stencilOpDepthFail;
  7306. },
  7307. set: function (value) {
  7308. if (this._stencilOpDepthFail === value) {
  7309. return;
  7310. }
  7311. this._stencilOpDepthFail = value;
  7312. this._isStencilOpDirty = true;
  7313. },
  7314. enumerable: true,
  7315. configurable: true
  7316. });
  7317. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7318. get: function () {
  7319. return this._stencilOpStencilDepthPass;
  7320. },
  7321. set: function (value) {
  7322. if (this._stencilOpStencilDepthPass === value) {
  7323. return;
  7324. }
  7325. this._stencilOpStencilDepthPass = value;
  7326. this._isStencilOpDirty = true;
  7327. },
  7328. enumerable: true,
  7329. configurable: true
  7330. });
  7331. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7332. get: function () {
  7333. return this._stencilMask;
  7334. },
  7335. set: function (value) {
  7336. if (this._stencilMask === value) {
  7337. return;
  7338. }
  7339. this._stencilMask = value;
  7340. this._isStencilMaskDirty = true;
  7341. },
  7342. enumerable: true,
  7343. configurable: true
  7344. });
  7345. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7346. get: function () {
  7347. return this._stencilTest;
  7348. },
  7349. set: function (value) {
  7350. if (this._stencilTest === value) {
  7351. return;
  7352. }
  7353. this._stencilTest = value;
  7354. this._isStencilTestDirty = true;
  7355. },
  7356. enumerable: true,
  7357. configurable: true
  7358. });
  7359. _StencilState.prototype.reset = function () {
  7360. this._stencilTest = false;
  7361. this._stencilMask = 0xFF;
  7362. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7363. this._stencilFuncRef = 1;
  7364. this._stencilFuncMask = 0xFF;
  7365. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7366. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7367. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7368. this._isStencilTestDirty = true;
  7369. this._isStencilMaskDirty = true;
  7370. this._isStencilFuncDirty = true;
  7371. this._isStencilOpDirty = true;
  7372. };
  7373. _StencilState.prototype.apply = function (gl) {
  7374. if (!this.isDirty) {
  7375. return;
  7376. }
  7377. // Stencil test
  7378. if (this._isStencilTestDirty) {
  7379. if (this.stencilTest) {
  7380. gl.enable(gl.STENCIL_TEST);
  7381. }
  7382. else {
  7383. gl.disable(gl.STENCIL_TEST);
  7384. }
  7385. this._isStencilTestDirty = false;
  7386. }
  7387. // Stencil mask
  7388. if (this._isStencilMaskDirty) {
  7389. gl.stencilMask(this.stencilMask);
  7390. this._isStencilMaskDirty = false;
  7391. }
  7392. // Stencil func
  7393. if (this._isStencilFuncDirty) {
  7394. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7395. this._isStencilFuncDirty = false;
  7396. }
  7397. // Stencil op
  7398. if (this._isStencilOpDirty) {
  7399. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7400. this._isStencilOpDirty = false;
  7401. }
  7402. };
  7403. return _StencilState;
  7404. }());
  7405. Internals._StencilState = _StencilState;
  7406. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7407. })(BABYLON || (BABYLON = {}));
  7408. //# sourceMappingURL=babylon.stencilState.js.map
  7409. var BABYLON;
  7410. (function (BABYLON) {
  7411. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7412. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7413. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7414. gl.compileShader(shader);
  7415. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7416. throw new Error(gl.getShaderInfoLog(shader));
  7417. }
  7418. return shader;
  7419. };
  7420. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7421. var magFilter = gl.NEAREST;
  7422. var minFilter = gl.NEAREST;
  7423. switch (samplingMode) {
  7424. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7425. magFilter = gl.LINEAR;
  7426. if (generateMipMaps) {
  7427. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7428. }
  7429. else {
  7430. minFilter = gl.LINEAR;
  7431. }
  7432. break;
  7433. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7434. magFilter = gl.LINEAR;
  7435. if (generateMipMaps) {
  7436. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7437. }
  7438. else {
  7439. minFilter = gl.LINEAR;
  7440. }
  7441. break;
  7442. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7443. magFilter = gl.NEAREST;
  7444. if (generateMipMaps) {
  7445. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7446. }
  7447. else {
  7448. minFilter = gl.NEAREST;
  7449. }
  7450. break;
  7451. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7452. magFilter = gl.NEAREST;
  7453. if (generateMipMaps) {
  7454. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7455. }
  7456. else {
  7457. minFilter = gl.NEAREST;
  7458. }
  7459. break;
  7460. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7461. magFilter = gl.NEAREST;
  7462. if (generateMipMaps) {
  7463. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7464. }
  7465. else {
  7466. minFilter = gl.LINEAR;
  7467. }
  7468. break;
  7469. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7470. magFilter = gl.NEAREST;
  7471. if (generateMipMaps) {
  7472. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7473. }
  7474. else {
  7475. minFilter = gl.LINEAR;
  7476. }
  7477. break;
  7478. case BABYLON.Texture.NEAREST_LINEAR:
  7479. magFilter = gl.NEAREST;
  7480. minFilter = gl.LINEAR;
  7481. break;
  7482. case BABYLON.Texture.NEAREST_NEAREST:
  7483. magFilter = gl.NEAREST;
  7484. minFilter = gl.NEAREST;
  7485. break;
  7486. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7487. magFilter = gl.LINEAR;
  7488. if (generateMipMaps) {
  7489. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7490. }
  7491. else {
  7492. minFilter = gl.NEAREST;
  7493. }
  7494. break;
  7495. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7496. magFilter = gl.LINEAR;
  7497. if (generateMipMaps) {
  7498. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7499. }
  7500. else {
  7501. minFilter = gl.NEAREST;
  7502. }
  7503. break;
  7504. case BABYLON.Texture.LINEAR_LINEAR:
  7505. magFilter = gl.LINEAR;
  7506. minFilter = gl.LINEAR;
  7507. break;
  7508. case BABYLON.Texture.LINEAR_NEAREST:
  7509. magFilter = gl.LINEAR;
  7510. minFilter = gl.NEAREST;
  7511. break;
  7512. }
  7513. return {
  7514. min: minFilter,
  7515. mag: magFilter
  7516. };
  7517. };
  7518. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7519. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7520. var img;
  7521. var onload = function () {
  7522. loadedImages[index] = img;
  7523. loadedImages._internalCount++;
  7524. if (scene) {
  7525. scene._removePendingData(img);
  7526. }
  7527. if (loadedImages._internalCount === 6) {
  7528. onfinish(loadedImages);
  7529. }
  7530. };
  7531. var onerror = function () {
  7532. if (scene) {
  7533. scene._removePendingData(img);
  7534. }
  7535. if (onErrorCallBack) {
  7536. onErrorCallBack();
  7537. }
  7538. };
  7539. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7540. if (scene) {
  7541. scene._addPendingData(img);
  7542. }
  7543. };
  7544. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7545. if (onError === void 0) { onError = null; }
  7546. var loadedImages = [];
  7547. loadedImages._internalCount = 0;
  7548. for (var index = 0; index < 6; index++) {
  7549. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7550. }
  7551. };
  7552. var BufferPointer = (function () {
  7553. function BufferPointer() {
  7554. }
  7555. return BufferPointer;
  7556. }());
  7557. var InstancingAttributeInfo = (function () {
  7558. function InstancingAttributeInfo() {
  7559. }
  7560. return InstancingAttributeInfo;
  7561. }());
  7562. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7563. /**
  7564. * Define options used to create a render target texture
  7565. */
  7566. var RenderTargetCreationOptions = (function () {
  7567. function RenderTargetCreationOptions() {
  7568. }
  7569. return RenderTargetCreationOptions;
  7570. }());
  7571. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7572. /**
  7573. * Regroup several parameters relative to the browser in use
  7574. */
  7575. var EngineCapabilities = (function () {
  7576. function EngineCapabilities() {
  7577. }
  7578. return EngineCapabilities;
  7579. }());
  7580. BABYLON.EngineCapabilities = EngineCapabilities;
  7581. /**
  7582. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7583. */
  7584. var Engine = (function () {
  7585. /**
  7586. * @constructor
  7587. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7588. * @param {boolean} [antialias] - enable antialias
  7589. * @param options - further options to be sent to the getContext function
  7590. */
  7591. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7592. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7593. var _this = this;
  7594. // Public members
  7595. this.forcePOTTextures = false;
  7596. this.isFullscreen = false;
  7597. this.isPointerLock = false;
  7598. this.cullBackFaces = true;
  7599. this.renderEvenInBackground = true;
  7600. this.preventCacheWipeBetweenFrames = false;
  7601. // To enable/disable IDB support and avoid XHR on .manifest
  7602. this.enableOfflineSupport = false;
  7603. this.scenes = new Array();
  7604. this.postProcesses = new Array();
  7605. // Observables
  7606. /**
  7607. * Observable event triggered each time the rendering canvas is resized
  7608. */
  7609. this.onResizeObservable = new BABYLON.Observable();
  7610. /**
  7611. * Observable event triggered each time the canvas loses focus
  7612. */
  7613. this.onCanvasBlurObservable = new BABYLON.Observable();
  7614. /**
  7615. * Observable event triggered each time the canvas gains focus
  7616. */
  7617. this.onCanvasFocusObservable = new BABYLON.Observable();
  7618. /**
  7619. * Observable event triggered each time the canvas receives pointerout event
  7620. */
  7621. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7622. this._vrExclusivePointerMode = false;
  7623. // Uniform buffers list
  7624. this.disableUniformBuffers = false;
  7625. this._uniformBuffers = new Array();
  7626. this._windowIsBackground = false;
  7627. this._webGLVersion = 1.0;
  7628. this._badOS = false;
  7629. this._badDesktopOS = false;
  7630. this._colorWrite = true;
  7631. this._drawCalls = new BABYLON.PerfCounter();
  7632. this._renderingQueueLaunched = false;
  7633. this._activeRenderLoops = [];
  7634. // Deterministic lockstepMaxSteps
  7635. this._deterministicLockstep = false;
  7636. this._lockstepMaxSteps = 4;
  7637. // Lost context
  7638. this.onContextLostObservable = new BABYLON.Observable();
  7639. this.onContextRestoredObservable = new BABYLON.Observable();
  7640. this._contextWasLost = false;
  7641. this._doNotHandleContextLost = false;
  7642. // FPS
  7643. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7644. this._fps = 60;
  7645. this._deltaTime = 0;
  7646. /**
  7647. * Turn this value on if you want to pause FPS computation when in background
  7648. */
  7649. this.disablePerformanceMonitorInBackground = false;
  7650. // States
  7651. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7652. this._stencilState = new BABYLON.Internals._StencilState();
  7653. this._alphaState = new BABYLON.Internals._AlphaState();
  7654. this._alphaMode = Engine.ALPHA_DISABLE;
  7655. // Cache
  7656. this._internalTexturesCache = new Array();
  7657. this._maxTextureChannels = 16;
  7658. this._activeTexturesCache = {};
  7659. this._compiledEffects = {};
  7660. this._vertexAttribArraysEnabled = [];
  7661. this._uintIndicesCurrentlySet = false;
  7662. this._currentBoundBuffer = new Array();
  7663. this._currentBufferPointers = new Array();
  7664. this._currentInstanceLocations = new Array();
  7665. this._currentInstanceBuffers = new Array();
  7666. this._vaoRecordInProgress = false;
  7667. this._mustWipeVertexAttributes = false;
  7668. // Hardware supported Compressed Textures
  7669. this._texturesSupported = new Array();
  7670. this._onVRFullScreenTriggered = function () {
  7671. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7672. //get the old size before we change
  7673. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7674. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7675. //get the width and height, change the render size
  7676. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7677. var width, height;
  7678. _this.setHardwareScalingLevel(1);
  7679. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7680. }
  7681. else {
  7682. //When the specs are implemented, need to uncomment this.
  7683. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7684. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7685. _this._vrDisplayEnabled = undefined;
  7686. }
  7687. };
  7688. var canvas;
  7689. Engine.Instances.push(this);
  7690. options = options || {};
  7691. if (canvasOrContext.getContext) {
  7692. canvas = canvasOrContext;
  7693. this._renderingCanvas = canvas;
  7694. if (antialias != null) {
  7695. options.antialias = antialias;
  7696. }
  7697. if (options.deterministicLockstep === undefined) {
  7698. options.deterministicLockstep = false;
  7699. }
  7700. if (options.lockstepMaxSteps === undefined) {
  7701. options.lockstepMaxSteps = 4;
  7702. }
  7703. if (options.preserveDrawingBuffer === undefined) {
  7704. options.preserveDrawingBuffer = false;
  7705. }
  7706. if (options.audioEngine === undefined) {
  7707. options.audioEngine = true;
  7708. }
  7709. if (options.stencil === undefined) {
  7710. options.stencil = true;
  7711. }
  7712. this._deterministicLockstep = options.deterministicLockstep;
  7713. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7714. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7715. // GL
  7716. if (!options.disableWebGL2Support) {
  7717. try {
  7718. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7719. if (this._gl) {
  7720. this._webGLVersion = 2.0;
  7721. }
  7722. }
  7723. catch (e) {
  7724. // Do nothing
  7725. }
  7726. }
  7727. if (!this._gl) {
  7728. if (!canvas) {
  7729. throw new Error("The provided canvas is null or undefined.");
  7730. }
  7731. try {
  7732. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7733. }
  7734. catch (e) {
  7735. throw new Error("WebGL not supported");
  7736. }
  7737. }
  7738. if (!this._gl) {
  7739. throw new Error("WebGL not supported");
  7740. }
  7741. this._onCanvasFocus = function () {
  7742. _this.onCanvasFocusObservable.notifyObservers(_this);
  7743. };
  7744. this._onCanvasBlur = function () {
  7745. _this.onCanvasBlurObservable.notifyObservers(_this);
  7746. };
  7747. canvas.addEventListener("focus", this._onCanvasFocus);
  7748. canvas.addEventListener("blur", this._onCanvasBlur);
  7749. this._onBlur = function () {
  7750. if (_this.disablePerformanceMonitorInBackground) {
  7751. _this._performanceMonitor.disable();
  7752. }
  7753. _this._windowIsBackground = true;
  7754. };
  7755. this._onFocus = function () {
  7756. if (_this.disablePerformanceMonitorInBackground) {
  7757. _this._performanceMonitor.enable();
  7758. }
  7759. _this._windowIsBackground = false;
  7760. };
  7761. this._onCanvasPointerOut = function () {
  7762. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7763. };
  7764. window.addEventListener("blur", this._onBlur);
  7765. window.addEventListener("focus", this._onFocus);
  7766. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7767. // Context lost
  7768. if (!this._doNotHandleContextLost) {
  7769. this._onContextLost = function (evt) {
  7770. evt.preventDefault();
  7771. _this._contextWasLost = true;
  7772. BABYLON.Tools.Warn("WebGL context lost.");
  7773. _this.onContextLostObservable.notifyObservers(_this);
  7774. };
  7775. this._onContextRestored = function (evt) {
  7776. // Adding a timeout to avoid race condition at browser level
  7777. setTimeout(function () {
  7778. // Rebuild gl context
  7779. _this._initGLContext();
  7780. // Rebuild effects
  7781. _this._rebuildEffects();
  7782. // Rebuild textures
  7783. _this._rebuildInternalTextures();
  7784. // Rebuild buffers
  7785. _this._rebuildBuffers();
  7786. // Cache
  7787. _this.wipeCaches(true);
  7788. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7789. _this.onContextRestoredObservable.notifyObservers(_this);
  7790. _this._contextWasLost = false;
  7791. }, 0);
  7792. };
  7793. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7794. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7795. }
  7796. }
  7797. else {
  7798. this._gl = canvasOrContext;
  7799. this._renderingCanvas = this._gl.canvas;
  7800. if (this._gl.renderbufferStorageMultisample) {
  7801. this._webGLVersion = 2.0;
  7802. }
  7803. options.stencil = this._gl.getContextAttributes().stencil;
  7804. }
  7805. // Viewport
  7806. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7807. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7808. this.resize();
  7809. this._isStencilEnable = options.stencil;
  7810. this._initGLContext();
  7811. if (canvas) {
  7812. // Fullscreen
  7813. this._onFullscreenChange = function () {
  7814. if (document.fullscreen !== undefined) {
  7815. _this.isFullscreen = document.fullscreen;
  7816. }
  7817. else if (document.mozFullScreen !== undefined) {
  7818. _this.isFullscreen = document.mozFullScreen;
  7819. }
  7820. else if (document.webkitIsFullScreen !== undefined) {
  7821. _this.isFullscreen = document.webkitIsFullScreen;
  7822. }
  7823. else if (document.msIsFullScreen !== undefined) {
  7824. _this.isFullscreen = document.msIsFullScreen;
  7825. }
  7826. // Pointer lock
  7827. if (_this.isFullscreen && _this._pointerLockRequested) {
  7828. canvas.requestPointerLock = canvas.requestPointerLock ||
  7829. canvas.msRequestPointerLock ||
  7830. canvas.mozRequestPointerLock ||
  7831. canvas.webkitRequestPointerLock;
  7832. if (canvas.requestPointerLock) {
  7833. canvas.requestPointerLock();
  7834. }
  7835. }
  7836. };
  7837. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7838. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7839. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7840. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7841. // Pointer lock
  7842. this._onPointerLockChange = function () {
  7843. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7844. document.webkitPointerLockElement === canvas ||
  7845. document.msPointerLockElement === canvas ||
  7846. document.pointerLockElement === canvas);
  7847. };
  7848. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7849. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7850. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7851. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7852. this._onVRDisplayPointerRestricted = function () {
  7853. _this._vrExclusivePointerMode = true;
  7854. canvas.requestPointerLock();
  7855. };
  7856. this._onVRDisplayPointerUnrestricted = function () {
  7857. _this._vrExclusivePointerMode = false;
  7858. document.exitPointerLock();
  7859. };
  7860. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7861. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7862. }
  7863. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7864. Engine.audioEngine = new BABYLON.AudioEngine();
  7865. }
  7866. // Prepare buffer pointers
  7867. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7868. this._currentBufferPointers[i] = new BufferPointer();
  7869. }
  7870. // Load WebVR Devices
  7871. if (options.autoEnableWebVR) {
  7872. this.initWebVR();
  7873. }
  7874. // Detect if we are running on a faulty buggy OS.
  7875. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7876. // Detect if we are running on a faulty buggy desktop OS.
  7877. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7878. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7879. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7880. }
  7881. Object.defineProperty(Engine, "LastCreatedEngine", {
  7882. get: function () {
  7883. if (Engine.Instances.length === 0) {
  7884. return null;
  7885. }
  7886. return Engine.Instances[Engine.Instances.length - 1];
  7887. },
  7888. enumerable: true,
  7889. configurable: true
  7890. });
  7891. Object.defineProperty(Engine, "LastCreatedScene", {
  7892. get: function () {
  7893. var lastCreatedEngine = Engine.LastCreatedEngine;
  7894. if (!lastCreatedEngine) {
  7895. return null;
  7896. }
  7897. if (lastCreatedEngine.scenes.length === 0) {
  7898. return null;
  7899. }
  7900. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7901. },
  7902. enumerable: true,
  7903. configurable: true
  7904. });
  7905. /**
  7906. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7907. */
  7908. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7909. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7910. var engine = Engine.Instances[engineIndex];
  7911. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7912. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7913. }
  7914. }
  7915. };
  7916. Object.defineProperty(Engine, "NEVER", {
  7917. get: function () {
  7918. return Engine._NEVER;
  7919. },
  7920. enumerable: true,
  7921. configurable: true
  7922. });
  7923. Object.defineProperty(Engine, "ALWAYS", {
  7924. get: function () {
  7925. return Engine._ALWAYS;
  7926. },
  7927. enumerable: true,
  7928. configurable: true
  7929. });
  7930. Object.defineProperty(Engine, "LESS", {
  7931. get: function () {
  7932. return Engine._LESS;
  7933. },
  7934. enumerable: true,
  7935. configurable: true
  7936. });
  7937. Object.defineProperty(Engine, "EQUAL", {
  7938. get: function () {
  7939. return Engine._EQUAL;
  7940. },
  7941. enumerable: true,
  7942. configurable: true
  7943. });
  7944. Object.defineProperty(Engine, "LEQUAL", {
  7945. get: function () {
  7946. return Engine._LEQUAL;
  7947. },
  7948. enumerable: true,
  7949. configurable: true
  7950. });
  7951. Object.defineProperty(Engine, "GREATER", {
  7952. get: function () {
  7953. return Engine._GREATER;
  7954. },
  7955. enumerable: true,
  7956. configurable: true
  7957. });
  7958. Object.defineProperty(Engine, "GEQUAL", {
  7959. get: function () {
  7960. return Engine._GEQUAL;
  7961. },
  7962. enumerable: true,
  7963. configurable: true
  7964. });
  7965. Object.defineProperty(Engine, "NOTEQUAL", {
  7966. get: function () {
  7967. return Engine._NOTEQUAL;
  7968. },
  7969. enumerable: true,
  7970. configurable: true
  7971. });
  7972. Object.defineProperty(Engine, "KEEP", {
  7973. get: function () {
  7974. return Engine._KEEP;
  7975. },
  7976. enumerable: true,
  7977. configurable: true
  7978. });
  7979. Object.defineProperty(Engine, "REPLACE", {
  7980. get: function () {
  7981. return Engine._REPLACE;
  7982. },
  7983. enumerable: true,
  7984. configurable: true
  7985. });
  7986. Object.defineProperty(Engine, "INCR", {
  7987. get: function () {
  7988. return Engine._INCR;
  7989. },
  7990. enumerable: true,
  7991. configurable: true
  7992. });
  7993. Object.defineProperty(Engine, "DECR", {
  7994. get: function () {
  7995. return Engine._DECR;
  7996. },
  7997. enumerable: true,
  7998. configurable: true
  7999. });
  8000. Object.defineProperty(Engine, "INVERT", {
  8001. get: function () {
  8002. return Engine._INVERT;
  8003. },
  8004. enumerable: true,
  8005. configurable: true
  8006. });
  8007. Object.defineProperty(Engine, "INCR_WRAP", {
  8008. get: function () {
  8009. return Engine._INCR_WRAP;
  8010. },
  8011. enumerable: true,
  8012. configurable: true
  8013. });
  8014. Object.defineProperty(Engine, "DECR_WRAP", {
  8015. get: function () {
  8016. return Engine._DECR_WRAP;
  8017. },
  8018. enumerable: true,
  8019. configurable: true
  8020. });
  8021. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8022. get: function () {
  8023. return Engine._ALPHA_DISABLE;
  8024. },
  8025. enumerable: true,
  8026. configurable: true
  8027. });
  8028. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8029. get: function () {
  8030. return Engine._ALPHA_ONEONE;
  8031. },
  8032. enumerable: true,
  8033. configurable: true
  8034. });
  8035. Object.defineProperty(Engine, "ALPHA_ADD", {
  8036. get: function () {
  8037. return Engine._ALPHA_ADD;
  8038. },
  8039. enumerable: true,
  8040. configurable: true
  8041. });
  8042. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8043. get: function () {
  8044. return Engine._ALPHA_COMBINE;
  8045. },
  8046. enumerable: true,
  8047. configurable: true
  8048. });
  8049. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8050. get: function () {
  8051. return Engine._ALPHA_SUBTRACT;
  8052. },
  8053. enumerable: true,
  8054. configurable: true
  8055. });
  8056. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8057. get: function () {
  8058. return Engine._ALPHA_MULTIPLY;
  8059. },
  8060. enumerable: true,
  8061. configurable: true
  8062. });
  8063. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8064. get: function () {
  8065. return Engine._ALPHA_MAXIMIZED;
  8066. },
  8067. enumerable: true,
  8068. configurable: true
  8069. });
  8070. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8071. get: function () {
  8072. return Engine._ALPHA_PREMULTIPLIED;
  8073. },
  8074. enumerable: true,
  8075. configurable: true
  8076. });
  8077. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8078. get: function () {
  8079. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8080. },
  8081. enumerable: true,
  8082. configurable: true
  8083. });
  8084. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8085. get: function () {
  8086. return Engine._ALPHA_INTERPOLATE;
  8087. },
  8088. enumerable: true,
  8089. configurable: true
  8090. });
  8091. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8092. get: function () {
  8093. return Engine._ALPHA_SCREENMODE;
  8094. },
  8095. enumerable: true,
  8096. configurable: true
  8097. });
  8098. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8099. get: function () {
  8100. return Engine._DELAYLOADSTATE_NONE;
  8101. },
  8102. enumerable: true,
  8103. configurable: true
  8104. });
  8105. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8106. get: function () {
  8107. return Engine._DELAYLOADSTATE_LOADED;
  8108. },
  8109. enumerable: true,
  8110. configurable: true
  8111. });
  8112. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8113. get: function () {
  8114. return Engine._DELAYLOADSTATE_LOADING;
  8115. },
  8116. enumerable: true,
  8117. configurable: true
  8118. });
  8119. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8120. get: function () {
  8121. return Engine._DELAYLOADSTATE_NOTLOADED;
  8122. },
  8123. enumerable: true,
  8124. configurable: true
  8125. });
  8126. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8127. get: function () {
  8128. return Engine._TEXTUREFORMAT_ALPHA;
  8129. },
  8130. enumerable: true,
  8131. configurable: true
  8132. });
  8133. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8134. get: function () {
  8135. return Engine._TEXTUREFORMAT_LUMINANCE;
  8136. },
  8137. enumerable: true,
  8138. configurable: true
  8139. });
  8140. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8141. get: function () {
  8142. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8143. },
  8144. enumerable: true,
  8145. configurable: true
  8146. });
  8147. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8148. get: function () {
  8149. return Engine._TEXTUREFORMAT_RGB;
  8150. },
  8151. enumerable: true,
  8152. configurable: true
  8153. });
  8154. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8155. get: function () {
  8156. return Engine._TEXTUREFORMAT_RGBA;
  8157. },
  8158. enumerable: true,
  8159. configurable: true
  8160. });
  8161. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8162. get: function () {
  8163. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8164. },
  8165. enumerable: true,
  8166. configurable: true
  8167. });
  8168. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8169. get: function () {
  8170. return Engine._TEXTURETYPE_FLOAT;
  8171. },
  8172. enumerable: true,
  8173. configurable: true
  8174. });
  8175. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8176. get: function () {
  8177. return Engine._TEXTURETYPE_HALF_FLOAT;
  8178. },
  8179. enumerable: true,
  8180. configurable: true
  8181. });
  8182. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8183. get: function () {
  8184. return Engine._SCALEMODE_FLOOR;
  8185. },
  8186. enumerable: true,
  8187. configurable: true
  8188. });
  8189. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8190. get: function () {
  8191. return Engine._SCALEMODE_NEAREST;
  8192. },
  8193. enumerable: true,
  8194. configurable: true
  8195. });
  8196. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8197. get: function () {
  8198. return Engine._SCALEMODE_CEILING;
  8199. },
  8200. enumerable: true,
  8201. configurable: true
  8202. });
  8203. Object.defineProperty(Engine, "Version", {
  8204. get: function () {
  8205. return "3.1-alpha";
  8206. },
  8207. enumerable: true,
  8208. configurable: true
  8209. });
  8210. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8211. get: function () {
  8212. return this._vrExclusivePointerMode;
  8213. },
  8214. enumerable: true,
  8215. configurable: true
  8216. });
  8217. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8218. get: function () {
  8219. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8220. },
  8221. enumerable: true,
  8222. configurable: true
  8223. });
  8224. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8225. get: function () {
  8226. return this._webGLVersion < 2 || this.forcePOTTextures;
  8227. },
  8228. enumerable: true,
  8229. configurable: true
  8230. });
  8231. Object.defineProperty(Engine.prototype, "badOS", {
  8232. get: function () {
  8233. return this._badOS;
  8234. },
  8235. enumerable: true,
  8236. configurable: true
  8237. });
  8238. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8239. get: function () {
  8240. return this._badDesktopOS;
  8241. },
  8242. enumerable: true,
  8243. configurable: true
  8244. });
  8245. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8246. get: function () {
  8247. return this._performanceMonitor;
  8248. },
  8249. enumerable: true,
  8250. configurable: true
  8251. });
  8252. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8253. get: function () {
  8254. return this._texturesSupported;
  8255. },
  8256. enumerable: true,
  8257. configurable: true
  8258. });
  8259. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8260. get: function () {
  8261. return this._textureFormatInUse;
  8262. },
  8263. enumerable: true,
  8264. configurable: true
  8265. });
  8266. Object.defineProperty(Engine.prototype, "currentViewport", {
  8267. get: function () {
  8268. return this._cachedViewport;
  8269. },
  8270. enumerable: true,
  8271. configurable: true
  8272. });
  8273. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8274. // Empty texture
  8275. get: function () {
  8276. if (!this._emptyTexture) {
  8277. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8278. }
  8279. return this._emptyTexture;
  8280. },
  8281. enumerable: true,
  8282. configurable: true
  8283. });
  8284. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8285. get: function () {
  8286. if (!this._emptyCubeTexture) {
  8287. var faceData = new Uint8Array(4);
  8288. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8289. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8290. }
  8291. return this._emptyCubeTexture;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Engine.prototype._rebuildInternalTextures = function () {
  8297. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8298. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8299. var internalTexture = currentState_1[_i];
  8300. internalTexture._rebuild();
  8301. }
  8302. };
  8303. Engine.prototype._rebuildEffects = function () {
  8304. for (var key in this._compiledEffects) {
  8305. var effect = this._compiledEffects[key];
  8306. effect._prepareEffect();
  8307. }
  8308. BABYLON.Effect.ResetCache();
  8309. };
  8310. Engine.prototype._rebuildBuffers = function () {
  8311. // Index / Vertex
  8312. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8313. var scene = _a[_i];
  8314. scene.resetCachedMaterial();
  8315. scene._rebuildGeometries();
  8316. scene._rebuildTextures();
  8317. }
  8318. // Uniforms
  8319. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8320. var uniformBuffer = _c[_b];
  8321. uniformBuffer._rebuild();
  8322. }
  8323. };
  8324. Engine.prototype._initGLContext = function () {
  8325. // Caps
  8326. this._caps = new EngineCapabilities();
  8327. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8328. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8329. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8330. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8331. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8332. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8333. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8334. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8335. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8336. // Infos
  8337. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8338. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8339. if (rendererInfo != null) {
  8340. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8341. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8342. }
  8343. if (!this._glVendor) {
  8344. this._glVendor = "Unknown vendor";
  8345. }
  8346. if (!this._glRenderer) {
  8347. this._glRenderer = "Unknown renderer";
  8348. }
  8349. // Constants
  8350. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8351. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8352. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8353. this._gl.DEPTH24_STENCIL8 = 35056;
  8354. // Extensions
  8355. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8356. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8357. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8358. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8359. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8360. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8361. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8362. 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');
  8363. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8364. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8365. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8366. this._caps.highPrecisionShaderSupported = true;
  8367. // Checks if some of the format renders first to allow the use of webgl inspector.
  8368. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8369. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8370. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8371. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8372. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8373. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8374. if (this._webGLVersion > 1) {
  8375. this._gl.HALF_FLOAT_OES = 0x140B;
  8376. }
  8377. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8378. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8379. // Draw buffers
  8380. if (this._webGLVersion > 1) {
  8381. this._caps.drawBuffersExtension = true;
  8382. }
  8383. else {
  8384. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8385. if (drawBuffersExtension !== null) {
  8386. this._caps.drawBuffersExtension = true;
  8387. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8388. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8389. for (var i = 0; i < 16; i++) {
  8390. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8391. }
  8392. }
  8393. else {
  8394. this._caps.drawBuffersExtension = false;
  8395. }
  8396. }
  8397. // Depth Texture
  8398. if (this._webGLVersion > 1) {
  8399. this._caps.depthTextureExtension = true;
  8400. }
  8401. else {
  8402. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8403. if (depthTextureExtension != null) {
  8404. this._caps.depthTextureExtension = true;
  8405. }
  8406. }
  8407. // Vertex array object
  8408. if (this._webGLVersion > 1) {
  8409. this._caps.vertexArrayObject = true;
  8410. }
  8411. else {
  8412. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8413. if (vertexArrayObjectExtension != null) {
  8414. this._caps.vertexArrayObject = true;
  8415. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8416. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8417. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8418. }
  8419. else {
  8420. this._caps.vertexArrayObject = false;
  8421. }
  8422. }
  8423. // Instances count
  8424. if (this._webGLVersion > 1) {
  8425. this._caps.instancedArrays = true;
  8426. }
  8427. else {
  8428. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8429. if (instanceExtension != null) {
  8430. this._caps.instancedArrays = true;
  8431. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8432. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8433. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8434. }
  8435. else {
  8436. this._caps.instancedArrays = false;
  8437. }
  8438. }
  8439. // Intelligently add supported compressed formats in order to check for.
  8440. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8441. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8442. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8443. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8444. if (this._caps.astc)
  8445. this.texturesSupported.push('-astc.ktx');
  8446. if (this._caps.s3tc)
  8447. this.texturesSupported.push('-dxt.ktx');
  8448. if (this._caps.pvrtc)
  8449. this.texturesSupported.push('-pvrtc.ktx');
  8450. if (this._caps.etc2)
  8451. this.texturesSupported.push('-etc2.ktx');
  8452. if (this._caps.etc1)
  8453. this.texturesSupported.push('-etc1.ktx');
  8454. if (this._gl.getShaderPrecisionFormat) {
  8455. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8456. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8457. }
  8458. // Depth buffer
  8459. this.setDepthBuffer(true);
  8460. this.setDepthFunctionToLessOrEqual();
  8461. this.setDepthWrite(true);
  8462. };
  8463. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8464. get: function () {
  8465. return this._webGLVersion;
  8466. },
  8467. enumerable: true,
  8468. configurable: true
  8469. });
  8470. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8471. /**
  8472. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8473. */
  8474. get: function () {
  8475. return this._isStencilEnable;
  8476. },
  8477. enumerable: true,
  8478. configurable: true
  8479. });
  8480. Engine.prototype._prepareWorkingCanvas = function () {
  8481. if (this._workingCanvas) {
  8482. return;
  8483. }
  8484. this._workingCanvas = document.createElement("canvas");
  8485. this._workingContext = this._workingCanvas.getContext("2d");
  8486. };
  8487. Engine.prototype.resetTextureCache = function () {
  8488. for (var key in this._activeTexturesCache) {
  8489. this._activeTexturesCache[key] = null;
  8490. }
  8491. };
  8492. Engine.prototype.isDeterministicLockStep = function () {
  8493. return this._deterministicLockstep;
  8494. };
  8495. Engine.prototype.getLockstepMaxSteps = function () {
  8496. return this._lockstepMaxSteps;
  8497. };
  8498. Engine.prototype.getGlInfo = function () {
  8499. return {
  8500. vendor: this._glVendor,
  8501. renderer: this._glRenderer,
  8502. version: this._glVersion
  8503. };
  8504. };
  8505. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8506. if (useScreen === void 0) { useScreen = false; }
  8507. var viewport = camera.viewport;
  8508. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8509. };
  8510. Engine.prototype.getRenderWidth = function (useScreen) {
  8511. if (useScreen === void 0) { useScreen = false; }
  8512. if (!useScreen && this._currentRenderTarget) {
  8513. return this._currentRenderTarget.width;
  8514. }
  8515. return this._gl.drawingBufferWidth;
  8516. };
  8517. Engine.prototype.getRenderHeight = function (useScreen) {
  8518. if (useScreen === void 0) { useScreen = false; }
  8519. if (!useScreen && this._currentRenderTarget) {
  8520. return this._currentRenderTarget.height;
  8521. }
  8522. return this._gl.drawingBufferHeight;
  8523. };
  8524. Engine.prototype.getRenderingCanvas = function () {
  8525. return this._renderingCanvas;
  8526. };
  8527. Engine.prototype.getRenderingCanvasClientRect = function () {
  8528. return this._renderingCanvas.getBoundingClientRect();
  8529. };
  8530. Engine.prototype.setHardwareScalingLevel = function (level) {
  8531. this._hardwareScalingLevel = level;
  8532. this.resize();
  8533. };
  8534. Engine.prototype.getHardwareScalingLevel = function () {
  8535. return this._hardwareScalingLevel;
  8536. };
  8537. Engine.prototype.getLoadedTexturesCache = function () {
  8538. return this._internalTexturesCache;
  8539. };
  8540. Engine.prototype.getCaps = function () {
  8541. return this._caps;
  8542. };
  8543. Object.defineProperty(Engine.prototype, "drawCalls", {
  8544. /** The number of draw calls submitted last frame */
  8545. get: function () {
  8546. return this._drawCalls.current;
  8547. },
  8548. enumerable: true,
  8549. configurable: true
  8550. });
  8551. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8552. get: function () {
  8553. return this._drawCalls;
  8554. },
  8555. enumerable: true,
  8556. configurable: true
  8557. });
  8558. Engine.prototype.getDepthFunction = function () {
  8559. return this._depthCullingState.depthFunc;
  8560. };
  8561. Engine.prototype.setDepthFunction = function (depthFunc) {
  8562. this._depthCullingState.depthFunc = depthFunc;
  8563. };
  8564. Engine.prototype.setDepthFunctionToGreater = function () {
  8565. this._depthCullingState.depthFunc = this._gl.GREATER;
  8566. };
  8567. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8568. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8569. };
  8570. Engine.prototype.setDepthFunctionToLess = function () {
  8571. this._depthCullingState.depthFunc = this._gl.LESS;
  8572. };
  8573. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8574. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8575. };
  8576. Engine.prototype.getStencilBuffer = function () {
  8577. return this._stencilState.stencilTest;
  8578. };
  8579. Engine.prototype.setStencilBuffer = function (enable) {
  8580. this._stencilState.stencilTest = enable;
  8581. };
  8582. Engine.prototype.getStencilMask = function () {
  8583. return this._stencilState.stencilMask;
  8584. };
  8585. Engine.prototype.setStencilMask = function (mask) {
  8586. this._stencilState.stencilMask = mask;
  8587. };
  8588. Engine.prototype.getStencilFunction = function () {
  8589. return this._stencilState.stencilFunc;
  8590. };
  8591. Engine.prototype.getStencilFunctionReference = function () {
  8592. return this._stencilState.stencilFuncRef;
  8593. };
  8594. Engine.prototype.getStencilFunctionMask = function () {
  8595. return this._stencilState.stencilFuncMask;
  8596. };
  8597. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8598. this._stencilState.stencilFunc = stencilFunc;
  8599. };
  8600. Engine.prototype.setStencilFunctionReference = function (reference) {
  8601. this._stencilState.stencilFuncRef = reference;
  8602. };
  8603. Engine.prototype.setStencilFunctionMask = function (mask) {
  8604. this._stencilState.stencilFuncMask = mask;
  8605. };
  8606. Engine.prototype.getStencilOperationFail = function () {
  8607. return this._stencilState.stencilOpStencilFail;
  8608. };
  8609. Engine.prototype.getStencilOperationDepthFail = function () {
  8610. return this._stencilState.stencilOpDepthFail;
  8611. };
  8612. Engine.prototype.getStencilOperationPass = function () {
  8613. return this._stencilState.stencilOpStencilDepthPass;
  8614. };
  8615. Engine.prototype.setStencilOperationFail = function (operation) {
  8616. this._stencilState.stencilOpStencilFail = operation;
  8617. };
  8618. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8619. this._stencilState.stencilOpDepthFail = operation;
  8620. };
  8621. Engine.prototype.setStencilOperationPass = function (operation) {
  8622. this._stencilState.stencilOpStencilDepthPass = operation;
  8623. };
  8624. Engine.prototype.setDitheringState = function (value) {
  8625. if (value) {
  8626. this._gl.enable(this._gl.DITHER);
  8627. }
  8628. else {
  8629. this._gl.disable(this._gl.DITHER);
  8630. }
  8631. };
  8632. /**
  8633. * stop executing a render loop function and remove it from the execution array
  8634. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8635. */
  8636. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8637. if (!renderFunction) {
  8638. this._activeRenderLoops = [];
  8639. return;
  8640. }
  8641. var index = this._activeRenderLoops.indexOf(renderFunction);
  8642. if (index >= 0) {
  8643. this._activeRenderLoops.splice(index, 1);
  8644. }
  8645. };
  8646. Engine.prototype._renderLoop = function () {
  8647. if (!this._contextWasLost) {
  8648. var shouldRender = true;
  8649. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8650. shouldRender = false;
  8651. }
  8652. if (shouldRender) {
  8653. // Start new frame
  8654. this.beginFrame();
  8655. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8656. var renderFunction = this._activeRenderLoops[index];
  8657. renderFunction();
  8658. }
  8659. // Present
  8660. this.endFrame();
  8661. }
  8662. }
  8663. if (this._activeRenderLoops.length > 0) {
  8664. // Register new frame
  8665. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8666. }
  8667. else {
  8668. this._renderingQueueLaunched = false;
  8669. }
  8670. };
  8671. /**
  8672. * Register and execute a render loop. The engine can have more than one render function.
  8673. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8674. * @example
  8675. * engine.runRenderLoop(function () {
  8676. * scene.render()
  8677. * })
  8678. */
  8679. Engine.prototype.runRenderLoop = function (renderFunction) {
  8680. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8681. return;
  8682. }
  8683. this._activeRenderLoops.push(renderFunction);
  8684. if (!this._renderingQueueLaunched) {
  8685. this._renderingQueueLaunched = true;
  8686. this._bindedRenderFunction = this._renderLoop.bind(this);
  8687. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8688. }
  8689. };
  8690. /**
  8691. * Toggle full screen mode.
  8692. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8693. * @param {any} options - an options object to be sent to the requestFullscreen function
  8694. */
  8695. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8696. if (this.isFullscreen) {
  8697. BABYLON.Tools.ExitFullscreen();
  8698. }
  8699. else {
  8700. this._pointerLockRequested = requestPointerLock;
  8701. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8702. }
  8703. };
  8704. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8705. if (stencil === void 0) { stencil = false; }
  8706. this.applyStates();
  8707. var mode = 0;
  8708. if (backBuffer && color) {
  8709. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8710. mode |= this._gl.COLOR_BUFFER_BIT;
  8711. }
  8712. if (depth) {
  8713. this._gl.clearDepth(1.0);
  8714. mode |= this._gl.DEPTH_BUFFER_BIT;
  8715. }
  8716. if (stencil) {
  8717. this._gl.clearStencil(0);
  8718. mode |= this._gl.STENCIL_BUFFER_BIT;
  8719. }
  8720. this._gl.clear(mode);
  8721. };
  8722. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8723. var gl = this._gl;
  8724. // Save state
  8725. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8726. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8727. // Change state
  8728. gl.enable(gl.SCISSOR_TEST);
  8729. gl.scissor(x, y, width, height);
  8730. // Clear
  8731. this.clear(clearColor, true, true, true);
  8732. // Restore state
  8733. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8734. if (curScissor === true) {
  8735. gl.enable(gl.SCISSOR_TEST);
  8736. }
  8737. else {
  8738. gl.disable(gl.SCISSOR_TEST);
  8739. }
  8740. };
  8741. /**
  8742. * Set the WebGL's viewport
  8743. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8744. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8745. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8746. */
  8747. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8748. var width = requiredWidth || this.getRenderWidth();
  8749. var height = requiredHeight || this.getRenderHeight();
  8750. var x = viewport.x || 0;
  8751. var y = viewport.y || 0;
  8752. this._cachedViewport = viewport;
  8753. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8754. };
  8755. /**
  8756. * Directly set the WebGL Viewport
  8757. * The x, y, width & height are directly passed to the WebGL call
  8758. * @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.
  8759. */
  8760. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8761. var currentViewport = this._cachedViewport;
  8762. this._cachedViewport = null;
  8763. this._gl.viewport(x, y, width, height);
  8764. return currentViewport;
  8765. };
  8766. Engine.prototype.beginFrame = function () {
  8767. this._measureFps();
  8768. };
  8769. Engine.prototype.endFrame = function () {
  8770. //force a flush in case we are using a bad OS.
  8771. if (this._badOS) {
  8772. this.flushFramebuffer();
  8773. }
  8774. //submit frame to the vr device, if enabled
  8775. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8776. this._vrDisplayEnabled.submitFrame();
  8777. }
  8778. };
  8779. /**
  8780. * resize the view according to the canvas' size.
  8781. * @example
  8782. * window.addEventListener("resize", function () {
  8783. * engine.resize();
  8784. * });
  8785. */
  8786. Engine.prototype.resize = function () {
  8787. // We're not resizing the size of the canvas while in VR mode & presenting
  8788. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8789. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8790. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8791. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8792. }
  8793. };
  8794. /**
  8795. * force a specific size of the canvas
  8796. * @param {number} width - the new canvas' width
  8797. * @param {number} height - the new canvas' height
  8798. */
  8799. Engine.prototype.setSize = function (width, height) {
  8800. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8801. return;
  8802. }
  8803. this._renderingCanvas.width = width;
  8804. this._renderingCanvas.height = height;
  8805. for (var index = 0; index < this.scenes.length; index++) {
  8806. var scene = this.scenes[index];
  8807. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8808. var cam = scene.cameras[camIndex];
  8809. cam._currentRenderId = 0;
  8810. }
  8811. }
  8812. if (this.onResizeObservable.hasObservers) {
  8813. this.onResizeObservable.notifyObservers(this);
  8814. }
  8815. };
  8816. //WebVR functions
  8817. Engine.prototype.isVRDevicePresent = function (callback) {
  8818. this.getVRDevice(null, function (device) {
  8819. callback(device !== null);
  8820. });
  8821. };
  8822. Engine.prototype.getVRDevice = function (name, callback) {
  8823. if (!this.vrDisplaysPromise) {
  8824. callback(null);
  8825. return;
  8826. }
  8827. this.vrDisplaysPromise.then(function (devices) {
  8828. if (devices.length > 0) {
  8829. if (name) {
  8830. var found = devices.some(function (device) {
  8831. if (device.displayName === name) {
  8832. callback(device);
  8833. return true;
  8834. }
  8835. else {
  8836. return false;
  8837. }
  8838. });
  8839. if (!found) {
  8840. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8841. callback(devices[0]);
  8842. }
  8843. }
  8844. else {
  8845. //choose the first one
  8846. callback(devices[0]);
  8847. }
  8848. }
  8849. else {
  8850. BABYLON.Tools.Error("No WebVR devices found!");
  8851. callback(null);
  8852. }
  8853. });
  8854. };
  8855. Engine.prototype.initWebVR = function () {
  8856. if (!this.vrDisplaysPromise) {
  8857. this._getVRDisplays();
  8858. }
  8859. };
  8860. Engine.prototype.enableVR = function (vrDevice) {
  8861. this._vrDisplayEnabled = vrDevice;
  8862. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8863. };
  8864. Engine.prototype.disableVR = function () {
  8865. if (this._vrDisplayEnabled) {
  8866. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8867. }
  8868. };
  8869. Engine.prototype._getVRDisplays = function () {
  8870. var _this = this;
  8871. var getWebVRDevices = function (devices) {
  8872. _this._vrDisplays = devices.filter(function (device) {
  8873. return device instanceof VRDisplay;
  8874. });
  8875. return _this._vrDisplays;
  8876. };
  8877. if (navigator.getVRDisplays) {
  8878. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8879. }
  8880. };
  8881. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8882. if (this._currentRenderTarget) {
  8883. this.unBindFramebuffer(this._currentRenderTarget);
  8884. }
  8885. this._currentRenderTarget = texture;
  8886. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8887. var gl = this._gl;
  8888. if (texture.isCube) {
  8889. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8890. }
  8891. if (this._cachedViewport && !forceFullscreenViewport) {
  8892. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8893. }
  8894. else {
  8895. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8896. }
  8897. this.wipeCaches();
  8898. };
  8899. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8900. if (this._currentFramebuffer !== framebuffer) {
  8901. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8902. this._currentFramebuffer = framebuffer;
  8903. }
  8904. };
  8905. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8906. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8907. this._currentRenderTarget = null;
  8908. // If MSAA, we need to bitblt back to main texture
  8909. var gl = this._gl;
  8910. if (texture._MSAAFramebuffer) {
  8911. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8912. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8913. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8914. }
  8915. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8916. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8917. gl.generateMipmap(gl.TEXTURE_2D);
  8918. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8919. }
  8920. if (onBeforeUnbind) {
  8921. if (texture._MSAAFramebuffer) {
  8922. // Bind the correct framebuffer
  8923. this.bindUnboundFramebuffer(texture._framebuffer);
  8924. }
  8925. onBeforeUnbind();
  8926. }
  8927. this.bindUnboundFramebuffer(null);
  8928. };
  8929. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8930. if (texture.generateMipMaps) {
  8931. var gl = this._gl;
  8932. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8933. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8934. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8935. }
  8936. };
  8937. Engine.prototype.flushFramebuffer = function () {
  8938. this._gl.flush();
  8939. };
  8940. Engine.prototype.restoreDefaultFramebuffer = function () {
  8941. if (this._currentRenderTarget) {
  8942. this.unBindFramebuffer(this._currentRenderTarget);
  8943. }
  8944. else {
  8945. this.bindUnboundFramebuffer(null);
  8946. }
  8947. if (this._cachedViewport) {
  8948. this.setViewport(this._cachedViewport);
  8949. }
  8950. this.wipeCaches();
  8951. };
  8952. // UBOs
  8953. Engine.prototype.createUniformBuffer = function (elements) {
  8954. var ubo = this._gl.createBuffer();
  8955. this.bindUniformBuffer(ubo);
  8956. if (elements instanceof Float32Array) {
  8957. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8958. }
  8959. else {
  8960. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8961. }
  8962. this.bindUniformBuffer(null);
  8963. ubo.references = 1;
  8964. return ubo;
  8965. };
  8966. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8967. var ubo = this._gl.createBuffer();
  8968. this.bindUniformBuffer(ubo);
  8969. if (elements instanceof Float32Array) {
  8970. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8971. }
  8972. else {
  8973. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8974. }
  8975. this.bindUniformBuffer(null);
  8976. ubo.references = 1;
  8977. return ubo;
  8978. };
  8979. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8980. this.bindUniformBuffer(uniformBuffer);
  8981. if (offset === undefined) {
  8982. offset = 0;
  8983. }
  8984. if (count === undefined) {
  8985. if (elements instanceof Float32Array) {
  8986. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8987. }
  8988. else {
  8989. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8990. }
  8991. }
  8992. else {
  8993. if (elements instanceof Float32Array) {
  8994. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8995. }
  8996. else {
  8997. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8998. }
  8999. }
  9000. this.bindUniformBuffer(null);
  9001. };
  9002. // VBOs
  9003. Engine.prototype._resetVertexBufferBinding = function () {
  9004. this.bindArrayBuffer(null);
  9005. this._cachedVertexBuffers = null;
  9006. };
  9007. Engine.prototype.createVertexBuffer = function (vertices) {
  9008. var vbo = this._gl.createBuffer();
  9009. this.bindArrayBuffer(vbo);
  9010. if (vertices instanceof Float32Array) {
  9011. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9012. }
  9013. else {
  9014. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9015. }
  9016. this._resetVertexBufferBinding();
  9017. vbo.references = 1;
  9018. return vbo;
  9019. };
  9020. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9021. var vbo = this._gl.createBuffer();
  9022. this.bindArrayBuffer(vbo);
  9023. if (vertices instanceof Float32Array) {
  9024. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9025. }
  9026. else {
  9027. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9028. }
  9029. this._resetVertexBufferBinding();
  9030. vbo.references = 1;
  9031. return vbo;
  9032. };
  9033. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9034. this.bindArrayBuffer(vertexBuffer);
  9035. if (offset === undefined) {
  9036. offset = 0;
  9037. }
  9038. if (count === undefined) {
  9039. if (vertices instanceof Float32Array) {
  9040. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9041. }
  9042. else {
  9043. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9044. }
  9045. }
  9046. else {
  9047. if (vertices instanceof Float32Array) {
  9048. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9049. }
  9050. else {
  9051. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9052. }
  9053. }
  9054. this._resetVertexBufferBinding();
  9055. };
  9056. Engine.prototype._resetIndexBufferBinding = function () {
  9057. this.bindIndexBuffer(null);
  9058. this._cachedIndexBuffer = null;
  9059. };
  9060. Engine.prototype.createIndexBuffer = function (indices) {
  9061. var vbo = this._gl.createBuffer();
  9062. this.bindIndexBuffer(vbo);
  9063. // Check for 32 bits indices
  9064. var arrayBuffer;
  9065. var need32Bits = false;
  9066. if (indices instanceof Uint16Array) {
  9067. arrayBuffer = indices;
  9068. }
  9069. else {
  9070. //check 32 bit support
  9071. if (this._caps.uintIndices) {
  9072. if (indices instanceof Uint32Array) {
  9073. arrayBuffer = indices;
  9074. need32Bits = true;
  9075. }
  9076. else {
  9077. //number[] or Int32Array, check if 32 bit is necessary
  9078. for (var index = 0; index < indices.length; index++) {
  9079. if (indices[index] > 65535) {
  9080. need32Bits = true;
  9081. break;
  9082. }
  9083. }
  9084. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9085. }
  9086. }
  9087. else {
  9088. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9089. arrayBuffer = new Uint16Array(indices);
  9090. }
  9091. }
  9092. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9093. this._resetIndexBufferBinding();
  9094. vbo.references = 1;
  9095. vbo.is32Bits = need32Bits;
  9096. return vbo;
  9097. };
  9098. Engine.prototype.bindArrayBuffer = function (buffer) {
  9099. if (!this._vaoRecordInProgress) {
  9100. this._unbindVertexArrayObject();
  9101. }
  9102. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9103. };
  9104. Engine.prototype.bindUniformBuffer = function (buffer) {
  9105. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9106. };
  9107. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9108. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9109. };
  9110. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9111. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9112. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9113. };
  9114. ;
  9115. Engine.prototype.bindIndexBuffer = function (buffer) {
  9116. if (!this._vaoRecordInProgress) {
  9117. this._unbindVertexArrayObject();
  9118. }
  9119. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9120. };
  9121. Engine.prototype.bindBuffer = function (buffer, target) {
  9122. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9123. this._gl.bindBuffer(target, buffer);
  9124. this._currentBoundBuffer[target] = buffer;
  9125. }
  9126. };
  9127. Engine.prototype.updateArrayBuffer = function (data) {
  9128. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9129. };
  9130. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9131. var pointer = this._currentBufferPointers[indx];
  9132. var changed = false;
  9133. if (!pointer.active) {
  9134. changed = true;
  9135. pointer.active = true;
  9136. pointer.index = indx;
  9137. pointer.size = size;
  9138. pointer.type = type;
  9139. pointer.normalized = normalized;
  9140. pointer.stride = stride;
  9141. pointer.offset = offset;
  9142. pointer.buffer = buffer;
  9143. }
  9144. else {
  9145. if (pointer.buffer !== buffer) {
  9146. pointer.buffer = buffer;
  9147. changed = true;
  9148. }
  9149. if (pointer.size !== size) {
  9150. pointer.size = size;
  9151. changed = true;
  9152. }
  9153. if (pointer.type !== type) {
  9154. pointer.type = type;
  9155. changed = true;
  9156. }
  9157. if (pointer.normalized !== normalized) {
  9158. pointer.normalized = normalized;
  9159. changed = true;
  9160. }
  9161. if (pointer.stride !== stride) {
  9162. pointer.stride = stride;
  9163. changed = true;
  9164. }
  9165. if (pointer.offset !== offset) {
  9166. pointer.offset = offset;
  9167. changed = true;
  9168. }
  9169. }
  9170. if (changed || this._vaoRecordInProgress) {
  9171. this.bindArrayBuffer(buffer);
  9172. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9173. }
  9174. };
  9175. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9176. if (indexBuffer == null) {
  9177. return;
  9178. }
  9179. if (this._cachedIndexBuffer !== indexBuffer) {
  9180. this._cachedIndexBuffer = indexBuffer;
  9181. this.bindIndexBuffer(indexBuffer);
  9182. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9183. }
  9184. };
  9185. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9186. var attributes = effect.getAttributesNames();
  9187. if (!this._vaoRecordInProgress) {
  9188. this._unbindVertexArrayObject();
  9189. }
  9190. this.unbindAllAttributes();
  9191. for (var index = 0; index < attributes.length; index++) {
  9192. var order = effect.getAttributeLocation(index);
  9193. if (order >= 0) {
  9194. var vertexBuffer = vertexBuffers[attributes[index]];
  9195. if (!vertexBuffer) {
  9196. continue;
  9197. }
  9198. this._gl.enableVertexAttribArray(order);
  9199. if (!this._vaoRecordInProgress) {
  9200. this._vertexAttribArraysEnabled[order] = true;
  9201. }
  9202. var buffer = vertexBuffer.getBuffer();
  9203. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9204. if (vertexBuffer.getIsInstanced()) {
  9205. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9206. if (!this._vaoRecordInProgress) {
  9207. this._currentInstanceLocations.push(order);
  9208. this._currentInstanceBuffers.push(buffer);
  9209. }
  9210. }
  9211. }
  9212. }
  9213. };
  9214. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9215. var vao = this._gl.createVertexArray();
  9216. this._vaoRecordInProgress = true;
  9217. this._gl.bindVertexArray(vao);
  9218. this._mustWipeVertexAttributes = true;
  9219. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9220. this.bindIndexBuffer(indexBuffer);
  9221. this._vaoRecordInProgress = false;
  9222. this._gl.bindVertexArray(null);
  9223. return vao;
  9224. };
  9225. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9226. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9227. this._cachedVertexArrayObject = vertexArrayObject;
  9228. this._gl.bindVertexArray(vertexArrayObject);
  9229. this._cachedVertexBuffers = null;
  9230. this._cachedIndexBuffer = null;
  9231. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9232. this._mustWipeVertexAttributes = true;
  9233. }
  9234. };
  9235. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9236. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9237. this._cachedVertexBuffers = vertexBuffer;
  9238. this._cachedEffectForVertexBuffers = effect;
  9239. var attributesCount = effect.getAttributesCount();
  9240. this._unbindVertexArrayObject();
  9241. this.unbindAllAttributes();
  9242. var offset = 0;
  9243. for (var index = 0; index < attributesCount; index++) {
  9244. if (index < vertexDeclaration.length) {
  9245. var order = effect.getAttributeLocation(index);
  9246. if (order >= 0) {
  9247. this._gl.enableVertexAttribArray(order);
  9248. this._vertexAttribArraysEnabled[order] = true;
  9249. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9250. }
  9251. offset += vertexDeclaration[index] * 4;
  9252. }
  9253. }
  9254. }
  9255. this._bindIndexBufferWithCache(indexBuffer);
  9256. };
  9257. Engine.prototype._unbindVertexArrayObject = function () {
  9258. if (!this._cachedVertexArrayObject) {
  9259. return;
  9260. }
  9261. this._cachedVertexArrayObject = null;
  9262. this._gl.bindVertexArray(null);
  9263. };
  9264. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9265. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9266. this._cachedVertexBuffers = vertexBuffers;
  9267. this._cachedEffectForVertexBuffers = effect;
  9268. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9269. }
  9270. this._bindIndexBufferWithCache(indexBuffer);
  9271. };
  9272. Engine.prototype.unbindInstanceAttributes = function () {
  9273. var boundBuffer;
  9274. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9275. var instancesBuffer = this._currentInstanceBuffers[i];
  9276. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9277. boundBuffer = instancesBuffer;
  9278. this.bindArrayBuffer(instancesBuffer);
  9279. }
  9280. var offsetLocation = this._currentInstanceLocations[i];
  9281. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9282. }
  9283. this._currentInstanceBuffers.length = 0;
  9284. this._currentInstanceLocations.length = 0;
  9285. };
  9286. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9287. this._gl.deleteVertexArray(vao);
  9288. };
  9289. Engine.prototype._releaseBuffer = function (buffer) {
  9290. buffer.references--;
  9291. if (buffer.references === 0) {
  9292. this._gl.deleteBuffer(buffer);
  9293. return true;
  9294. }
  9295. return false;
  9296. };
  9297. Engine.prototype.createInstancesBuffer = function (capacity) {
  9298. var buffer = this._gl.createBuffer();
  9299. buffer.capacity = capacity;
  9300. this.bindArrayBuffer(buffer);
  9301. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9302. return buffer;
  9303. };
  9304. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9305. this._gl.deleteBuffer(buffer);
  9306. };
  9307. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9308. this.bindArrayBuffer(instancesBuffer);
  9309. if (data) {
  9310. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9311. }
  9312. if (offsetLocations[0].index !== undefined) {
  9313. var stride = 0;
  9314. for (var i = 0; i < offsetLocations.length; i++) {
  9315. var ai = offsetLocations[i];
  9316. stride += ai.attributeSize * 4;
  9317. }
  9318. for (var i = 0; i < offsetLocations.length; i++) {
  9319. var ai = offsetLocations[i];
  9320. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9321. this._gl.enableVertexAttribArray(ai.index);
  9322. this._vertexAttribArraysEnabled[ai.index] = true;
  9323. }
  9324. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9325. this._gl.vertexAttribDivisor(ai.index, 1);
  9326. this._currentInstanceLocations.push(ai.index);
  9327. this._currentInstanceBuffers.push(instancesBuffer);
  9328. }
  9329. }
  9330. else {
  9331. for (var index = 0; index < 4; index++) {
  9332. var offsetLocation = offsetLocations[index];
  9333. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9334. this._gl.enableVertexAttribArray(offsetLocation);
  9335. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9336. }
  9337. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9338. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9339. this._currentInstanceLocations.push(offsetLocation);
  9340. this._currentInstanceBuffers.push(instancesBuffer);
  9341. }
  9342. }
  9343. };
  9344. Engine.prototype.applyStates = function () {
  9345. this._depthCullingState.apply(this._gl);
  9346. this._stencilState.apply(this._gl);
  9347. this._alphaState.apply(this._gl);
  9348. };
  9349. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9350. // Apply states
  9351. this.applyStates();
  9352. this._drawCalls.addCount(1, false);
  9353. // Render
  9354. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9355. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9356. if (instancesCount) {
  9357. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9358. return;
  9359. }
  9360. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9361. };
  9362. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9363. // Apply states
  9364. this.applyStates();
  9365. this._drawCalls.addCount(1, false);
  9366. if (instancesCount) {
  9367. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9368. return;
  9369. }
  9370. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9371. };
  9372. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9373. // Apply states
  9374. this.applyStates();
  9375. this._drawCalls.addCount(1, false);
  9376. if (instancesCount) {
  9377. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9378. return;
  9379. }
  9380. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9381. };
  9382. // Shaders
  9383. Engine.prototype._releaseEffect = function (effect) {
  9384. if (this._compiledEffects[effect._key]) {
  9385. delete this._compiledEffects[effect._key];
  9386. if (effect.getProgram()) {
  9387. this._gl.deleteProgram(effect.getProgram());
  9388. }
  9389. }
  9390. };
  9391. /**
  9392. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9393. * @param samplers An array of string used to represent textures
  9394. */
  9395. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9396. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9397. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9398. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9399. if (this._compiledEffects[name]) {
  9400. var compiledEffect = this._compiledEffects[name];
  9401. if (onCompiled && compiledEffect.isReady()) {
  9402. onCompiled(compiledEffect);
  9403. }
  9404. return compiledEffect;
  9405. }
  9406. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9407. effect._key = name;
  9408. this._compiledEffects[name] = effect;
  9409. return effect;
  9410. };
  9411. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9412. if (uniformsNames === void 0) { uniformsNames = []; }
  9413. if (samplers === void 0) { samplers = []; }
  9414. if (defines === void 0) { defines = ""; }
  9415. return this.createEffect({
  9416. vertex: "particles",
  9417. fragmentElement: fragmentName
  9418. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9419. };
  9420. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9421. context = context || this._gl;
  9422. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9423. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9424. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9425. var shaderProgram = context.createProgram();
  9426. context.attachShader(shaderProgram, vertexShader);
  9427. context.attachShader(shaderProgram, fragmentShader);
  9428. context.linkProgram(shaderProgram);
  9429. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9430. if (!linked) {
  9431. context.validateProgram(shaderProgram);
  9432. var error = context.getProgramInfoLog(shaderProgram);
  9433. if (error) {
  9434. throw new Error(error);
  9435. }
  9436. }
  9437. context.deleteShader(vertexShader);
  9438. context.deleteShader(fragmentShader);
  9439. return shaderProgram;
  9440. };
  9441. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9442. var results = [];
  9443. for (var index = 0; index < uniformsNames.length; index++) {
  9444. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9445. }
  9446. return results;
  9447. };
  9448. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9449. var results = [];
  9450. for (var index = 0; index < attributesNames.length; index++) {
  9451. try {
  9452. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9453. }
  9454. catch (e) {
  9455. results.push(-1);
  9456. }
  9457. }
  9458. return results;
  9459. };
  9460. Engine.prototype.enableEffect = function (effect) {
  9461. // Use program
  9462. this.setProgram(effect.getProgram());
  9463. this._currentEffect = effect;
  9464. if (effect.onBind) {
  9465. effect.onBind(effect);
  9466. }
  9467. effect.onBindObservable.notifyObservers(effect);
  9468. };
  9469. Engine.prototype.setIntArray = function (uniform, array) {
  9470. if (!uniform)
  9471. return;
  9472. this._gl.uniform1iv(uniform, array);
  9473. };
  9474. Engine.prototype.setIntArray2 = function (uniform, array) {
  9475. if (!uniform || array.length % 2 !== 0)
  9476. return;
  9477. this._gl.uniform2iv(uniform, array);
  9478. };
  9479. Engine.prototype.setIntArray3 = function (uniform, array) {
  9480. if (!uniform || array.length % 3 !== 0)
  9481. return;
  9482. this._gl.uniform3iv(uniform, array);
  9483. };
  9484. Engine.prototype.setIntArray4 = function (uniform, array) {
  9485. if (!uniform || array.length % 4 !== 0)
  9486. return;
  9487. this._gl.uniform4iv(uniform, array);
  9488. };
  9489. Engine.prototype.setFloatArray = function (uniform, array) {
  9490. if (!uniform)
  9491. return;
  9492. this._gl.uniform1fv(uniform, array);
  9493. };
  9494. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9495. if (!uniform || array.length % 2 !== 0)
  9496. return;
  9497. this._gl.uniform2fv(uniform, array);
  9498. };
  9499. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9500. if (!uniform || array.length % 3 !== 0)
  9501. return;
  9502. this._gl.uniform3fv(uniform, array);
  9503. };
  9504. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9505. if (!uniform || array.length % 4 !== 0)
  9506. return;
  9507. this._gl.uniform4fv(uniform, array);
  9508. };
  9509. Engine.prototype.setArray = function (uniform, array) {
  9510. if (!uniform)
  9511. return;
  9512. this._gl.uniform1fv(uniform, array);
  9513. };
  9514. Engine.prototype.setArray2 = function (uniform, array) {
  9515. if (!uniform || array.length % 2 !== 0)
  9516. return;
  9517. this._gl.uniform2fv(uniform, array);
  9518. };
  9519. Engine.prototype.setArray3 = function (uniform, array) {
  9520. if (!uniform || array.length % 3 !== 0)
  9521. return;
  9522. this._gl.uniform3fv(uniform, array);
  9523. };
  9524. Engine.prototype.setArray4 = function (uniform, array) {
  9525. if (!uniform || array.length % 4 !== 0)
  9526. return;
  9527. this._gl.uniform4fv(uniform, array);
  9528. };
  9529. Engine.prototype.setMatrices = function (uniform, matrices) {
  9530. if (!uniform)
  9531. return;
  9532. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9533. };
  9534. Engine.prototype.setMatrix = function (uniform, matrix) {
  9535. if (!uniform)
  9536. return;
  9537. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9538. };
  9539. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9540. if (!uniform)
  9541. return;
  9542. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9543. };
  9544. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9545. if (!uniform)
  9546. return;
  9547. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9548. };
  9549. Engine.prototype.setFloat = function (uniform, value) {
  9550. if (!uniform)
  9551. return;
  9552. this._gl.uniform1f(uniform, value);
  9553. };
  9554. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9555. if (!uniform)
  9556. return;
  9557. this._gl.uniform2f(uniform, x, y);
  9558. };
  9559. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9560. if (!uniform)
  9561. return;
  9562. this._gl.uniform3f(uniform, x, y, z);
  9563. };
  9564. Engine.prototype.setBool = function (uniform, bool) {
  9565. if (!uniform)
  9566. return;
  9567. this._gl.uniform1i(uniform, bool);
  9568. };
  9569. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9570. if (!uniform)
  9571. return;
  9572. this._gl.uniform4f(uniform, x, y, z, w);
  9573. };
  9574. Engine.prototype.setColor3 = function (uniform, color3) {
  9575. if (!uniform)
  9576. return;
  9577. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9578. };
  9579. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9580. if (!uniform)
  9581. return;
  9582. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9583. };
  9584. // States
  9585. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9586. if (zOffset === void 0) { zOffset = 0; }
  9587. if (reverseSide === void 0) { reverseSide = false; }
  9588. // Culling
  9589. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9590. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9591. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9592. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9593. if (culling) {
  9594. this._depthCullingState.cullFace = cullFace;
  9595. this._depthCullingState.cull = true;
  9596. }
  9597. else {
  9598. this._depthCullingState.cull = false;
  9599. }
  9600. }
  9601. // Z offset
  9602. this.setZOffset(zOffset);
  9603. };
  9604. Engine.prototype.setZOffset = function (value) {
  9605. this._depthCullingState.zOffset = value;
  9606. };
  9607. Engine.prototype.getZOffset = function () {
  9608. return this._depthCullingState.zOffset;
  9609. };
  9610. Engine.prototype.setDepthBuffer = function (enable) {
  9611. this._depthCullingState.depthTest = enable;
  9612. };
  9613. Engine.prototype.getDepthWrite = function () {
  9614. return this._depthCullingState.depthMask;
  9615. };
  9616. Engine.prototype.setDepthWrite = function (enable) {
  9617. this._depthCullingState.depthMask = enable;
  9618. };
  9619. Engine.prototype.setColorWrite = function (enable) {
  9620. this._gl.colorMask(enable, enable, enable, enable);
  9621. this._colorWrite = enable;
  9622. };
  9623. Engine.prototype.getColorWrite = function () {
  9624. return this._colorWrite;
  9625. };
  9626. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9627. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9628. };
  9629. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9630. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9631. if (this._alphaMode === mode) {
  9632. return;
  9633. }
  9634. switch (mode) {
  9635. case Engine.ALPHA_DISABLE:
  9636. this._alphaState.alphaBlend = false;
  9637. break;
  9638. case Engine.ALPHA_PREMULTIPLIED:
  9639. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9640. this._alphaState.alphaBlend = true;
  9641. break;
  9642. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9643. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9644. this._alphaState.alphaBlend = true;
  9645. break;
  9646. case Engine.ALPHA_COMBINE:
  9647. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9648. this._alphaState.alphaBlend = true;
  9649. break;
  9650. case Engine.ALPHA_ONEONE:
  9651. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9652. this._alphaState.alphaBlend = true;
  9653. break;
  9654. case Engine.ALPHA_ADD:
  9655. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9656. this._alphaState.alphaBlend = true;
  9657. break;
  9658. case Engine.ALPHA_SUBTRACT:
  9659. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9660. this._alphaState.alphaBlend = true;
  9661. break;
  9662. case Engine.ALPHA_MULTIPLY:
  9663. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9664. this._alphaState.alphaBlend = true;
  9665. break;
  9666. case Engine.ALPHA_MAXIMIZED:
  9667. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9668. this._alphaState.alphaBlend = true;
  9669. break;
  9670. case Engine.ALPHA_INTERPOLATE:
  9671. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9672. this._alphaState.alphaBlend = true;
  9673. break;
  9674. case Engine.ALPHA_SCREENMODE:
  9675. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9676. this._alphaState.alphaBlend = true;
  9677. break;
  9678. }
  9679. if (!noDepthWriteChange) {
  9680. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9681. }
  9682. this._alphaMode = mode;
  9683. };
  9684. Engine.prototype.getAlphaMode = function () {
  9685. return this._alphaMode;
  9686. };
  9687. Engine.prototype.setAlphaTesting = function (enable) {
  9688. this._alphaTest = enable;
  9689. };
  9690. Engine.prototype.getAlphaTesting = function () {
  9691. return !!this._alphaTest;
  9692. };
  9693. // Textures
  9694. Engine.prototype.wipeCaches = function (bruteForce) {
  9695. if (this.preventCacheWipeBetweenFrames) {
  9696. return;
  9697. }
  9698. this.resetTextureCache();
  9699. this._currentEffect = null;
  9700. // 6/8/2017: deltakosh: Should not be required anymore.
  9701. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9702. if (bruteForce) {
  9703. this._currentProgram = null;
  9704. this._stencilState.reset();
  9705. this._depthCullingState.reset();
  9706. this.setDepthFunctionToLessOrEqual();
  9707. this._alphaState.reset();
  9708. }
  9709. this._cachedVertexBuffers = null;
  9710. this._cachedIndexBuffer = null;
  9711. this._cachedEffectForVertexBuffers = null;
  9712. this._unbindVertexArrayObject();
  9713. this.bindIndexBuffer(null);
  9714. this.bindArrayBuffer(null);
  9715. };
  9716. /**
  9717. * Set the compressed texture format to use, based on the formats you have, and the formats
  9718. * supported by the hardware / browser.
  9719. *
  9720. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9721. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9722. * to API arguments needed to compressed textures. This puts the burden on the container
  9723. * generator to house the arcane code for determining these for current & future formats.
  9724. *
  9725. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9726. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9727. *
  9728. * Note: The result of this call is not taken into account when a texture is base64.
  9729. *
  9730. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9731. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9732. *
  9733. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9734. * @returns The extension selected.
  9735. */
  9736. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9737. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9738. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9739. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9740. return this._textureFormatInUse = this._texturesSupported[i];
  9741. }
  9742. }
  9743. }
  9744. // actively set format to nothing, to allow this to be called more than once
  9745. // and possibly fail the 2nd time
  9746. return this._textureFormatInUse = null;
  9747. };
  9748. Engine.prototype._createTexture = function () {
  9749. return this._gl.createTexture();
  9750. };
  9751. /**
  9752. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9753. * @param {string} urlArg- This contains one of the following:
  9754. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9755. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9756. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9757. *
  9758. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9759. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9760. * @param {Scene} scene- Needed for loading to the correct scene.
  9761. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9762. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9763. * @param {callback} onError- Optional callback to be called upon failure.
  9764. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9765. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9766. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9767. *
  9768. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9769. */
  9770. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9771. var _this = this;
  9772. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9773. if (onLoad === void 0) { onLoad = null; }
  9774. if (onError === void 0) { onError = null; }
  9775. if (buffer === void 0) { buffer = null; }
  9776. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9777. var fromData = url.substr(0, 5) === "data:";
  9778. var fromBlob = url.substr(0, 5) === "blob:";
  9779. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9780. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9781. // establish the file extension, if possible
  9782. var lastDot = url.lastIndexOf('.');
  9783. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9784. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9785. var isTGA = (extension === ".tga");
  9786. // determine if a ktx file should be substituted
  9787. var isKTX = false;
  9788. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9789. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9790. isKTX = true;
  9791. }
  9792. if (scene) {
  9793. scene._addPendingData(texture);
  9794. }
  9795. texture.url = url;
  9796. texture.generateMipMaps = !noMipmap;
  9797. texture.samplingMode = samplingMode;
  9798. texture.invertY = invertY;
  9799. if (!this._doNotHandleContextLost) {
  9800. // Keep a link to the buffer only if we plan to handle context lost
  9801. texture._buffer = buffer;
  9802. }
  9803. if (onLoad) {
  9804. texture.onLoadedObservable.add(onLoad);
  9805. }
  9806. if (!fallBack)
  9807. this._internalTexturesCache.push(texture);
  9808. var onerror = function () {
  9809. if (scene) {
  9810. scene._removePendingData(texture);
  9811. }
  9812. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9813. if (isKTX) {
  9814. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9815. }
  9816. else if (onError) {
  9817. onError();
  9818. }
  9819. };
  9820. var callback;
  9821. // processing for non-image formats
  9822. if (isKTX || isTGA || isDDS) {
  9823. if (isKTX) {
  9824. callback = function (data) {
  9825. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9826. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9827. ktx.uploadLevels(_this._gl, !noMipmap);
  9828. return false;
  9829. }, samplingMode);
  9830. };
  9831. }
  9832. else if (isTGA) {
  9833. callback = function (arrayBuffer) {
  9834. var data = new Uint8Array(arrayBuffer);
  9835. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9836. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9837. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9838. return false;
  9839. }, samplingMode);
  9840. };
  9841. }
  9842. else if (isDDS) {
  9843. callback = function (data) {
  9844. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9845. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9846. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9847. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9848. return false;
  9849. }, samplingMode);
  9850. };
  9851. }
  9852. if (!buffer) {
  9853. BABYLON.Tools.LoadFile(url, function (data) {
  9854. callback(data);
  9855. }, null, scene ? scene.database : null, true, onerror);
  9856. }
  9857. else {
  9858. callback(buffer);
  9859. }
  9860. // image format processing
  9861. }
  9862. else {
  9863. var onload = function (img) {
  9864. if (fromBlob && !_this._doNotHandleContextLost) {
  9865. // We need to store the image if we need to rebuild the texture
  9866. // in case of a webgl context lost
  9867. texture._buffer = img;
  9868. }
  9869. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9870. var gl = _this._gl;
  9871. var isPot = (img.width === potWidth && img.height === potHeight);
  9872. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9873. if (isPot) {
  9874. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9875. return false;
  9876. }
  9877. // Using shaders to rescale because canvas.drawImage is lossy
  9878. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9879. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9880. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9881. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9884. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9885. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9886. _this._releaseTexture(source);
  9887. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9888. continuationCallback();
  9889. });
  9890. return true;
  9891. }, samplingMode);
  9892. };
  9893. if (!fromData || isBase64)
  9894. if (buffer instanceof HTMLImageElement) {
  9895. onload(buffer);
  9896. }
  9897. else {
  9898. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9899. }
  9900. else if (buffer instanceof Array || typeof buffer === "string")
  9901. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9902. else
  9903. onload(buffer);
  9904. }
  9905. return texture;
  9906. };
  9907. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9908. var _this = this;
  9909. var rtt = this.createRenderTargetTexture({
  9910. width: destination.width,
  9911. height: destination.height,
  9912. }, {
  9913. generateMipMaps: false,
  9914. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9915. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9916. generateDepthBuffer: false,
  9917. generateStencilBuffer: false
  9918. });
  9919. if (!this._rescalePostProcess) {
  9920. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9921. }
  9922. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9923. _this._rescalePostProcess.onApply = function (effect) {
  9924. effect._bindTexture("textureSampler", source);
  9925. };
  9926. var hostingScene = scene;
  9927. if (!hostingScene) {
  9928. hostingScene = _this.scenes[_this.scenes.length - 1];
  9929. }
  9930. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9931. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9932. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9933. _this.unBindFramebuffer(rtt);
  9934. _this._releaseTexture(rtt);
  9935. if (onComplete) {
  9936. onComplete();
  9937. }
  9938. });
  9939. };
  9940. Engine.prototype._getInternalFormat = function (format) {
  9941. var internalFormat = this._gl.RGBA;
  9942. switch (format) {
  9943. case Engine.TEXTUREFORMAT_ALPHA:
  9944. internalFormat = this._gl.ALPHA;
  9945. break;
  9946. case Engine.TEXTUREFORMAT_LUMINANCE:
  9947. internalFormat = this._gl.LUMINANCE;
  9948. break;
  9949. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9950. internalFormat = this._gl.LUMINANCE_ALPHA;
  9951. break;
  9952. case Engine.TEXTUREFORMAT_RGB:
  9953. internalFormat = this._gl.RGB;
  9954. break;
  9955. case Engine.TEXTUREFORMAT_RGBA:
  9956. internalFormat = this._gl.RGBA;
  9957. break;
  9958. }
  9959. return internalFormat;
  9960. };
  9961. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9962. if (compression === void 0) { compression = null; }
  9963. var internalFormat = this._getInternalFormat(format);
  9964. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9965. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9966. if (!this._doNotHandleContextLost) {
  9967. texture._bufferView = data;
  9968. texture.format = format;
  9969. texture.invertY = invertY;
  9970. texture._compression = compression;
  9971. }
  9972. if (texture.width % 4 !== 0) {
  9973. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9974. }
  9975. if (compression) {
  9976. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9977. }
  9978. else {
  9979. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9980. }
  9981. if (texture.generateMipMaps) {
  9982. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9983. }
  9984. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9985. this.resetTextureCache();
  9986. texture.isReady = true;
  9987. };
  9988. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9989. if (compression === void 0) { compression = null; }
  9990. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9991. texture.baseWidth = width;
  9992. texture.baseHeight = height;
  9993. texture.width = width;
  9994. texture.height = height;
  9995. texture.format = format;
  9996. texture.generateMipMaps = generateMipMaps;
  9997. texture.samplingMode = samplingMode;
  9998. texture.invertY = invertY;
  9999. texture._compression = compression;
  10000. if (!this._doNotHandleContextLost) {
  10001. texture._bufferView = data;
  10002. }
  10003. this.updateRawTexture(texture, data, format, invertY, compression);
  10004. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10005. // Filters
  10006. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10007. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10008. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10009. if (generateMipMaps) {
  10010. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10011. }
  10012. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10013. this._internalTexturesCache.push(texture);
  10014. return texture;
  10015. };
  10016. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10017. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10018. texture.baseWidth = width;
  10019. texture.baseHeight = height;
  10020. if (generateMipMaps) {
  10021. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10022. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10023. }
  10024. this.resetTextureCache();
  10025. texture.width = width;
  10026. texture.height = height;
  10027. texture.isReady = false;
  10028. texture.generateMipMaps = generateMipMaps;
  10029. texture.samplingMode = samplingMode;
  10030. this.updateTextureSamplingMode(samplingMode, texture);
  10031. this._internalTexturesCache.push(texture);
  10032. return texture;
  10033. };
  10034. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10035. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10036. if (texture.isCube) {
  10037. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10038. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10039. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10040. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10041. }
  10042. else {
  10043. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10044. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10045. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10046. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10047. }
  10048. texture.samplingMode = samplingMode;
  10049. };
  10050. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10051. if (premulAlpha === void 0) { premulAlpha = false; }
  10052. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10053. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10054. if (premulAlpha) {
  10055. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10056. }
  10057. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10058. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10059. if (texture.generateMipMaps) {
  10060. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10061. }
  10062. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10063. if (premulAlpha) {
  10064. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10065. }
  10066. this.resetTextureCache();
  10067. texture.isReady = true;
  10068. };
  10069. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10070. if (texture._isDisabled) {
  10071. return;
  10072. }
  10073. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10074. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10075. try {
  10076. // Testing video texture support
  10077. if (this._videoTextureSupported === undefined) {
  10078. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10079. if (this._gl.getError() !== 0) {
  10080. this._videoTextureSupported = false;
  10081. }
  10082. else {
  10083. this._videoTextureSupported = true;
  10084. }
  10085. }
  10086. // Copy video through the current working canvas if video texture is not supported
  10087. if (!this._videoTextureSupported) {
  10088. if (!texture._workingCanvas) {
  10089. texture._workingCanvas = document.createElement("canvas");
  10090. texture._workingContext = texture._workingCanvas.getContext("2d");
  10091. texture._workingCanvas.width = texture.width;
  10092. texture._workingCanvas.height = texture.height;
  10093. }
  10094. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10095. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10096. }
  10097. else {
  10098. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10099. }
  10100. if (texture.generateMipMaps) {
  10101. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10102. }
  10103. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10104. this.resetTextureCache();
  10105. texture.isReady = true;
  10106. }
  10107. catch (ex) {
  10108. // Something unexpected
  10109. // Let's disable the texture
  10110. texture._isDisabled = true;
  10111. }
  10112. };
  10113. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10114. var fullOptions = new RenderTargetCreationOptions();
  10115. if (options !== undefined && typeof options === "object") {
  10116. fullOptions.generateMipMaps = options.generateMipMaps;
  10117. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10118. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10119. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10120. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10121. }
  10122. else {
  10123. fullOptions.generateMipMaps = options;
  10124. fullOptions.generateDepthBuffer = true;
  10125. fullOptions.generateStencilBuffer = false;
  10126. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10127. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10128. }
  10129. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10130. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10131. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10132. }
  10133. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10134. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10135. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10136. }
  10137. var gl = this._gl;
  10138. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10139. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10140. var width = size.width || size;
  10141. var height = size.height || size;
  10142. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10143. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10144. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10145. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10146. }
  10147. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10148. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10149. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10150. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10151. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10152. // Create the framebuffer
  10153. var framebuffer = gl.createFramebuffer();
  10154. this.bindUnboundFramebuffer(framebuffer);
  10155. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10156. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10157. if (fullOptions.generateMipMaps) {
  10158. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10159. }
  10160. // Unbind
  10161. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10162. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10163. this.bindUnboundFramebuffer(null);
  10164. texture._framebuffer = framebuffer;
  10165. texture.baseWidth = width;
  10166. texture.baseHeight = height;
  10167. texture.width = width;
  10168. texture.height = height;
  10169. texture.isReady = true;
  10170. texture.samples = 1;
  10171. texture.generateMipMaps = fullOptions.generateMipMaps;
  10172. texture.samplingMode = fullOptions.samplingMode;
  10173. texture.type = fullOptions.type;
  10174. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10175. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10176. this.resetTextureCache();
  10177. this._internalTexturesCache.push(texture);
  10178. return texture;
  10179. };
  10180. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10181. var generateMipMaps = false;
  10182. var generateDepthBuffer = true;
  10183. var generateStencilBuffer = false;
  10184. var generateDepthTexture = false;
  10185. var textureCount = 1;
  10186. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10187. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10188. var types = [], samplingModes = [];
  10189. if (options !== undefined) {
  10190. generateMipMaps = options.generateMipMaps;
  10191. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10192. generateStencilBuffer = options.generateStencilBuffer;
  10193. generateDepthTexture = options.generateDepthTexture;
  10194. textureCount = options.textureCount || 1;
  10195. if (options.types) {
  10196. types = options.types;
  10197. }
  10198. if (options.samplingModes) {
  10199. samplingModes = options.samplingModes;
  10200. }
  10201. }
  10202. var gl = this._gl;
  10203. // Create the framebuffer
  10204. var framebuffer = gl.createFramebuffer();
  10205. this.bindUnboundFramebuffer(framebuffer);
  10206. var width = size.width || size;
  10207. var height = size.height || size;
  10208. var textures = [];
  10209. var attachments = [];
  10210. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10211. for (var i = 0; i < textureCount; i++) {
  10212. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10213. var type = types[i] || defaultType;
  10214. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10215. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10216. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10217. }
  10218. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10219. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10220. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10221. }
  10222. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10223. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10224. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10225. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10226. }
  10227. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10228. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10229. textures.push(texture);
  10230. attachments.push(attachment);
  10231. gl.activeTexture(gl["TEXTURE" + i]);
  10232. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10233. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10234. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10235. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10236. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10237. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10238. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10239. if (generateMipMaps) {
  10240. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10241. }
  10242. // Unbind
  10243. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10244. texture._framebuffer = framebuffer;
  10245. texture._depthStencilBuffer = depthStencilBuffer;
  10246. texture.baseWidth = width;
  10247. texture.baseHeight = height;
  10248. texture.width = width;
  10249. texture.height = height;
  10250. texture.isReady = true;
  10251. texture.samples = 1;
  10252. texture.generateMipMaps = generateMipMaps;
  10253. texture.samplingMode = samplingMode;
  10254. texture.type = type;
  10255. texture._generateDepthBuffer = generateDepthBuffer;
  10256. texture._generateStencilBuffer = generateStencilBuffer;
  10257. this._internalTexturesCache.push(texture);
  10258. }
  10259. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10260. // Depth texture
  10261. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10262. gl.activeTexture(gl.TEXTURE0);
  10263. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10264. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10268. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10269. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10270. depthTexture._framebuffer = framebuffer;
  10271. depthTexture.baseWidth = width;
  10272. depthTexture.baseHeight = height;
  10273. depthTexture.width = width;
  10274. depthTexture.height = height;
  10275. depthTexture.isReady = true;
  10276. depthTexture.samples = 1;
  10277. depthTexture.generateMipMaps = generateMipMaps;
  10278. depthTexture.samplingMode = gl.NEAREST;
  10279. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10280. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10281. textures.push(depthTexture);
  10282. this._internalTexturesCache.push(depthTexture);
  10283. }
  10284. gl.drawBuffers(attachments);
  10285. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10286. this.bindUnboundFramebuffer(null);
  10287. this.resetTextureCache();
  10288. return textures;
  10289. };
  10290. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10291. if (samples === void 0) { samples = 1; }
  10292. var depthStencilBuffer = null;
  10293. var gl = this._gl;
  10294. // Create the depth/stencil buffer
  10295. if (generateStencilBuffer) {
  10296. depthStencilBuffer = gl.createRenderbuffer();
  10297. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10298. if (samples > 1) {
  10299. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10300. }
  10301. else {
  10302. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10303. }
  10304. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10305. }
  10306. else if (generateDepthBuffer) {
  10307. depthStencilBuffer = gl.createRenderbuffer();
  10308. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10309. if (samples > 1) {
  10310. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10311. }
  10312. else {
  10313. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10314. }
  10315. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10316. }
  10317. return depthStencilBuffer;
  10318. };
  10319. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10320. if (this.webGLVersion < 2) {
  10321. return 1;
  10322. }
  10323. if (texture.samples === samples) {
  10324. return samples;
  10325. }
  10326. var gl = this._gl;
  10327. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10328. // Dispose previous render buffers
  10329. if (texture._depthStencilBuffer) {
  10330. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10331. }
  10332. if (texture._MSAAFramebuffer) {
  10333. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10334. }
  10335. if (texture._MSAARenderBuffer) {
  10336. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10337. }
  10338. if (samples > 1) {
  10339. texture._MSAAFramebuffer = gl.createFramebuffer();
  10340. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10341. var colorRenderbuffer = gl.createRenderbuffer();
  10342. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10343. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10344. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10345. texture._MSAARenderBuffer = colorRenderbuffer;
  10346. }
  10347. else {
  10348. this.bindUnboundFramebuffer(texture._framebuffer);
  10349. }
  10350. texture.samples = samples;
  10351. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10352. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10353. this.bindUnboundFramebuffer(null);
  10354. return samples;
  10355. };
  10356. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10357. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10358. };
  10359. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10360. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10361. };
  10362. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10363. var gl = this._gl;
  10364. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10365. var generateMipMaps = true;
  10366. var generateDepthBuffer = true;
  10367. var generateStencilBuffer = false;
  10368. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10369. if (options !== undefined) {
  10370. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10371. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10372. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10373. if (options.samplingMode !== undefined) {
  10374. samplingMode = options.samplingMode;
  10375. }
  10376. }
  10377. texture.isCube = true;
  10378. texture.generateMipMaps = generateMipMaps;
  10379. texture.samples = 1;
  10380. texture.samplingMode = samplingMode;
  10381. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10382. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10383. for (var face = 0; face < 6; face++) {
  10384. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10385. }
  10386. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10387. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10388. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10389. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10390. // Create the framebuffer
  10391. var framebuffer = gl.createFramebuffer();
  10392. this.bindUnboundFramebuffer(framebuffer);
  10393. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10394. // Mipmaps
  10395. if (texture.generateMipMaps) {
  10396. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10397. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10398. }
  10399. // Unbind
  10400. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10401. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10402. this.bindUnboundFramebuffer(null);
  10403. texture._framebuffer = framebuffer;
  10404. texture.width = size;
  10405. texture.height = size;
  10406. texture.isReady = true;
  10407. this.resetTextureCache();
  10408. this._internalTexturesCache.push(texture);
  10409. return texture;
  10410. };
  10411. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10412. var _this = this;
  10413. if (onError === void 0) { onError = null; }
  10414. if (forcedExtension === void 0) { forcedExtension = null; }
  10415. var callback = function (loadData) {
  10416. if (!loadData) {
  10417. if (onLoad) {
  10418. onLoad(null);
  10419. }
  10420. return;
  10421. }
  10422. var texture = loadData.texture;
  10423. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10424. texture._lodGenerationScale = scale;
  10425. texture._lodGenerationOffset = offset;
  10426. if (_this._caps.textureLOD) {
  10427. // Do not add extra process if texture lod is supported.
  10428. if (onLoad) {
  10429. onLoad(texture);
  10430. }
  10431. return;
  10432. }
  10433. var mipSlices = 3;
  10434. var gl = _this._gl;
  10435. var width = loadData.width;
  10436. if (!width) {
  10437. return;
  10438. }
  10439. var textures = [];
  10440. for (var i = 0; i < mipSlices; i++) {
  10441. //compute LOD from even spacing in smoothness (matching shader calculation)
  10442. var smoothness = i / (mipSlices - 1);
  10443. var roughness = 1 - smoothness;
  10444. var minLODIndex = offset; // roughness = 0
  10445. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10446. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10447. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10448. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10449. glTextureFromLod.isCube = true;
  10450. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10451. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10452. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10453. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10454. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10455. if (loadData.isDDS) {
  10456. var info = loadData.info;
  10457. var data = loadData.data;
  10458. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10459. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10460. }
  10461. else {
  10462. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10463. }
  10464. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10465. // Wrap in a base texture for easy binding.
  10466. var lodTexture = new BABYLON.BaseTexture(scene);
  10467. lodTexture.isCube = true;
  10468. lodTexture._texture = glTextureFromLod;
  10469. glTextureFromLod.isReady = true;
  10470. textures.push(lodTexture);
  10471. }
  10472. texture._lodTextureHigh = textures[2];
  10473. texture._lodTextureMid = textures[1];
  10474. texture._lodTextureLow = textures[0];
  10475. if (onLoad) {
  10476. onLoad(texture);
  10477. }
  10478. };
  10479. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10480. };
  10481. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10482. var _this = this;
  10483. if (onLoad === void 0) { onLoad = null; }
  10484. if (onError === void 0) { onError = null; }
  10485. if (forcedExtension === void 0) { forcedExtension = null; }
  10486. var gl = this._gl;
  10487. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10488. texture.isCube = true;
  10489. texture.url = rootUrl;
  10490. texture.generateMipMaps = !noMipmap;
  10491. if (!this._doNotHandleContextLost) {
  10492. texture._extension = forcedExtension;
  10493. texture._files = files;
  10494. }
  10495. var isKTX = false;
  10496. var isDDS = false;
  10497. var lastDot = rootUrl.lastIndexOf('.');
  10498. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10499. if (this._textureFormatInUse) {
  10500. extension = this._textureFormatInUse;
  10501. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10502. isKTX = true;
  10503. }
  10504. else {
  10505. isDDS = (extension === ".dds");
  10506. }
  10507. if (isKTX) {
  10508. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10509. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10510. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10511. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10512. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10513. ktx.uploadLevels(_this._gl, !noMipmap);
  10514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10518. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10519. _this.resetTextureCache();
  10520. texture.width = ktx.pixelWidth;
  10521. texture.height = ktx.pixelHeight;
  10522. texture.isReady = true;
  10523. }, null, null, true, onError);
  10524. }
  10525. else if (isDDS) {
  10526. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10527. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10528. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10529. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10530. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10531. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10532. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10533. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10534. }
  10535. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10538. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10539. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10540. _this.resetTextureCache();
  10541. texture.width = info.width;
  10542. texture.height = info.height;
  10543. texture.isReady = true;
  10544. texture.type = info.textureType;
  10545. if (onLoad) {
  10546. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10547. }
  10548. }, null, null, true, onError);
  10549. }
  10550. else {
  10551. cascadeLoad(rootUrl, scene, function (imgs) {
  10552. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10553. var height = width;
  10554. _this._prepareWorkingCanvas();
  10555. _this._workingCanvas.width = width;
  10556. _this._workingCanvas.height = height;
  10557. var faces = [
  10558. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10559. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10560. ];
  10561. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10562. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10563. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10564. for (var index = 0; index < faces.length; index++) {
  10565. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10566. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10567. }
  10568. if (!noMipmap) {
  10569. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10570. }
  10571. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10572. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10575. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10576. _this.resetTextureCache();
  10577. texture.width = width;
  10578. texture.height = height;
  10579. texture.isReady = true;
  10580. texture.format = format;
  10581. texture.onLoadedObservable.notifyObservers(texture);
  10582. texture.onLoadedObservable.clear();
  10583. if (onLoad) {
  10584. onLoad();
  10585. }
  10586. }, files, onError);
  10587. }
  10588. this._internalTexturesCache.push(texture);
  10589. return texture;
  10590. };
  10591. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10592. if (compression === void 0) { compression = null; }
  10593. if (level === void 0) { level = 0; }
  10594. texture._bufferViewArray = data;
  10595. texture.format = format;
  10596. texture.type = type;
  10597. texture.invertY = invertY;
  10598. texture._compression = compression;
  10599. var gl = this._gl;
  10600. var textureType = this._getWebGLTextureType(type);
  10601. var internalFormat = this._getInternalFormat(format);
  10602. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10603. var needConversion = false;
  10604. if (internalFormat === gl.RGB) {
  10605. internalFormat = gl.RGBA;
  10606. needConversion = true;
  10607. }
  10608. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10609. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10610. if (texture.width % 4 !== 0) {
  10611. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10612. }
  10613. // Data are known to be in +X +Y +Z -X -Y -Z
  10614. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10615. var faceData = data[faceIndex];
  10616. if (compression) {
  10617. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10618. }
  10619. else {
  10620. if (needConversion) {
  10621. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10622. }
  10623. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10624. }
  10625. }
  10626. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10627. if (isPot && texture.generateMipMaps && level === 0) {
  10628. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10629. }
  10630. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10631. this.resetTextureCache();
  10632. texture.isReady = true;
  10633. };
  10634. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10635. if (compression === void 0) { compression = null; }
  10636. var gl = this._gl;
  10637. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10638. texture.isCube = true;
  10639. texture.generateMipMaps = generateMipMaps;
  10640. texture.format = format;
  10641. texture.type = type;
  10642. if (!this._doNotHandleContextLost) {
  10643. texture._bufferViewArray = data;
  10644. }
  10645. var textureType = this._getWebGLTextureType(type);
  10646. var internalFormat = this._getInternalFormat(format);
  10647. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10648. var needConversion = false;
  10649. if (internalFormat === gl.RGB) {
  10650. internalFormat = gl.RGBA;
  10651. needConversion = true;
  10652. }
  10653. var width = size;
  10654. var height = width;
  10655. texture.width = width;
  10656. texture.height = height;
  10657. // Double check on POT to generate Mips.
  10658. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10659. if (!isPot) {
  10660. generateMipMaps = false;
  10661. }
  10662. // Upload data if needed. The texture won't be ready until then.
  10663. if (data) {
  10664. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10665. }
  10666. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10667. // Filters
  10668. if (data && generateMipMaps) {
  10669. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10670. }
  10671. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10672. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10673. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10674. }
  10675. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10676. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10677. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10678. }
  10679. else {
  10680. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10681. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10682. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10683. }
  10684. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10686. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10687. return texture;
  10688. };
  10689. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10690. var _this = this;
  10691. if (onLoad === void 0) { onLoad = null; }
  10692. if (onError === void 0) { onError = null; }
  10693. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10694. if (invertY === void 0) { invertY = false; }
  10695. var gl = this._gl;
  10696. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10697. scene._addPendingData(texture);
  10698. texture.url = url;
  10699. this._internalTexturesCache.push(texture);
  10700. var onerror = function () {
  10701. scene._removePendingData(texture);
  10702. if (onError) {
  10703. onError();
  10704. }
  10705. };
  10706. var internalCallback = function (data) {
  10707. var width = texture.width;
  10708. var height = texture.height;
  10709. var faceDataArrays = callback(data);
  10710. if (mipmmapGenerator) {
  10711. var textureType = _this._getWebGLTextureType(type);
  10712. var internalFormat = _this._getInternalFormat(format);
  10713. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10714. var needConversion = false;
  10715. if (internalFormat === gl.RGB) {
  10716. internalFormat = gl.RGBA;
  10717. needConversion = true;
  10718. }
  10719. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10720. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10721. var mipData = mipmmapGenerator(faceDataArrays);
  10722. for (var level = 0; level < mipData.length; level++) {
  10723. var mipSize = width >> level;
  10724. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10725. var mipFaceData = mipData[level][faceIndex];
  10726. if (needConversion) {
  10727. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10728. }
  10729. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10730. }
  10731. }
  10732. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10733. }
  10734. else {
  10735. texture.generateMipMaps = !noMipmap;
  10736. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10737. }
  10738. texture.isReady = true;
  10739. _this.resetTextureCache();
  10740. scene._removePendingData(texture);
  10741. if (onLoad) {
  10742. onLoad();
  10743. }
  10744. };
  10745. BABYLON.Tools.LoadFile(url, function (data) {
  10746. internalCallback(data);
  10747. }, onerror, scene.database, true);
  10748. return texture;
  10749. };
  10750. ;
  10751. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10752. var gl = this._gl;
  10753. if (!gl) {
  10754. return;
  10755. }
  10756. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10757. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10758. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10759. if (!noMipmap && !isCompressed) {
  10760. gl.generateMipmap(gl.TEXTURE_2D);
  10761. }
  10762. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10763. this.resetTextureCache();
  10764. if (scene) {
  10765. scene._removePendingData(texture);
  10766. }
  10767. texture.onLoadedObservable.notifyObservers(texture);
  10768. texture.onLoadedObservable.clear();
  10769. };
  10770. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10771. var _this = this;
  10772. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10773. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10774. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10775. var gl = this._gl;
  10776. if (!gl) {
  10777. return;
  10778. }
  10779. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10780. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10781. texture.baseWidth = width;
  10782. texture.baseHeight = height;
  10783. texture.width = potWidth;
  10784. texture.height = potHeight;
  10785. texture.isReady = true;
  10786. if (processFunction(potWidth, potHeight, function () {
  10787. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10788. })) {
  10789. // Returning as texture needs extra async steps
  10790. return;
  10791. }
  10792. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10793. };
  10794. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10795. // Create new RGBA data container.
  10796. var rgbaData;
  10797. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10798. rgbaData = new Float32Array(width * height * 4);
  10799. }
  10800. else {
  10801. rgbaData = new Uint32Array(width * height * 4);
  10802. }
  10803. // Convert each pixel.
  10804. for (var x = 0; x < width; x++) {
  10805. for (var y = 0; y < height; y++) {
  10806. var index = (y * width + x) * 3;
  10807. var newIndex = (y * width + x) * 4;
  10808. // Map Old Value to new value.
  10809. rgbaData[newIndex + 0] = rgbData[index + 0];
  10810. rgbaData[newIndex + 1] = rgbData[index + 1];
  10811. rgbaData[newIndex + 2] = rgbData[index + 2];
  10812. // Add fully opaque alpha channel.
  10813. rgbaData[newIndex + 3] = 1;
  10814. }
  10815. }
  10816. return rgbaData;
  10817. };
  10818. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10819. var gl = this._gl;
  10820. if (texture._framebuffer) {
  10821. gl.deleteFramebuffer(texture._framebuffer);
  10822. texture._framebuffer = null;
  10823. }
  10824. if (texture._depthStencilBuffer) {
  10825. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10826. texture._depthStencilBuffer = null;
  10827. }
  10828. if (texture._MSAAFramebuffer) {
  10829. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10830. texture._MSAAFramebuffer = null;
  10831. }
  10832. if (texture._MSAARenderBuffer) {
  10833. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10834. texture._MSAARenderBuffer = null;
  10835. }
  10836. };
  10837. Engine.prototype._releaseTexture = function (texture) {
  10838. var gl = this._gl;
  10839. this._releaseFramebufferObjects(texture);
  10840. gl.deleteTexture(texture._webGLTexture);
  10841. // Unbind channels
  10842. this.unbindAllTextures();
  10843. var index = this._internalTexturesCache.indexOf(texture);
  10844. if (index !== -1) {
  10845. this._internalTexturesCache.splice(index, 1);
  10846. }
  10847. // Integrated fixed lod samplers.
  10848. if (texture._lodTextureHigh) {
  10849. texture._lodTextureHigh.dispose();
  10850. }
  10851. if (texture._lodTextureMid) {
  10852. texture._lodTextureMid.dispose();
  10853. }
  10854. if (texture._lodTextureLow) {
  10855. texture._lodTextureLow.dispose();
  10856. }
  10857. };
  10858. Engine.prototype.setProgram = function (program) {
  10859. if (this._currentProgram !== program) {
  10860. this._gl.useProgram(program);
  10861. this._currentProgram = program;
  10862. }
  10863. };
  10864. Engine.prototype.bindSamplers = function (effect) {
  10865. this.setProgram(effect.getProgram());
  10866. var samplers = effect.getSamplers();
  10867. for (var index = 0; index < samplers.length; index++) {
  10868. var uniform = effect.getUniform(samplers[index]);
  10869. this._gl.uniform1i(uniform, index);
  10870. }
  10871. this._currentEffect = null;
  10872. };
  10873. Engine.prototype.activateTexture = function (texture) {
  10874. if (this._activeTexture !== texture) {
  10875. this._gl.activeTexture(texture);
  10876. this._activeTexture = texture;
  10877. }
  10878. };
  10879. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10880. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10881. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10882. this._activeTexturesCache[this._activeTexture] = texture;
  10883. }
  10884. };
  10885. Engine.prototype._bindTexture = function (channel, texture) {
  10886. if (channel < 0) {
  10887. return;
  10888. }
  10889. this.activateTexture(this._gl.TEXTURE0 + channel);
  10890. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10891. };
  10892. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10893. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10894. };
  10895. Engine.prototype.unbindAllTextures = function () {
  10896. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10897. this.activateTexture(this._gl["TEXTURE" + channel]);
  10898. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10899. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10900. }
  10901. };
  10902. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10903. if (channel < 0) {
  10904. return;
  10905. }
  10906. this._gl.uniform1i(uniform, channel);
  10907. this._setTexture(channel, texture);
  10908. };
  10909. Engine.prototype._setTexture = function (channel, texture) {
  10910. // Not ready?
  10911. if (!texture) {
  10912. if (this._activeTexturesCache[channel] != null) {
  10913. this.activateTexture(this._gl["TEXTURE" + channel]);
  10914. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10915. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10916. }
  10917. return;
  10918. }
  10919. // Video
  10920. var alreadyActivated = false;
  10921. if (texture.video) {
  10922. this.activateTexture(this._gl["TEXTURE" + channel]);
  10923. alreadyActivated = true;
  10924. texture.update();
  10925. }
  10926. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10927. texture.delayLoad();
  10928. return;
  10929. }
  10930. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10931. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10932. if (this._activeTexturesCache[channel] === internalTexture) {
  10933. return;
  10934. }
  10935. if (!alreadyActivated) {
  10936. this.activateTexture(this._gl["TEXTURE" + channel]);
  10937. }
  10938. if (internalTexture.isCube) {
  10939. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10940. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10941. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10942. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10943. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10944. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10945. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10946. }
  10947. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10948. }
  10949. else {
  10950. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10951. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10952. internalTexture._cachedWrapU = texture.wrapU;
  10953. switch (texture.wrapU) {
  10954. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10955. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10956. break;
  10957. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10958. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10959. break;
  10960. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10961. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10962. break;
  10963. }
  10964. }
  10965. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10966. internalTexture._cachedWrapV = texture.wrapV;
  10967. switch (texture.wrapV) {
  10968. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10969. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10970. break;
  10971. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10972. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10973. break;
  10974. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10975. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10976. break;
  10977. }
  10978. }
  10979. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10980. }
  10981. };
  10982. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10983. if (channel < 0) {
  10984. return;
  10985. }
  10986. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10987. this._textureUnits = new Int32Array(textures.length);
  10988. }
  10989. for (var i = 0; i < textures.length; i++) {
  10990. this._textureUnits[i] = channel + i;
  10991. }
  10992. this._gl.uniform1iv(uniform, this._textureUnits);
  10993. for (var index = 0; index < textures.length; index++) {
  10994. this._setTexture(channel + index, textures[index]);
  10995. }
  10996. };
  10997. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10998. var internalTexture = texture.getInternalTexture();
  10999. if (!internalTexture) {
  11000. return;
  11001. }
  11002. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11003. var value = texture.anisotropicFilteringLevel;
  11004. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11005. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11006. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11007. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11008. }
  11009. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11010. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11011. internalTexture._cachedAnisotropicFilteringLevel = value;
  11012. }
  11013. };
  11014. Engine.prototype.readPixels = function (x, y, width, height) {
  11015. var data = new Uint8Array(height * width * 4);
  11016. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11017. return data;
  11018. };
  11019. /**
  11020. * Add an externaly attached data from its key.
  11021. * This method call will fail and return false, if such key already exists.
  11022. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11023. * @param key the unique key that identifies the data
  11024. * @param data the data object to associate to the key for this Engine instance
  11025. * @return true if no such key were already present and the data was added successfully, false otherwise
  11026. */
  11027. Engine.prototype.addExternalData = function (key, data) {
  11028. if (!this._externalData) {
  11029. this._externalData = new BABYLON.StringDictionary();
  11030. }
  11031. return this._externalData.add(key, data);
  11032. };
  11033. /**
  11034. * Get an externaly attached data from its key
  11035. * @param key the unique key that identifies the data
  11036. * @return the associated data, if present (can be null), or undefined if not present
  11037. */
  11038. Engine.prototype.getExternalData = function (key) {
  11039. if (!this._externalData) {
  11040. this._externalData = new BABYLON.StringDictionary();
  11041. }
  11042. return this._externalData.get(key);
  11043. };
  11044. /**
  11045. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11046. * @param key the unique key that identifies the data
  11047. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11048. * @return the associated data, can be null if the factory returned null.
  11049. */
  11050. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11051. if (!this._externalData) {
  11052. this._externalData = new BABYLON.StringDictionary();
  11053. }
  11054. return this._externalData.getOrAddWithFactory(key, factory);
  11055. };
  11056. /**
  11057. * Remove an externaly attached data from the Engine instance
  11058. * @param key the unique key that identifies the data
  11059. * @return true if the data was successfully removed, false if it doesn't exist
  11060. */
  11061. Engine.prototype.removeExternalData = function (key) {
  11062. if (!this._externalData) {
  11063. this._externalData = new BABYLON.StringDictionary();
  11064. }
  11065. return this._externalData.remove(key);
  11066. };
  11067. Engine.prototype.unbindAllAttributes = function () {
  11068. if (this._mustWipeVertexAttributes) {
  11069. this._mustWipeVertexAttributes = false;
  11070. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11071. this._gl.disableVertexAttribArray(i);
  11072. this._vertexAttribArraysEnabled[i] = false;
  11073. this._currentBufferPointers[i].active = false;
  11074. }
  11075. return;
  11076. }
  11077. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11078. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11079. continue;
  11080. }
  11081. this._gl.disableVertexAttribArray(i);
  11082. this._vertexAttribArraysEnabled[i] = false;
  11083. this._currentBufferPointers[i].active = false;
  11084. }
  11085. };
  11086. Engine.prototype.releaseEffects = function () {
  11087. for (var name in this._compiledEffects) {
  11088. this._gl.deleteProgram(this._compiledEffects[name]._program);
  11089. }
  11090. this._compiledEffects = {};
  11091. };
  11092. // Dispose
  11093. Engine.prototype.dispose = function () {
  11094. this.hideLoadingUI();
  11095. this.stopRenderLoop();
  11096. // Release postProcesses
  11097. while (this.postProcesses.length) {
  11098. this.postProcesses[0].dispose();
  11099. }
  11100. // Empty texture
  11101. if (this._emptyTexture) {
  11102. this._releaseTexture(this._emptyTexture);
  11103. this._emptyTexture = null;
  11104. }
  11105. if (this._emptyCubeTexture) {
  11106. this._releaseTexture(this._emptyCubeTexture);
  11107. this._emptyCubeTexture = null;
  11108. }
  11109. // Rescale PP
  11110. if (this._rescalePostProcess) {
  11111. this._rescalePostProcess.dispose();
  11112. }
  11113. // Release scenes
  11114. while (this.scenes.length) {
  11115. this.scenes[0].dispose();
  11116. }
  11117. // Release audio engine
  11118. if (Engine.audioEngine) {
  11119. Engine.audioEngine.dispose();
  11120. }
  11121. // Release effects
  11122. this.releaseEffects();
  11123. // Unbind
  11124. this.unbindAllAttributes();
  11125. if (this._dummyFramebuffer) {
  11126. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11127. }
  11128. this._gl = null;
  11129. //WebVR
  11130. this.disableVR();
  11131. // Events
  11132. window.removeEventListener("blur", this._onBlur);
  11133. window.removeEventListener("focus", this._onFocus);
  11134. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11135. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11136. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11137. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11138. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11139. if (!this._doNotHandleContextLost) {
  11140. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11141. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11142. }
  11143. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11144. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11145. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11146. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11147. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11148. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11149. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11150. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11151. // Remove from Instances
  11152. var index = Engine.Instances.indexOf(this);
  11153. if (index >= 0) {
  11154. Engine.Instances.splice(index, 1);
  11155. }
  11156. this._workingCanvas = null;
  11157. this._workingContext = null;
  11158. this._currentBufferPointers = null;
  11159. this._renderingCanvas = null;
  11160. this._currentProgram = null;
  11161. this.onResizeObservable.clear();
  11162. this.onCanvasBlurObservable.clear();
  11163. this.onCanvasFocusObservable.clear();
  11164. this.onCanvasPointerOutObservable.clear();
  11165. BABYLON.Effect.ResetCache();
  11166. };
  11167. // Loading screen
  11168. Engine.prototype.displayLoadingUI = function () {
  11169. var loadingScreen = this.loadingScreen;
  11170. if (loadingScreen) {
  11171. loadingScreen.displayLoadingUI();
  11172. }
  11173. };
  11174. Engine.prototype.hideLoadingUI = function () {
  11175. var loadingScreen = this.loadingScreen;
  11176. if (loadingScreen) {
  11177. loadingScreen.hideLoadingUI();
  11178. }
  11179. };
  11180. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11181. get: function () {
  11182. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11183. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11184. return this._loadingScreen;
  11185. },
  11186. set: function (loadingScreen) {
  11187. this._loadingScreen = loadingScreen;
  11188. },
  11189. enumerable: true,
  11190. configurable: true
  11191. });
  11192. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11193. set: function (text) {
  11194. this.loadingScreen.loadingUIText = text;
  11195. },
  11196. enumerable: true,
  11197. configurable: true
  11198. });
  11199. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11200. set: function (color) {
  11201. this.loadingScreen.loadingUIBackgroundColor = color;
  11202. },
  11203. enumerable: true,
  11204. configurable: true
  11205. });
  11206. Engine.prototype.attachContextLostEvent = function (callback) {
  11207. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11208. };
  11209. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11210. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11211. };
  11212. Engine.prototype.getVertexShaderSource = function (program) {
  11213. var shaders = this._gl.getAttachedShaders(program);
  11214. return this._gl.getShaderSource(shaders[0]);
  11215. };
  11216. Engine.prototype.getFragmentShaderSource = function (program) {
  11217. var shaders = this._gl.getAttachedShaders(program);
  11218. return this._gl.getShaderSource(shaders[1]);
  11219. };
  11220. Engine.prototype.getError = function () {
  11221. return this._gl.getError();
  11222. };
  11223. // FPS
  11224. Engine.prototype.getFps = function () {
  11225. return this._fps;
  11226. };
  11227. Engine.prototype.getDeltaTime = function () {
  11228. return this._deltaTime;
  11229. };
  11230. Engine.prototype._measureFps = function () {
  11231. this._performanceMonitor.sampleFrame();
  11232. this._fps = this._performanceMonitor.averageFPS;
  11233. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11234. };
  11235. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11236. if (faceIndex === void 0) { faceIndex = -1; }
  11237. var gl = this._gl;
  11238. if (!this._dummyFramebuffer) {
  11239. this._dummyFramebuffer = gl.createFramebuffer();
  11240. }
  11241. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11242. if (faceIndex > -1) {
  11243. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11244. }
  11245. else {
  11246. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11247. }
  11248. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11249. var buffer;
  11250. switch (readType) {
  11251. case gl.UNSIGNED_BYTE:
  11252. buffer = new Uint8Array(4 * width * height);
  11253. readType = gl.UNSIGNED_BYTE;
  11254. break;
  11255. default:
  11256. buffer = new Float32Array(4 * width * height);
  11257. readType = gl.FLOAT;
  11258. break;
  11259. }
  11260. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11261. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11262. return buffer;
  11263. };
  11264. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11265. if (this._webGLVersion > 1) {
  11266. return this._caps.colorBufferFloat;
  11267. }
  11268. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11269. };
  11270. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11271. if (this._webGLVersion > 1) {
  11272. return this._caps.colorBufferFloat;
  11273. }
  11274. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11275. };
  11276. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11277. Engine.prototype._canRenderToFramebuffer = function (type) {
  11278. var gl = this._gl;
  11279. //clear existing errors
  11280. while (gl.getError() !== gl.NO_ERROR) { }
  11281. var successful = true;
  11282. var texture = gl.createTexture();
  11283. gl.bindTexture(gl.TEXTURE_2D, texture);
  11284. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11286. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11287. var fb = gl.createFramebuffer();
  11288. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11289. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11290. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11291. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11292. successful = successful && (gl.getError() === gl.NO_ERROR);
  11293. //try render by clearing frame buffer's color buffer
  11294. if (successful) {
  11295. gl.clear(gl.COLOR_BUFFER_BIT);
  11296. successful = successful && (gl.getError() === gl.NO_ERROR);
  11297. }
  11298. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11299. if (successful) {
  11300. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11301. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11302. var readFormat = gl.RGBA;
  11303. var readType = gl.UNSIGNED_BYTE;
  11304. var buffer = new Uint8Array(4);
  11305. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11306. successful = successful && (gl.getError() === gl.NO_ERROR);
  11307. }
  11308. //clean up
  11309. gl.deleteTexture(texture);
  11310. gl.deleteFramebuffer(fb);
  11311. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11312. //clear accumulated errors
  11313. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11314. return successful;
  11315. };
  11316. Engine.prototype._getWebGLTextureType = function (type) {
  11317. if (type === Engine.TEXTURETYPE_FLOAT) {
  11318. return this._gl.FLOAT;
  11319. }
  11320. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11321. // Add Half Float Constant.
  11322. return this._gl.HALF_FLOAT_OES;
  11323. }
  11324. return this._gl.UNSIGNED_BYTE;
  11325. };
  11326. ;
  11327. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11328. if (this._webGLVersion === 1) {
  11329. return this._gl.RGBA;
  11330. }
  11331. if (type === Engine.TEXTURETYPE_FLOAT) {
  11332. return this._gl.RGBA32F;
  11333. }
  11334. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11335. return this._gl.RGBA16F;
  11336. }
  11337. return this._gl.RGBA;
  11338. };
  11339. ;
  11340. Engine.prototype.createQuery = function () {
  11341. return this._gl.createQuery();
  11342. };
  11343. Engine.prototype.deleteQuery = function (query) {
  11344. this._gl.deleteQuery(query);
  11345. return this;
  11346. };
  11347. Engine.prototype.isQueryResultAvailable = function (query) {
  11348. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11349. };
  11350. Engine.prototype.getQueryResult = function (query) {
  11351. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11352. };
  11353. Engine.prototype.beginQuery = function (algorithmType, query) {
  11354. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11355. this._gl.beginQuery(glAlgorithm, query);
  11356. };
  11357. Engine.prototype.endQuery = function (algorithmType) {
  11358. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11359. this._gl.endQuery(glAlgorithm);
  11360. return this;
  11361. };
  11362. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11363. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11364. };
  11365. // Statics
  11366. Engine.isSupported = function () {
  11367. try {
  11368. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11369. if (navigator.isCocoonJS) {
  11370. return true;
  11371. }
  11372. var tempcanvas = document.createElement("canvas");
  11373. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11374. return gl != null && !!window.WebGLRenderingContext;
  11375. }
  11376. catch (e) {
  11377. return false;
  11378. }
  11379. };
  11380. Engine.Instances = new Array();
  11381. // Const statics
  11382. Engine._ALPHA_DISABLE = 0;
  11383. Engine._ALPHA_ADD = 1;
  11384. Engine._ALPHA_COMBINE = 2;
  11385. Engine._ALPHA_SUBTRACT = 3;
  11386. Engine._ALPHA_MULTIPLY = 4;
  11387. Engine._ALPHA_MAXIMIZED = 5;
  11388. Engine._ALPHA_ONEONE = 6;
  11389. Engine._ALPHA_PREMULTIPLIED = 7;
  11390. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11391. Engine._ALPHA_INTERPOLATE = 9;
  11392. Engine._ALPHA_SCREENMODE = 10;
  11393. Engine._DELAYLOADSTATE_NONE = 0;
  11394. Engine._DELAYLOADSTATE_LOADED = 1;
  11395. Engine._DELAYLOADSTATE_LOADING = 2;
  11396. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11397. Engine._TEXTUREFORMAT_ALPHA = 0;
  11398. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11399. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11400. Engine._TEXTUREFORMAT_RGB = 4;
  11401. Engine._TEXTUREFORMAT_RGBA = 5;
  11402. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11403. Engine._TEXTURETYPE_FLOAT = 1;
  11404. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11405. // Depht or Stencil test Constants.
  11406. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11407. 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.
  11408. 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.
  11409. 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.
  11410. 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.
  11411. 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.
  11412. 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.
  11413. 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.
  11414. // Stencil Actions Constants.
  11415. Engine._KEEP = 0x1E00;
  11416. Engine._REPLACE = 0x1E01;
  11417. Engine._INCR = 0x1E02;
  11418. Engine._DECR = 0x1E03;
  11419. Engine._INVERT = 0x150A;
  11420. Engine._INCR_WRAP = 0x8507;
  11421. Engine._DECR_WRAP = 0x8508;
  11422. // Texture rescaling mode
  11423. Engine._SCALEMODE_FLOOR = 1;
  11424. Engine._SCALEMODE_NEAREST = 2;
  11425. Engine._SCALEMODE_CEILING = 3;
  11426. // Updatable statics so stick with vars here
  11427. Engine.CollisionsEpsilon = 0.001;
  11428. Engine.CodeRepository = "src/";
  11429. Engine.ShadersRepository = "src/Shaders/";
  11430. return Engine;
  11431. }());
  11432. BABYLON.Engine = Engine;
  11433. })(BABYLON || (BABYLON = {}));
  11434. //# sourceMappingURL=babylon.engine.js.map
  11435. /// <reference path="Tools\babylon.decorators.ts" />
  11436. var BABYLON;
  11437. (function (BABYLON) {
  11438. /**
  11439. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11440. */
  11441. var Node = (function () {
  11442. /**
  11443. * @constructor
  11444. * @param {string} name - the name and id to be given to this node
  11445. * @param {BABYLON.Scene} the scene this node will be added to
  11446. */
  11447. function Node(name, scene) {
  11448. this.state = "";
  11449. this.metadata = null;
  11450. this.doNotSerialize = false;
  11451. this.animations = new Array();
  11452. this._ranges = {};
  11453. this._childrenFlag = -1;
  11454. this._isEnabled = true;
  11455. this._isReady = true;
  11456. this._currentRenderId = -1;
  11457. this._parentRenderId = -1;
  11458. /**
  11459. * An event triggered when the mesh is disposed.
  11460. * @type {BABYLON.Observable}
  11461. */
  11462. this.onDisposeObservable = new BABYLON.Observable();
  11463. // Behaviors
  11464. this._behaviors = new Array();
  11465. this.name = name;
  11466. this.id = name;
  11467. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11468. this._initCache();
  11469. }
  11470. Object.defineProperty(Node.prototype, "parent", {
  11471. get: function () {
  11472. return this._parentNode;
  11473. },
  11474. set: function (parent) {
  11475. if (this._parentNode === parent) {
  11476. return;
  11477. }
  11478. if (this._parentNode) {
  11479. var index = this._parentNode._children.indexOf(this);
  11480. if (index !== -1) {
  11481. this._parentNode._children.splice(index, 1);
  11482. }
  11483. }
  11484. this._parentNode = parent;
  11485. if (this._parentNode) {
  11486. if (!this._parentNode._children) {
  11487. this._parentNode._children = new Array();
  11488. }
  11489. this._parentNode._children.push(this);
  11490. }
  11491. },
  11492. enumerable: true,
  11493. configurable: true
  11494. });
  11495. Node.prototype.getClassName = function () {
  11496. return "Node";
  11497. };
  11498. Object.defineProperty(Node.prototype, "onDispose", {
  11499. set: function (callback) {
  11500. if (this._onDisposeObserver) {
  11501. this.onDisposeObservable.remove(this._onDisposeObserver);
  11502. }
  11503. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11504. },
  11505. enumerable: true,
  11506. configurable: true
  11507. });
  11508. Node.prototype.getScene = function () {
  11509. return this._scene;
  11510. };
  11511. Node.prototype.getEngine = function () {
  11512. return this._scene.getEngine();
  11513. };
  11514. Node.prototype.addBehavior = function (behavior) {
  11515. var index = this._behaviors.indexOf(behavior);
  11516. if (index !== -1) {
  11517. return;
  11518. }
  11519. behavior.attach(this);
  11520. this._behaviors.push(behavior);
  11521. return this;
  11522. };
  11523. Node.prototype.removeBehavior = function (behavior) {
  11524. var index = this._behaviors.indexOf(behavior);
  11525. if (index === -1) {
  11526. return;
  11527. }
  11528. this._behaviors[index].detach();
  11529. this._behaviors.splice(index, 1);
  11530. return this;
  11531. };
  11532. Object.defineProperty(Node.prototype, "behaviors", {
  11533. get: function () {
  11534. return this._behaviors;
  11535. },
  11536. enumerable: true,
  11537. configurable: true
  11538. });
  11539. Node.prototype.getBehaviorByName = function (name) {
  11540. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11541. var behavior = _a[_i];
  11542. if (behavior.name === name) {
  11543. return behavior;
  11544. }
  11545. }
  11546. return null;
  11547. };
  11548. // override it in derived class
  11549. Node.prototype.getWorldMatrix = function () {
  11550. return BABYLON.Matrix.Identity();
  11551. };
  11552. // override it in derived class if you add new variables to the cache
  11553. // and call the parent class method
  11554. Node.prototype._initCache = function () {
  11555. this._cache = {};
  11556. this._cache.parent = undefined;
  11557. };
  11558. Node.prototype.updateCache = function (force) {
  11559. if (!force && this.isSynchronized())
  11560. return;
  11561. this._cache.parent = this.parent;
  11562. this._updateCache();
  11563. };
  11564. // override it in derived class if you add new variables to the cache
  11565. // and call the parent class method if !ignoreParentClass
  11566. Node.prototype._updateCache = function (ignoreParentClass) {
  11567. };
  11568. // override it in derived class if you add new variables to the cache
  11569. Node.prototype._isSynchronized = function () {
  11570. return true;
  11571. };
  11572. Node.prototype._markSyncedWithParent = function () {
  11573. this._parentRenderId = this.parent._currentRenderId;
  11574. };
  11575. Node.prototype.isSynchronizedWithParent = function () {
  11576. if (!this.parent) {
  11577. return true;
  11578. }
  11579. if (this._parentRenderId !== this.parent._currentRenderId) {
  11580. return false;
  11581. }
  11582. return this.parent.isSynchronized();
  11583. };
  11584. Node.prototype.isSynchronized = function (updateCache) {
  11585. var check = this.hasNewParent();
  11586. check = check || !this.isSynchronizedWithParent();
  11587. check = check || !this._isSynchronized();
  11588. if (updateCache)
  11589. this.updateCache(true);
  11590. return !check;
  11591. };
  11592. Node.prototype.hasNewParent = function (update) {
  11593. if (this._cache.parent === this.parent)
  11594. return false;
  11595. if (update)
  11596. this._cache.parent = this.parent;
  11597. return true;
  11598. };
  11599. /**
  11600. * Is this node ready to be used/rendered
  11601. * @return {boolean} is it ready
  11602. */
  11603. Node.prototype.isReady = function () {
  11604. return this._isReady;
  11605. };
  11606. /**
  11607. * Is this node enabled.
  11608. * If the node has a parent and is enabled, the parent will be inspected as well.
  11609. * @return {boolean} whether this node (and its parent) is enabled.
  11610. * @see setEnabled
  11611. */
  11612. Node.prototype.isEnabled = function () {
  11613. if (!this._isEnabled) {
  11614. return false;
  11615. }
  11616. if (this.parent) {
  11617. return this.parent.isEnabled();
  11618. }
  11619. return true;
  11620. };
  11621. /**
  11622. * Set the enabled state of this node.
  11623. * @param {boolean} value - the new enabled state
  11624. * @see isEnabled
  11625. */
  11626. Node.prototype.setEnabled = function (value) {
  11627. this._isEnabled = value;
  11628. };
  11629. /**
  11630. * Is this node a descendant of the given node.
  11631. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11632. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11633. * @see parent
  11634. */
  11635. Node.prototype.isDescendantOf = function (ancestor) {
  11636. if (this.parent) {
  11637. if (this.parent === ancestor) {
  11638. return true;
  11639. }
  11640. return this.parent.isDescendantOf(ancestor);
  11641. }
  11642. return false;
  11643. };
  11644. /**
  11645. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11646. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11647. * @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.
  11648. * @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.
  11649. */
  11650. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11651. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11652. if (!this._children) {
  11653. return;
  11654. }
  11655. for (var index = 0; index < this._children.length; index++) {
  11656. var item = this._children[index];
  11657. if (!predicate || predicate(item)) {
  11658. results.push(item);
  11659. }
  11660. if (!directDescendantsOnly) {
  11661. item._getDescendants(results, false, predicate);
  11662. }
  11663. }
  11664. };
  11665. /**
  11666. * Will return all nodes that have this node as ascendant.
  11667. * @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.
  11668. * @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.
  11669. * @return {BABYLON.Node[]} all children nodes of all types.
  11670. */
  11671. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11672. var results = [];
  11673. this._getDescendants(results, directDescendantsOnly, predicate);
  11674. return results;
  11675. };
  11676. /**
  11677. * Get all child-meshes of this node.
  11678. */
  11679. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11680. var results = [];
  11681. this._getDescendants(results, directDecendantsOnly, function (node) {
  11682. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11683. });
  11684. return results;
  11685. };
  11686. /**
  11687. * Get all direct children of this node.
  11688. */
  11689. Node.prototype.getChildren = function (predicate) {
  11690. return this.getDescendants(true, predicate);
  11691. };
  11692. Node.prototype._setReady = function (state) {
  11693. if (state === this._isReady) {
  11694. return;
  11695. }
  11696. if (!state) {
  11697. this._isReady = false;
  11698. return;
  11699. }
  11700. this._isReady = true;
  11701. if (this.onReady) {
  11702. this.onReady(this);
  11703. }
  11704. };
  11705. Node.prototype.getAnimationByName = function (name) {
  11706. for (var i = 0; i < this.animations.length; i++) {
  11707. var animation = this.animations[i];
  11708. if (animation.name === name) {
  11709. return animation;
  11710. }
  11711. }
  11712. return null;
  11713. };
  11714. Node.prototype.createAnimationRange = function (name, from, to) {
  11715. // check name not already in use
  11716. if (!this._ranges[name]) {
  11717. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11718. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11719. if (this.animations[i]) {
  11720. this.animations[i].createRange(name, from, to);
  11721. }
  11722. }
  11723. }
  11724. };
  11725. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11726. if (deleteFrames === void 0) { deleteFrames = true; }
  11727. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11728. if (this.animations[i]) {
  11729. this.animations[i].deleteRange(name, deleteFrames);
  11730. }
  11731. }
  11732. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11733. };
  11734. Node.prototype.getAnimationRange = function (name) {
  11735. return this._ranges[name];
  11736. };
  11737. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11738. var range = this.getAnimationRange(name);
  11739. if (!range) {
  11740. return null;
  11741. }
  11742. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11743. };
  11744. Node.prototype.serializeAnimationRanges = function () {
  11745. var serializationRanges = [];
  11746. for (var name in this._ranges) {
  11747. var range = {};
  11748. range.name = name;
  11749. range.from = this._ranges[name].from;
  11750. range.to = this._ranges[name].to;
  11751. serializationRanges.push(range);
  11752. }
  11753. return serializationRanges;
  11754. };
  11755. Node.prototype.dispose = function () {
  11756. this.parent = null;
  11757. // Callback
  11758. this.onDisposeObservable.notifyObservers(this);
  11759. this.onDisposeObservable.clear();
  11760. // Behaviors
  11761. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11762. var behavior = _a[_i];
  11763. behavior.detach();
  11764. }
  11765. this._behaviors = [];
  11766. };
  11767. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11768. if (parsedNode.ranges) {
  11769. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11770. var data = parsedNode.ranges[index];
  11771. node.createAnimationRange(data.name, data.from, data.to);
  11772. }
  11773. }
  11774. };
  11775. __decorate([
  11776. BABYLON.serialize()
  11777. ], Node.prototype, "name", void 0);
  11778. __decorate([
  11779. BABYLON.serialize()
  11780. ], Node.prototype, "id", void 0);
  11781. __decorate([
  11782. BABYLON.serialize()
  11783. ], Node.prototype, "uniqueId", void 0);
  11784. __decorate([
  11785. BABYLON.serialize()
  11786. ], Node.prototype, "state", void 0);
  11787. __decorate([
  11788. BABYLON.serialize()
  11789. ], Node.prototype, "metadata", void 0);
  11790. return Node;
  11791. }());
  11792. BABYLON.Node = Node;
  11793. })(BABYLON || (BABYLON = {}));
  11794. //# sourceMappingURL=babylon.node.js.map
  11795. var BABYLON;
  11796. (function (BABYLON) {
  11797. var BoundingSphere = (function () {
  11798. function BoundingSphere(minimum, maximum) {
  11799. this.minimum = minimum;
  11800. this.maximum = maximum;
  11801. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11802. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11803. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11804. this.radius = distance * 0.5;
  11805. this.centerWorld = BABYLON.Vector3.Zero();
  11806. this._update(BABYLON.Matrix.Identity());
  11807. }
  11808. // Methods
  11809. BoundingSphere.prototype._update = function (world) {
  11810. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11811. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11812. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11813. };
  11814. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11815. for (var i = 0; i < 6; i++) {
  11816. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11817. return false;
  11818. }
  11819. return true;
  11820. };
  11821. BoundingSphere.prototype.intersectsPoint = function (point) {
  11822. var x = this.centerWorld.x - point.x;
  11823. var y = this.centerWorld.y - point.y;
  11824. var z = this.centerWorld.z - point.z;
  11825. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11826. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11827. return false;
  11828. return true;
  11829. };
  11830. // Statics
  11831. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11832. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11833. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11834. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11835. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11836. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11837. return false;
  11838. return true;
  11839. };
  11840. return BoundingSphere;
  11841. }());
  11842. BABYLON.BoundingSphere = BoundingSphere;
  11843. })(BABYLON || (BABYLON = {}));
  11844. //# sourceMappingURL=babylon.boundingSphere.js.map
  11845. var BABYLON;
  11846. (function (BABYLON) {
  11847. var BoundingBox = (function () {
  11848. function BoundingBox(minimum, maximum) {
  11849. this.minimum = minimum;
  11850. this.maximum = maximum;
  11851. this.vectors = new Array();
  11852. this.vectorsWorld = new Array();
  11853. // Bounding vectors
  11854. this.vectors.push(this.minimum.clone());
  11855. this.vectors.push(this.maximum.clone());
  11856. this.vectors.push(this.minimum.clone());
  11857. this.vectors[2].x = this.maximum.x;
  11858. this.vectors.push(this.minimum.clone());
  11859. this.vectors[3].y = this.maximum.y;
  11860. this.vectors.push(this.minimum.clone());
  11861. this.vectors[4].z = this.maximum.z;
  11862. this.vectors.push(this.maximum.clone());
  11863. this.vectors[5].z = this.minimum.z;
  11864. this.vectors.push(this.maximum.clone());
  11865. this.vectors[6].x = this.minimum.x;
  11866. this.vectors.push(this.maximum.clone());
  11867. this.vectors[7].y = this.minimum.y;
  11868. // OBB
  11869. this.center = this.maximum.add(this.minimum).scale(0.5);
  11870. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11871. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11872. // World
  11873. for (var index = 0; index < this.vectors.length; index++) {
  11874. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11875. }
  11876. this.minimumWorld = BABYLON.Vector3.Zero();
  11877. this.maximumWorld = BABYLON.Vector3.Zero();
  11878. this.centerWorld = BABYLON.Vector3.Zero();
  11879. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11880. this._update(BABYLON.Matrix.Identity());
  11881. }
  11882. // Methods
  11883. BoundingBox.prototype.getWorldMatrix = function () {
  11884. return this._worldMatrix;
  11885. };
  11886. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11887. this._worldMatrix.copyFrom(matrix);
  11888. return this;
  11889. };
  11890. BoundingBox.prototype._update = function (world) {
  11891. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11892. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11893. for (var index = 0; index < this.vectors.length; index++) {
  11894. var v = this.vectorsWorld[index];
  11895. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11896. if (v.x < this.minimumWorld.x)
  11897. this.minimumWorld.x = v.x;
  11898. if (v.y < this.minimumWorld.y)
  11899. this.minimumWorld.y = v.y;
  11900. if (v.z < this.minimumWorld.z)
  11901. this.minimumWorld.z = v.z;
  11902. if (v.x > this.maximumWorld.x)
  11903. this.maximumWorld.x = v.x;
  11904. if (v.y > this.maximumWorld.y)
  11905. this.maximumWorld.y = v.y;
  11906. if (v.z > this.maximumWorld.z)
  11907. this.maximumWorld.z = v.z;
  11908. }
  11909. // Extend
  11910. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11911. this.extendSizeWorld.scaleInPlace(0.5);
  11912. // OBB
  11913. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11914. this.centerWorld.scaleInPlace(0.5);
  11915. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11916. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11917. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11918. this._worldMatrix = world;
  11919. };
  11920. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11921. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11922. };
  11923. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11924. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11925. };
  11926. BoundingBox.prototype.intersectsPoint = function (point) {
  11927. var delta = -BABYLON.Epsilon;
  11928. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11929. return false;
  11930. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11931. return false;
  11932. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11933. return false;
  11934. return true;
  11935. };
  11936. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11937. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11938. };
  11939. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11940. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11941. return false;
  11942. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11943. return false;
  11944. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11945. return false;
  11946. return true;
  11947. };
  11948. // Statics
  11949. BoundingBox.Intersects = function (box0, box1) {
  11950. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11951. return false;
  11952. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11953. return false;
  11954. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11955. return false;
  11956. return true;
  11957. };
  11958. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11959. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11960. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11961. return (num <= (sphereRadius * sphereRadius));
  11962. };
  11963. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11964. for (var p = 0; p < 6; p++) {
  11965. for (var i = 0; i < 8; i++) {
  11966. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11967. return false;
  11968. }
  11969. }
  11970. }
  11971. return true;
  11972. };
  11973. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11974. for (var p = 0; p < 6; p++) {
  11975. var inCount = 8;
  11976. for (var i = 0; i < 8; i++) {
  11977. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11978. --inCount;
  11979. }
  11980. else {
  11981. break;
  11982. }
  11983. }
  11984. if (inCount === 0)
  11985. return false;
  11986. }
  11987. return true;
  11988. };
  11989. return BoundingBox;
  11990. }());
  11991. BABYLON.BoundingBox = BoundingBox;
  11992. })(BABYLON || (BABYLON = {}));
  11993. //# sourceMappingURL=babylon.boundingBox.js.map
  11994. var BABYLON;
  11995. (function (BABYLON) {
  11996. var computeBoxExtents = function (axis, box) {
  11997. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11998. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11999. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12000. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12001. var r = r0 + r1 + r2;
  12002. return {
  12003. min: p - r,
  12004. max: p + r
  12005. };
  12006. };
  12007. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12008. var axisOverlap = function (axis, box0, box1) {
  12009. var result0 = computeBoxExtents(axis, box0);
  12010. var result1 = computeBoxExtents(axis, box1);
  12011. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12012. };
  12013. var BoundingInfo = (function () {
  12014. function BoundingInfo(minimum, maximum) {
  12015. this.minimum = minimum;
  12016. this.maximum = maximum;
  12017. this._isLocked = false;
  12018. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12019. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12020. }
  12021. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12022. get: function () {
  12023. return this._isLocked;
  12024. },
  12025. set: function (value) {
  12026. this._isLocked = value;
  12027. },
  12028. enumerable: true,
  12029. configurable: true
  12030. });
  12031. // Methods
  12032. BoundingInfo.prototype.update = function (world) {
  12033. if (this._isLocked) {
  12034. return;
  12035. }
  12036. this.boundingBox._update(world);
  12037. this.boundingSphere._update(world);
  12038. };
  12039. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12040. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12041. return false;
  12042. return this.boundingBox.isInFrustum(frustumPlanes);
  12043. };
  12044. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12045. /**
  12046. * Gets the world distance between the min and max points of the bounding box
  12047. */
  12048. get: function () {
  12049. var boundingBox = this.boundingBox;
  12050. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12051. return size.length();
  12052. },
  12053. enumerable: true,
  12054. configurable: true
  12055. });
  12056. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12057. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12058. };
  12059. BoundingInfo.prototype._checkCollision = function (collider) {
  12060. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12061. };
  12062. BoundingInfo.prototype.intersectsPoint = function (point) {
  12063. if (!this.boundingSphere.centerWorld) {
  12064. return false;
  12065. }
  12066. if (!this.boundingSphere.intersectsPoint(point)) {
  12067. return false;
  12068. }
  12069. if (!this.boundingBox.intersectsPoint(point)) {
  12070. return false;
  12071. }
  12072. return true;
  12073. };
  12074. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12075. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12076. return false;
  12077. }
  12078. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12079. return false;
  12080. }
  12081. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12082. return false;
  12083. }
  12084. if (!precise) {
  12085. return true;
  12086. }
  12087. var box0 = this.boundingBox;
  12088. var box1 = boundingInfo.boundingBox;
  12089. if (!axisOverlap(box0.directions[0], box0, box1))
  12090. return false;
  12091. if (!axisOverlap(box0.directions[1], box0, box1))
  12092. return false;
  12093. if (!axisOverlap(box0.directions[2], box0, box1))
  12094. return false;
  12095. if (!axisOverlap(box1.directions[0], box0, box1))
  12096. return false;
  12097. if (!axisOverlap(box1.directions[1], box0, box1))
  12098. return false;
  12099. if (!axisOverlap(box1.directions[2], box0, box1))
  12100. return false;
  12101. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12102. return false;
  12103. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12104. return false;
  12105. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12106. return false;
  12107. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12108. return false;
  12109. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12110. return false;
  12111. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12112. return false;
  12113. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12114. return false;
  12115. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12116. return false;
  12117. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12118. return false;
  12119. return true;
  12120. };
  12121. return BoundingInfo;
  12122. }());
  12123. BABYLON.BoundingInfo = BoundingInfo;
  12124. })(BABYLON || (BABYLON = {}));
  12125. //# sourceMappingURL=babylon.boundingInfo.js.map
  12126. var BABYLON;
  12127. (function (BABYLON) {
  12128. var AbstractMesh = (function (_super) {
  12129. __extends(AbstractMesh, _super);
  12130. // Constructor
  12131. function AbstractMesh(name, scene) {
  12132. var _this = _super.call(this, name, scene) || this;
  12133. _this._facetNb = 0; // facet number
  12134. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12135. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12136. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12137. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12138. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12139. _this._subDiv = {
  12140. max: 1,
  12141. X: 1,
  12142. Y: 1,
  12143. Z: 1
  12144. };
  12145. // Events
  12146. /**
  12147. * An event triggered when this mesh collides with another one
  12148. * @type {BABYLON.Observable}
  12149. */
  12150. _this.onCollideObservable = new BABYLON.Observable();
  12151. /**
  12152. * An event triggered when the collision's position changes
  12153. * @type {BABYLON.Observable}
  12154. */
  12155. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12156. /**
  12157. * An event triggered after the world matrix is updated
  12158. * @type {BABYLON.Observable}
  12159. */
  12160. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12161. /**
  12162. * An event triggered when material is changed
  12163. * @type {BABYLON.Observable}
  12164. */
  12165. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12166. // Properties
  12167. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12168. _this.position = BABYLON.Vector3.Zero();
  12169. /**
  12170. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12171. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12172. * or
  12173. * 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.
  12174. * for more info check WebGl documentations
  12175. */
  12176. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12177. /**
  12178. * 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:
  12179. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12180. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12181. * 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.
  12182. */
  12183. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12184. /**
  12185. * 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.
  12186. * The default value is -1 which means don't break the query and wait till the result.
  12187. */
  12188. _this.occlusionRetryCount = -1;
  12189. _this._occlusionInternalRetryCounter = 0;
  12190. _this._isOccluded = false;
  12191. _this._isOcclusionQueryInProgress = false;
  12192. _this._rotation = BABYLON.Vector3.Zero();
  12193. _this._scaling = BABYLON.Vector3.One();
  12194. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12195. _this.visibility = 1.0;
  12196. _this.alphaIndex = Number.MAX_VALUE;
  12197. _this.infiniteDistance = false;
  12198. _this.isVisible = true;
  12199. _this.isPickable = true;
  12200. _this.showBoundingBox = false;
  12201. _this.showSubMeshesBoundingBox = false;
  12202. _this.isBlocker = false;
  12203. _this.enablePointerMoveEvents = false;
  12204. _this.renderingGroupId = 0;
  12205. _this._receiveShadows = false;
  12206. _this.renderOutline = false;
  12207. _this.outlineColor = BABYLON.Color3.Red();
  12208. _this.outlineWidth = 0.02;
  12209. _this.renderOverlay = false;
  12210. _this.overlayColor = BABYLON.Color3.Red();
  12211. _this.overlayAlpha = 0.5;
  12212. _this._hasVertexAlpha = false;
  12213. _this._useVertexColors = true;
  12214. _this._computeBonesUsingShaders = true;
  12215. _this._numBoneInfluencers = 4;
  12216. _this._applyFog = true;
  12217. _this.scalingDeterminant = 1;
  12218. _this.useOctreeForRenderingSelection = true;
  12219. _this.useOctreeForPicking = true;
  12220. _this.useOctreeForCollisions = true;
  12221. _this._layerMask = 0x0FFFFFFF;
  12222. /**
  12223. * True if the mesh must be rendered in any case.
  12224. */
  12225. _this.alwaysSelectAsActiveMesh = false;
  12226. // Collisions
  12227. _this._checkCollisions = false;
  12228. _this._collisionMask = -1;
  12229. _this._collisionGroup = -1;
  12230. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12231. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12232. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12233. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12234. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12235. // Edges
  12236. _this.edgesWidth = 1;
  12237. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12238. // Cache
  12239. _this._localWorld = BABYLON.Matrix.Zero();
  12240. _this._worldMatrix = BABYLON.Matrix.Zero();
  12241. _this._absolutePosition = BABYLON.Vector3.Zero();
  12242. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12243. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12244. _this._isDirty = false;
  12245. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12246. _this._isDisposed = false;
  12247. _this._renderId = 0;
  12248. _this._intersectionsInProgress = new Array();
  12249. _this._isWorldMatrixFrozen = false;
  12250. _this._unIndexed = false;
  12251. _this._lightSources = new Array();
  12252. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12253. if (collidedMesh === void 0) { collidedMesh = null; }
  12254. //TODO move this to the collision coordinator!
  12255. if (_this.getScene().workerCollisions)
  12256. newPosition.multiplyInPlace(_this._collider.radius);
  12257. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12258. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12259. _this.position.addInPlace(_this._diffPositionForCollisions);
  12260. }
  12261. if (collidedMesh) {
  12262. _this.onCollideObservable.notifyObservers(collidedMesh);
  12263. }
  12264. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12265. };
  12266. _this.getScene().addMesh(_this);
  12267. _this._resyncLightSources();
  12268. return _this;
  12269. }
  12270. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12271. get: function () {
  12272. return AbstractMesh._BILLBOARDMODE_NONE;
  12273. },
  12274. enumerable: true,
  12275. configurable: true
  12276. });
  12277. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12278. get: function () {
  12279. return AbstractMesh._BILLBOARDMODE_X;
  12280. },
  12281. enumerable: true,
  12282. configurable: true
  12283. });
  12284. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12285. get: function () {
  12286. return AbstractMesh._BILLBOARDMODE_Y;
  12287. },
  12288. enumerable: true,
  12289. configurable: true
  12290. });
  12291. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12292. get: function () {
  12293. return AbstractMesh._BILLBOARDMODE_Z;
  12294. },
  12295. enumerable: true,
  12296. configurable: true
  12297. });
  12298. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12299. get: function () {
  12300. return AbstractMesh._BILLBOARDMODE_ALL;
  12301. },
  12302. enumerable: true,
  12303. configurable: true
  12304. });
  12305. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12306. /**
  12307. * Read-only : the number of facets in the mesh
  12308. */
  12309. get: function () {
  12310. return this._facetNb;
  12311. },
  12312. enumerable: true,
  12313. configurable: true
  12314. });
  12315. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12316. /**
  12317. * The number (integer) of subdivisions per axis in the partioning space
  12318. */
  12319. get: function () {
  12320. return this._partitioningSubdivisions;
  12321. },
  12322. set: function (nb) {
  12323. this._partitioningSubdivisions = nb;
  12324. },
  12325. enumerable: true,
  12326. configurable: true
  12327. });
  12328. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12329. /**
  12330. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12331. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12332. */
  12333. get: function () {
  12334. return this._partitioningBBoxRatio;
  12335. },
  12336. set: function (ratio) {
  12337. this._partitioningBBoxRatio = ratio;
  12338. },
  12339. enumerable: true,
  12340. configurable: true
  12341. });
  12342. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12343. /**
  12344. * Read-only boolean : is the feature facetData enabled ?
  12345. */
  12346. get: function () {
  12347. return this._facetDataEnabled;
  12348. },
  12349. enumerable: true,
  12350. configurable: true
  12351. });
  12352. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12353. set: function (callback) {
  12354. if (this._onCollideObserver) {
  12355. this.onCollideObservable.remove(this._onCollideObserver);
  12356. }
  12357. this._onCollideObserver = this.onCollideObservable.add(callback);
  12358. },
  12359. enumerable: true,
  12360. configurable: true
  12361. });
  12362. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12363. set: function (callback) {
  12364. if (this._onCollisionPositionChangeObserver) {
  12365. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12366. }
  12367. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12368. },
  12369. enumerable: true,
  12370. configurable: true
  12371. });
  12372. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12373. /**
  12374. * 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.
  12375. */
  12376. get: function () {
  12377. return this._isOccluded;
  12378. },
  12379. set: function (value) {
  12380. this._isOccluded = value;
  12381. },
  12382. enumerable: true,
  12383. configurable: true
  12384. });
  12385. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12386. /**
  12387. * Flag to check the progress status of the query
  12388. */
  12389. get: function () {
  12390. return this._isOcclusionQueryInProgress;
  12391. },
  12392. enumerable: true,
  12393. configurable: true
  12394. });
  12395. Object.defineProperty(AbstractMesh.prototype, "material", {
  12396. get: function () {
  12397. return this._material;
  12398. },
  12399. set: function (value) {
  12400. if (this._material === value) {
  12401. return;
  12402. }
  12403. this._material = value;
  12404. if (this.onMaterialChangedObservable.hasObservers) {
  12405. this.onMaterialChangedObservable.notifyObservers(this);
  12406. }
  12407. if (!this.subMeshes) {
  12408. return;
  12409. }
  12410. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12411. var subMesh = _a[_i];
  12412. subMesh.setEffect(null);
  12413. }
  12414. },
  12415. enumerable: true,
  12416. configurable: true
  12417. });
  12418. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12419. get: function () {
  12420. return this._receiveShadows;
  12421. },
  12422. set: function (value) {
  12423. if (this._receiveShadows === value) {
  12424. return;
  12425. }
  12426. this._receiveShadows = value;
  12427. this._markSubMeshesAsLightDirty();
  12428. },
  12429. enumerable: true,
  12430. configurable: true
  12431. });
  12432. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12433. get: function () {
  12434. return this._hasVertexAlpha;
  12435. },
  12436. set: function (value) {
  12437. if (this._hasVertexAlpha === value) {
  12438. return;
  12439. }
  12440. this._hasVertexAlpha = value;
  12441. this._markSubMeshesAsAttributesDirty();
  12442. },
  12443. enumerable: true,
  12444. configurable: true
  12445. });
  12446. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12447. get: function () {
  12448. return this._useVertexColors;
  12449. },
  12450. set: function (value) {
  12451. if (this._useVertexColors === value) {
  12452. return;
  12453. }
  12454. this._useVertexColors = value;
  12455. this._markSubMeshesAsAttributesDirty();
  12456. },
  12457. enumerable: true,
  12458. configurable: true
  12459. });
  12460. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12461. get: function () {
  12462. return this._computeBonesUsingShaders;
  12463. },
  12464. set: function (value) {
  12465. if (this._computeBonesUsingShaders === value) {
  12466. return;
  12467. }
  12468. this._computeBonesUsingShaders = value;
  12469. this._markSubMeshesAsAttributesDirty();
  12470. },
  12471. enumerable: true,
  12472. configurable: true
  12473. });
  12474. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12475. get: function () {
  12476. return this._numBoneInfluencers;
  12477. },
  12478. set: function (value) {
  12479. if (this._numBoneInfluencers === value) {
  12480. return;
  12481. }
  12482. this._numBoneInfluencers = value;
  12483. this._markSubMeshesAsAttributesDirty();
  12484. },
  12485. enumerable: true,
  12486. configurable: true
  12487. });
  12488. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12489. get: function () {
  12490. return this._applyFog;
  12491. },
  12492. set: function (value) {
  12493. if (this._applyFog === value) {
  12494. return;
  12495. }
  12496. this._applyFog = value;
  12497. this._markSubMeshesAsMiscDirty();
  12498. },
  12499. enumerable: true,
  12500. configurable: true
  12501. });
  12502. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12503. get: function () {
  12504. return this._layerMask;
  12505. },
  12506. set: function (value) {
  12507. if (value === this._layerMask) {
  12508. return;
  12509. }
  12510. this._layerMask = value;
  12511. this._resyncLightSources();
  12512. },
  12513. enumerable: true,
  12514. configurable: true
  12515. });
  12516. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12517. get: function () {
  12518. return this._collisionMask;
  12519. },
  12520. set: function (mask) {
  12521. this._collisionMask = !isNaN(mask) ? mask : -1;
  12522. },
  12523. enumerable: true,
  12524. configurable: true
  12525. });
  12526. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12527. get: function () {
  12528. return this._collisionGroup;
  12529. },
  12530. set: function (mask) {
  12531. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12532. },
  12533. enumerable: true,
  12534. configurable: true
  12535. });
  12536. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12537. get: function () {
  12538. return null;
  12539. },
  12540. enumerable: true,
  12541. configurable: true
  12542. });
  12543. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12544. get: function () {
  12545. return this._skeleton;
  12546. },
  12547. set: function (value) {
  12548. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12549. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12550. }
  12551. if (value && value.needInitialSkinMatrix) {
  12552. value._registerMeshWithPoseMatrix(this);
  12553. }
  12554. this._skeleton = value;
  12555. if (!this._skeleton) {
  12556. this._bonesTransformMatrices = null;
  12557. }
  12558. this._markSubMeshesAsAttributesDirty();
  12559. },
  12560. enumerable: true,
  12561. configurable: true
  12562. });
  12563. /**
  12564. * Boolean : true if the mesh has been disposed.
  12565. */
  12566. AbstractMesh.prototype.isDisposed = function () {
  12567. return this._isDisposed;
  12568. };
  12569. /**
  12570. * Returns the string "AbstractMesh"
  12571. */
  12572. AbstractMesh.prototype.getClassName = function () {
  12573. return "AbstractMesh";
  12574. };
  12575. /**
  12576. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12577. */
  12578. AbstractMesh.prototype.toString = function (fullDetails) {
  12579. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12580. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12581. if (this._skeleton) {
  12582. ret += ", skeleton: " + this._skeleton.name;
  12583. }
  12584. if (fullDetails) {
  12585. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12586. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12587. }
  12588. return ret;
  12589. };
  12590. AbstractMesh.prototype._rebuild = function () {
  12591. if (this._occlusionQuery) {
  12592. this._occlusionQuery = null;
  12593. }
  12594. if (this._edgesRenderer) {
  12595. this._edgesRenderer._rebuild();
  12596. }
  12597. if (!this.subMeshes) {
  12598. return;
  12599. }
  12600. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12601. var subMesh = _a[_i];
  12602. subMesh._rebuild();
  12603. }
  12604. };
  12605. AbstractMesh.prototype._resyncLightSources = function () {
  12606. this._lightSources.length = 0;
  12607. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12608. var light = _a[_i];
  12609. if (!light.isEnabled()) {
  12610. continue;
  12611. }
  12612. if (light.canAffectMesh(this)) {
  12613. this._lightSources.push(light);
  12614. }
  12615. }
  12616. this._markSubMeshesAsLightDirty();
  12617. };
  12618. AbstractMesh.prototype._resyncLighSource = function (light) {
  12619. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12620. var index = this._lightSources.indexOf(light);
  12621. if (index === -1) {
  12622. if (!isIn) {
  12623. return;
  12624. }
  12625. this._lightSources.push(light);
  12626. }
  12627. else {
  12628. if (isIn) {
  12629. return;
  12630. }
  12631. this._lightSources.splice(index, 1);
  12632. }
  12633. this._markSubMeshesAsLightDirty();
  12634. };
  12635. AbstractMesh.prototype._removeLightSource = function (light) {
  12636. var index = this._lightSources.indexOf(light);
  12637. if (index === -1) {
  12638. return;
  12639. }
  12640. this._lightSources.splice(index, 1);
  12641. };
  12642. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12643. if (!this.subMeshes) {
  12644. return;
  12645. }
  12646. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12647. var subMesh = _a[_i];
  12648. if (subMesh._materialDefines) {
  12649. func(subMesh._materialDefines);
  12650. }
  12651. }
  12652. };
  12653. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12654. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12655. };
  12656. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12657. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12658. };
  12659. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12660. if (!this.subMeshes) {
  12661. return;
  12662. }
  12663. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12664. var subMesh = _a[_i];
  12665. var material = subMesh.getMaterial();
  12666. if (material) {
  12667. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12668. }
  12669. }
  12670. };
  12671. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12672. /**
  12673. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12674. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12675. * Default : (0.0, 0.0, 0.0)
  12676. */
  12677. get: function () {
  12678. return this._rotation;
  12679. },
  12680. set: function (newRotation) {
  12681. this._rotation = newRotation;
  12682. },
  12683. enumerable: true,
  12684. configurable: true
  12685. });
  12686. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12687. /**
  12688. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12689. * Default : (1.0, 1.0, 1.0)
  12690. */
  12691. get: function () {
  12692. return this._scaling;
  12693. },
  12694. set: function (newScaling) {
  12695. this._scaling = newScaling;
  12696. if (this.physicsImpostor) {
  12697. this.physicsImpostor.forceUpdate();
  12698. }
  12699. },
  12700. enumerable: true,
  12701. configurable: true
  12702. });
  12703. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12704. /**
  12705. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12706. * It's null by default.
  12707. * 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)
  12708. */
  12709. get: function () {
  12710. return this._rotationQuaternion;
  12711. },
  12712. set: function (quaternion) {
  12713. this._rotationQuaternion = quaternion;
  12714. //reset the rotation vector.
  12715. if (quaternion && this.rotation.length()) {
  12716. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12717. }
  12718. },
  12719. enumerable: true,
  12720. configurable: true
  12721. });
  12722. // Methods
  12723. /**
  12724. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12725. * Returns the AbstractMesh.
  12726. */
  12727. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12728. this._poseMatrix.copyFrom(matrix);
  12729. return this;
  12730. };
  12731. /**
  12732. * Returns the mesh Pose matrix.
  12733. * Returned object : Matrix
  12734. */
  12735. AbstractMesh.prototype.getPoseMatrix = function () {
  12736. return this._poseMatrix;
  12737. };
  12738. /**
  12739. * Disables the mesh edger rendering mode.
  12740. * Returns the AbstractMesh.
  12741. */
  12742. AbstractMesh.prototype.disableEdgesRendering = function () {
  12743. if (this._edgesRenderer !== undefined) {
  12744. this._edgesRenderer.dispose();
  12745. this._edgesRenderer = undefined;
  12746. }
  12747. return this;
  12748. };
  12749. /**
  12750. * Enables the edge rendering mode on the mesh.
  12751. * This mode makes the mesh edges visible.
  12752. * Returns the AbstractMesh.
  12753. */
  12754. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12755. if (epsilon === void 0) { epsilon = 0.95; }
  12756. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12757. this.disableEdgesRendering();
  12758. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12759. return this;
  12760. };
  12761. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12762. /**
  12763. * Returns true if the mesh is blocked. Used by the class Mesh.
  12764. * Returns the boolean `false` by default.
  12765. */
  12766. get: function () {
  12767. return false;
  12768. },
  12769. enumerable: true,
  12770. configurable: true
  12771. });
  12772. /**
  12773. * Returns the mesh itself by default, used by the class Mesh.
  12774. * Returned type : AbstractMesh
  12775. */
  12776. AbstractMesh.prototype.getLOD = function (camera) {
  12777. return this;
  12778. };
  12779. /**
  12780. * Returns 0 by default, used by the class Mesh.
  12781. * Returns an integer.
  12782. */
  12783. AbstractMesh.prototype.getTotalVertices = function () {
  12784. return 0;
  12785. };
  12786. /**
  12787. * Returns null by default, used by the class Mesh.
  12788. * Returned type : integer array
  12789. */
  12790. AbstractMesh.prototype.getIndices = function () {
  12791. return null;
  12792. };
  12793. /**
  12794. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12795. * Returned type : float array or Float32Array
  12796. */
  12797. AbstractMesh.prototype.getVerticesData = function (kind) {
  12798. return null;
  12799. };
  12800. /**
  12801. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12802. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12803. * The `data` are either a numeric array either a Float32Array.
  12804. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12805. * 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).
  12806. * Note that a new underlying VertexBuffer object is created each call.
  12807. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12808. *
  12809. * Possible `kind` values :
  12810. * - BABYLON.VertexBuffer.PositionKind
  12811. * - BABYLON.VertexBuffer.UVKind
  12812. * - BABYLON.VertexBuffer.UV2Kind
  12813. * - BABYLON.VertexBuffer.UV3Kind
  12814. * - BABYLON.VertexBuffer.UV4Kind
  12815. * - BABYLON.VertexBuffer.UV5Kind
  12816. * - BABYLON.VertexBuffer.UV6Kind
  12817. * - BABYLON.VertexBuffer.ColorKind
  12818. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12819. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12820. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12821. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12822. *
  12823. * Returns the Mesh.
  12824. */
  12825. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12826. return null;
  12827. };
  12828. /**
  12829. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12830. * If the mesh has no geometry, it is simply returned as it is.
  12831. * The `data` are either a numeric array either a Float32Array.
  12832. * No new underlying VertexBuffer object is created.
  12833. * 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.
  12834. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12835. *
  12836. * Possible `kind` values :
  12837. * - BABYLON.VertexBuffer.PositionKind
  12838. * - BABYLON.VertexBuffer.UVKind
  12839. * - BABYLON.VertexBuffer.UV2Kind
  12840. * - BABYLON.VertexBuffer.UV3Kind
  12841. * - BABYLON.VertexBuffer.UV4Kind
  12842. * - BABYLON.VertexBuffer.UV5Kind
  12843. * - BABYLON.VertexBuffer.UV6Kind
  12844. * - BABYLON.VertexBuffer.ColorKind
  12845. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12846. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12847. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12848. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12849. *
  12850. * Returns the Mesh.
  12851. */
  12852. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12853. return null;
  12854. };
  12855. /**
  12856. * Sets the mesh indices.
  12857. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12858. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12859. * This method creates a new index buffer each call.
  12860. * Returns the Mesh.
  12861. */
  12862. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12863. return null;
  12864. };
  12865. /** Returns false by default, used by the class Mesh.
  12866. * Returns a boolean
  12867. */
  12868. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12869. return false;
  12870. };
  12871. /**
  12872. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12873. * Returns a BoundingInfo
  12874. */
  12875. AbstractMesh.prototype.getBoundingInfo = function () {
  12876. if (this._masterMesh) {
  12877. return this._masterMesh.getBoundingInfo();
  12878. }
  12879. if (!this._boundingInfo) {
  12880. this._updateBoundingInfo();
  12881. }
  12882. return this._boundingInfo;
  12883. };
  12884. /**
  12885. * Sets a mesh new object BoundingInfo.
  12886. * Returns the AbstractMesh.
  12887. */
  12888. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12889. this._boundingInfo = boundingInfo;
  12890. return this;
  12891. };
  12892. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12893. get: function () {
  12894. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12895. },
  12896. enumerable: true,
  12897. configurable: true
  12898. });
  12899. AbstractMesh.prototype._preActivate = function () {
  12900. };
  12901. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12902. };
  12903. AbstractMesh.prototype._activate = function (renderId) {
  12904. this._renderId = renderId;
  12905. };
  12906. /**
  12907. * Returns the last update of the World matrix
  12908. * Returns a Matrix.
  12909. */
  12910. AbstractMesh.prototype.getWorldMatrix = function () {
  12911. if (this._masterMesh) {
  12912. return this._masterMesh.getWorldMatrix();
  12913. }
  12914. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12915. this.computeWorldMatrix();
  12916. }
  12917. return this._worldMatrix;
  12918. };
  12919. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12920. /**
  12921. * Returns directly the last state of the mesh World matrix.
  12922. * A Matrix is returned.
  12923. */
  12924. get: function () {
  12925. return this._worldMatrix;
  12926. },
  12927. enumerable: true,
  12928. configurable: true
  12929. });
  12930. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12931. /**
  12932. * Returns the current mesh absolute position.
  12933. * Retuns a Vector3.
  12934. */
  12935. get: function () {
  12936. return this._absolutePosition;
  12937. },
  12938. enumerable: true,
  12939. configurable: true
  12940. });
  12941. /**
  12942. * Prevents the World matrix to be computed any longer.
  12943. * Returns the AbstractMesh.
  12944. */
  12945. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12946. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12947. this.computeWorldMatrix(true);
  12948. this._isWorldMatrixFrozen = true;
  12949. return this;
  12950. };
  12951. /**
  12952. * Allows back the World matrix computation.
  12953. * Returns the AbstractMesh.
  12954. */
  12955. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12956. this._isWorldMatrixFrozen = false;
  12957. this.computeWorldMatrix(true);
  12958. return this;
  12959. };
  12960. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12961. /**
  12962. * True if the World matrix has been frozen.
  12963. * Returns a boolean.
  12964. */
  12965. get: function () {
  12966. return this._isWorldMatrixFrozen;
  12967. },
  12968. enumerable: true,
  12969. configurable: true
  12970. });
  12971. /**
  12972. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12973. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12974. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12975. * The passed axis is also normalized.
  12976. * Returns the AbstractMesh.
  12977. */
  12978. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12979. axis.normalize();
  12980. if (!this.rotationQuaternion) {
  12981. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12982. this.rotation = BABYLON.Vector3.Zero();
  12983. }
  12984. var rotationQuaternion;
  12985. if (!space || space === BABYLON.Space.LOCAL) {
  12986. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12987. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12988. }
  12989. else {
  12990. if (this.parent) {
  12991. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12992. invertParentWorldMatrix.invert();
  12993. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12994. }
  12995. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12996. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12997. }
  12998. return this;
  12999. };
  13000. /**
  13001. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13002. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13003. * The passed axis is also normalized.
  13004. * Returns the AbstractMesh.
  13005. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13006. */
  13007. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13008. axis.normalize();
  13009. if (!this.rotationQuaternion) {
  13010. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13011. this.rotation.copyFromFloats(0, 0, 0);
  13012. }
  13013. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13014. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13015. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13016. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13017. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13018. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13019. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13020. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13021. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13022. return this;
  13023. };
  13024. /**
  13025. * Translates the mesh along the axis vector for the passed distance in the given space.
  13026. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13027. * Returns the AbstractMesh.
  13028. */
  13029. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13030. var displacementVector = axis.scale(distance);
  13031. if (!space || space === BABYLON.Space.LOCAL) {
  13032. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13033. this.setPositionWithLocalVector(tempV3);
  13034. }
  13035. else {
  13036. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13037. }
  13038. return this;
  13039. };
  13040. /**
  13041. * Adds a rotation step to the mesh current rotation.
  13042. * x, y, z are Euler angles expressed in radians.
  13043. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13044. * This means this rotation is made in the mesh local space only.
  13045. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13046. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13047. * ```javascript
  13048. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13049. * ```
  13050. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13051. * 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.
  13052. * Returns the AbstractMesh.
  13053. */
  13054. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13055. var rotationQuaternion;
  13056. if (this.rotationQuaternion) {
  13057. rotationQuaternion = this.rotationQuaternion;
  13058. }
  13059. else {
  13060. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13061. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13062. }
  13063. var accumulation = BABYLON.Tmp.Quaternion[0];
  13064. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13065. rotationQuaternion.multiplyInPlace(accumulation);
  13066. if (!this.rotationQuaternion) {
  13067. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13068. }
  13069. return this;
  13070. };
  13071. /**
  13072. * Retuns the mesh absolute position in the World.
  13073. * Returns a Vector3.
  13074. */
  13075. AbstractMesh.prototype.getAbsolutePosition = function () {
  13076. this.computeWorldMatrix();
  13077. return this._absolutePosition;
  13078. };
  13079. /**
  13080. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13081. * Returns the AbstractMesh.
  13082. */
  13083. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13084. if (!absolutePosition) {
  13085. return;
  13086. }
  13087. var absolutePositionX;
  13088. var absolutePositionY;
  13089. var absolutePositionZ;
  13090. if (absolutePosition.x === undefined) {
  13091. if (arguments.length < 3) {
  13092. return;
  13093. }
  13094. absolutePositionX = arguments[0];
  13095. absolutePositionY = arguments[1];
  13096. absolutePositionZ = arguments[2];
  13097. }
  13098. else {
  13099. absolutePositionX = absolutePosition.x;
  13100. absolutePositionY = absolutePosition.y;
  13101. absolutePositionZ = absolutePosition.z;
  13102. }
  13103. if (this.parent) {
  13104. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13105. invertParentWorldMatrix.invert();
  13106. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13107. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13108. }
  13109. else {
  13110. this.position.x = absolutePositionX;
  13111. this.position.y = absolutePositionY;
  13112. this.position.z = absolutePositionZ;
  13113. }
  13114. return this;
  13115. };
  13116. // ================================== Point of View Movement =================================
  13117. /**
  13118. * Perform relative position change from the point of view of behind the front of the mesh.
  13119. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13120. * Supports definition of mesh facing forward or backward.
  13121. * @param {number} amountRight
  13122. * @param {number} amountUp
  13123. * @param {number} amountForward
  13124. *
  13125. * Returns the AbstractMesh.
  13126. */
  13127. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13128. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13129. return this;
  13130. };
  13131. /**
  13132. * Calculate relative position change from the point of view of behind the front of the mesh.
  13133. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13134. * Supports definition of mesh facing forward or backward.
  13135. * @param {number} amountRight
  13136. * @param {number} amountUp
  13137. * @param {number} amountForward
  13138. *
  13139. * Returns a new Vector3.
  13140. */
  13141. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13142. var rotMatrix = new BABYLON.Matrix();
  13143. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13144. rotQuaternion.toRotationMatrix(rotMatrix);
  13145. var translationDelta = BABYLON.Vector3.Zero();
  13146. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13147. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13148. return translationDelta;
  13149. };
  13150. // ================================== Point of View Rotation =================================
  13151. /**
  13152. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13153. * Supports definition of mesh facing forward or backward.
  13154. * @param {number} flipBack
  13155. * @param {number} twirlClockwise
  13156. * @param {number} tiltRight
  13157. *
  13158. * Returns the AbstractMesh.
  13159. */
  13160. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13161. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13162. return this;
  13163. };
  13164. /**
  13165. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13166. * Supports definition of mesh facing forward or backward.
  13167. * @param {number} flipBack
  13168. * @param {number} twirlClockwise
  13169. * @param {number} tiltRight
  13170. *
  13171. * Returns a new Vector3.
  13172. */
  13173. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13174. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13175. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13176. };
  13177. /**
  13178. * Sets a new pivot matrix to the mesh.
  13179. * Returns the AbstractMesh.
  13180. */
  13181. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  13182. this._pivotMatrix = matrix;
  13183. this._cache.pivotMatrixUpdated = true;
  13184. return this;
  13185. };
  13186. /**
  13187. * Returns the mesh pivot matrix.
  13188. * Default : Identity.
  13189. * A Matrix is returned.
  13190. */
  13191. AbstractMesh.prototype.getPivotMatrix = function () {
  13192. return this._pivotMatrix;
  13193. };
  13194. AbstractMesh.prototype._isSynchronized = function () {
  13195. if (this._isDirty) {
  13196. return false;
  13197. }
  13198. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13199. return false;
  13200. if (this._cache.pivotMatrixUpdated) {
  13201. return false;
  13202. }
  13203. if (this.infiniteDistance) {
  13204. return false;
  13205. }
  13206. if (!this._cache.position.equals(this.position))
  13207. return false;
  13208. if (this.rotationQuaternion) {
  13209. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13210. return false;
  13211. }
  13212. if (!this._cache.rotation.equals(this.rotation))
  13213. return false;
  13214. if (!this._cache.scaling.equals(this.scaling))
  13215. return false;
  13216. return true;
  13217. };
  13218. AbstractMesh.prototype._initCache = function () {
  13219. _super.prototype._initCache.call(this);
  13220. this._cache.localMatrixUpdated = false;
  13221. this._cache.position = BABYLON.Vector3.Zero();
  13222. this._cache.scaling = BABYLON.Vector3.Zero();
  13223. this._cache.rotation = BABYLON.Vector3.Zero();
  13224. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13225. this._cache.billboardMode = -1;
  13226. };
  13227. AbstractMesh.prototype.markAsDirty = function (property) {
  13228. if (property === "rotation") {
  13229. this.rotationQuaternion = null;
  13230. }
  13231. this._currentRenderId = Number.MAX_VALUE;
  13232. this._isDirty = true;
  13233. return this;
  13234. };
  13235. /**
  13236. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13237. */
  13238. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13239. this.computeWorldMatrix(true);
  13240. var min;
  13241. var max;
  13242. if (!this.subMeshes) {
  13243. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13244. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13245. }
  13246. else {
  13247. min = this.getBoundingInfo().boundingBox.minimumWorld;
  13248. max = this.getBoundingInfo().boundingBox.maximumWorld;
  13249. }
  13250. var descendants = this.getDescendants(false);
  13251. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13252. var descendant = descendants_1[_i];
  13253. var childMesh = descendant;
  13254. childMesh.computeWorldMatrix(true);
  13255. if (childMesh.getTotalVertices() === 0) {
  13256. continue;
  13257. }
  13258. var boundingBox = childMesh.getBoundingInfo().boundingBox;
  13259. var minBox = boundingBox.minimumWorld;
  13260. var maxBox = boundingBox.maximumWorld;
  13261. BABYLON.Tools.CheckExtends(minBox, min, max);
  13262. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13263. }
  13264. return {
  13265. min: min,
  13266. max: max
  13267. };
  13268. };
  13269. /**
  13270. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13271. * Returns the AbstractMesh.
  13272. */
  13273. AbstractMesh.prototype._updateBoundingInfo = function () {
  13274. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13275. this._boundingInfo.update(this.worldMatrixFromCache);
  13276. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13277. return this;
  13278. };
  13279. /**
  13280. * Update a mesh's children BoundingInfo objects only.
  13281. * Returns the AbstractMesh.
  13282. */
  13283. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13284. if (!this.subMeshes) {
  13285. return;
  13286. }
  13287. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13288. var subMesh = this.subMeshes[subIndex];
  13289. if (!subMesh.IsGlobal) {
  13290. subMesh.updateBoundingInfo(matrix);
  13291. }
  13292. }
  13293. return this;
  13294. };
  13295. /**
  13296. * Computes the mesh World matrix and returns it.
  13297. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13298. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13299. * If the parameter `force`is set to `true`, the actual computation is done.
  13300. * Returns the mesh World Matrix.
  13301. */
  13302. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13303. if (this._isWorldMatrixFrozen) {
  13304. return this._worldMatrix;
  13305. }
  13306. if (!force && this.isSynchronized(true)) {
  13307. this._currentRenderId = this.getScene().getRenderId();
  13308. return this._worldMatrix;
  13309. }
  13310. this._cache.position.copyFrom(this.position);
  13311. this._cache.scaling.copyFrom(this.scaling);
  13312. this._cache.pivotMatrixUpdated = false;
  13313. this._cache.billboardMode = this.billboardMode;
  13314. this._currentRenderId = this.getScene().getRenderId();
  13315. this._isDirty = false;
  13316. // Scaling
  13317. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13318. // Rotation
  13319. //rotate, if quaternion is set and rotation was used
  13320. if (this.rotationQuaternion) {
  13321. var len = this.rotation.length();
  13322. if (len) {
  13323. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13324. this.rotation.copyFromFloats(0, 0, 0);
  13325. }
  13326. }
  13327. if (this.rotationQuaternion) {
  13328. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13329. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13330. }
  13331. else {
  13332. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13333. this._cache.rotation.copyFrom(this.rotation);
  13334. }
  13335. // Translation
  13336. if (this.infiniteDistance && !this.parent) {
  13337. var camera = this.getScene().activeCamera;
  13338. if (camera) {
  13339. var cameraWorldMatrix = camera.getWorldMatrix();
  13340. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13341. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13342. }
  13343. }
  13344. else {
  13345. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13346. }
  13347. // Composing transformations
  13348. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13349. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13350. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13351. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13352. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13353. // Need to decompose each rotation here
  13354. var currentPosition = BABYLON.Tmp.Vector3[3];
  13355. if (this.parent && this.parent.getWorldMatrix) {
  13356. if (this._meshToBoneReferal) {
  13357. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13358. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13359. }
  13360. else {
  13361. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13362. }
  13363. }
  13364. else {
  13365. currentPosition.copyFrom(this.position);
  13366. }
  13367. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13368. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13369. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13370. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13371. }
  13372. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13373. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13374. }
  13375. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13376. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13377. }
  13378. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13379. }
  13380. else {
  13381. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13382. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13383. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13384. }
  13385. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13386. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13387. }
  13388. // Local world
  13389. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13390. // Parent
  13391. if (this.parent && this.parent.getWorldMatrix) {
  13392. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13393. if (this._meshToBoneReferal) {
  13394. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13395. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13396. }
  13397. else {
  13398. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13399. }
  13400. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13401. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13402. this._worldMatrix.copyFrom(this._localWorld);
  13403. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13404. }
  13405. else {
  13406. if (this._meshToBoneReferal) {
  13407. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13408. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13409. }
  13410. else {
  13411. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13412. }
  13413. }
  13414. this._markSyncedWithParent();
  13415. }
  13416. else {
  13417. this._worldMatrix.copyFrom(this._localWorld);
  13418. }
  13419. // Bounding info
  13420. this._updateBoundingInfo();
  13421. // Absolute position
  13422. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13423. // Callbacks
  13424. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13425. if (!this._poseMatrix) {
  13426. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13427. }
  13428. return this._worldMatrix;
  13429. };
  13430. /**
  13431. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13432. * @param func: callback function to add
  13433. *
  13434. * Returns the AbstractMesh.
  13435. */
  13436. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13437. this.onAfterWorldMatrixUpdateObservable.add(func);
  13438. return this;
  13439. };
  13440. /**
  13441. * Removes a registered callback function.
  13442. * Returns the AbstractMesh.
  13443. */
  13444. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13445. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13446. return this;
  13447. };
  13448. /**
  13449. * Sets the mesh position in its local space.
  13450. * Returns the AbstractMesh.
  13451. */
  13452. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13453. this.computeWorldMatrix();
  13454. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13455. return this;
  13456. };
  13457. /**
  13458. * Returns the mesh position in the local space from the current World matrix values.
  13459. * Returns a new Vector3.
  13460. */
  13461. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13462. this.computeWorldMatrix();
  13463. var invLocalWorldMatrix = this._localWorld.clone();
  13464. invLocalWorldMatrix.invert();
  13465. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13466. };
  13467. /**
  13468. * Translates the mesh along the passed Vector3 in its local space.
  13469. * Returns the AbstractMesh.
  13470. */
  13471. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13472. this.computeWorldMatrix(true);
  13473. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13474. return this;
  13475. };
  13476. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13477. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13478. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13479. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13480. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13481. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13482. /// <returns>Mesh oriented towards targetMesh</returns>
  13483. if (yawCor === void 0) { yawCor = 0; }
  13484. if (pitchCor === void 0) { pitchCor = 0; }
  13485. if (rollCor === void 0) { rollCor = 0; }
  13486. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13487. var dv = AbstractMesh._lookAtVectorCache;
  13488. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13489. targetPoint.subtractToRef(pos, dv);
  13490. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13491. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13492. var pitch = Math.atan2(dv.y, len);
  13493. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13494. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13495. return this;
  13496. };
  13497. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13498. this._meshToBoneReferal = affectedMesh;
  13499. this.parent = bone;
  13500. if (bone.getWorldMatrix().determinant() < 0) {
  13501. this.scalingDeterminant *= -1;
  13502. }
  13503. return this;
  13504. };
  13505. AbstractMesh.prototype.detachFromBone = function () {
  13506. if (this.parent.getWorldMatrix().determinant() < 0) {
  13507. this.scalingDeterminant *= -1;
  13508. }
  13509. this._meshToBoneReferal = null;
  13510. this.parent = null;
  13511. return this;
  13512. };
  13513. /**
  13514. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13515. * A mesh is in the frustum if its bounding box intersects the frustum.
  13516. * Boolean returned.
  13517. */
  13518. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13519. return this._boundingInfo.isInFrustum(frustumPlanes);
  13520. };
  13521. /**
  13522. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13523. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13524. * Boolean returned.
  13525. */
  13526. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13527. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13528. ;
  13529. };
  13530. /**
  13531. * True if the mesh intersects another mesh or a SolidParticle object.
  13532. * 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)
  13533. * Returns a boolean.
  13534. */
  13535. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13536. if (!this._boundingInfo || !mesh._boundingInfo) {
  13537. return false;
  13538. }
  13539. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13540. };
  13541. /**
  13542. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13543. * Returns a boolean.
  13544. */
  13545. AbstractMesh.prototype.intersectsPoint = function (point) {
  13546. if (!this._boundingInfo) {
  13547. return false;
  13548. }
  13549. return this._boundingInfo.intersectsPoint(point);
  13550. };
  13551. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13552. return this.physicsImpostor;
  13553. };
  13554. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13555. if (!camera) {
  13556. camera = this.getScene().activeCamera;
  13557. }
  13558. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13559. };
  13560. /**
  13561. * Returns the distance from the mesh to the active camera.
  13562. * Returns a float.
  13563. */
  13564. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13565. if (!camera) {
  13566. camera = this.getScene().activeCamera;
  13567. }
  13568. return this.absolutePosition.subtract(camera.position).length();
  13569. };
  13570. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13571. if (!this.physicsImpostor) {
  13572. return;
  13573. }
  13574. this.physicsImpostor.applyImpulse(force, contactPoint);
  13575. return this;
  13576. };
  13577. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13578. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13579. return;
  13580. }
  13581. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13582. mainPivot: pivot1,
  13583. connectedPivot: pivot2,
  13584. nativeParams: options
  13585. });
  13586. return this;
  13587. };
  13588. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13589. // Collisions
  13590. /**
  13591. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13592. * Default `false`.
  13593. */
  13594. get: function () {
  13595. return this._checkCollisions;
  13596. },
  13597. set: function (collisionEnabled) {
  13598. this._checkCollisions = collisionEnabled;
  13599. if (this.getScene().workerCollisions) {
  13600. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13601. }
  13602. },
  13603. enumerable: true,
  13604. configurable: true
  13605. });
  13606. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  13607. var globalPosition = this.getAbsolutePosition();
  13608. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13609. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13610. if (!this._collider) {
  13611. this._collider = new BABYLON.Collider();
  13612. }
  13613. this._collider.radius = this.ellipsoid;
  13614. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13615. return this;
  13616. };
  13617. // Submeshes octree
  13618. /**
  13619. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13620. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13621. * Returns an Octree of submeshes.
  13622. */
  13623. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13624. if (maxCapacity === void 0) { maxCapacity = 64; }
  13625. if (maxDepth === void 0) { maxDepth = 2; }
  13626. if (!this._submeshesOctree) {
  13627. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13628. }
  13629. this.computeWorldMatrix(true);
  13630. // Update octree
  13631. var bbox = this.getBoundingInfo().boundingBox;
  13632. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13633. return this._submeshesOctree;
  13634. };
  13635. // Collisions
  13636. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13637. this._generatePointsArray();
  13638. // Transformation
  13639. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13640. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13641. subMesh._lastColliderWorldVertices = [];
  13642. subMesh._trianglePlanes = [];
  13643. var start = subMesh.verticesStart;
  13644. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13645. for (var i = start; i < end; i++) {
  13646. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13647. }
  13648. }
  13649. // Collide
  13650. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13651. if (collider.collisionFound) {
  13652. collider.collidedMesh = this;
  13653. }
  13654. return this;
  13655. };
  13656. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13657. var subMeshes;
  13658. var len;
  13659. // Octrees
  13660. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13661. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13662. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13663. len = intersections.length;
  13664. subMeshes = intersections.data;
  13665. }
  13666. else {
  13667. subMeshes = this.subMeshes;
  13668. len = subMeshes.length;
  13669. }
  13670. for (var index = 0; index < len; index++) {
  13671. var subMesh = subMeshes[index];
  13672. // Bounding test
  13673. if (len > 1 && !subMesh._checkCollision(collider))
  13674. continue;
  13675. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13676. }
  13677. return this;
  13678. };
  13679. AbstractMesh.prototype._checkCollision = function (collider) {
  13680. // Bounding box test
  13681. if (!this._boundingInfo._checkCollision(collider))
  13682. return this;
  13683. // Transformation matrix
  13684. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13685. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13686. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13687. return this;
  13688. };
  13689. // Picking
  13690. AbstractMesh.prototype._generatePointsArray = function () {
  13691. return false;
  13692. };
  13693. /**
  13694. * Checks if the passed Ray intersects with the mesh.
  13695. * Returns an object PickingInfo.
  13696. */
  13697. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13698. var pickingInfo = new BABYLON.PickingInfo();
  13699. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13700. return pickingInfo;
  13701. }
  13702. if (!this._generatePointsArray()) {
  13703. return pickingInfo;
  13704. }
  13705. var intersectInfo = null;
  13706. // Octrees
  13707. var subMeshes;
  13708. var len;
  13709. if (this._submeshesOctree && this.useOctreeForPicking) {
  13710. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13711. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13712. len = intersections.length;
  13713. subMeshes = intersections.data;
  13714. }
  13715. else {
  13716. subMeshes = this.subMeshes;
  13717. len = subMeshes.length;
  13718. }
  13719. for (var index = 0; index < len; index++) {
  13720. var subMesh = subMeshes[index];
  13721. // Bounding test
  13722. if (len > 1 && !subMesh.canIntersects(ray))
  13723. continue;
  13724. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13725. if (currentIntersectInfo) {
  13726. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13727. intersectInfo = currentIntersectInfo;
  13728. intersectInfo.subMeshId = index;
  13729. if (fastCheck) {
  13730. break;
  13731. }
  13732. }
  13733. }
  13734. }
  13735. if (intersectInfo) {
  13736. // Get picked point
  13737. var world = this.getWorldMatrix();
  13738. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13739. var direction = ray.direction.clone();
  13740. direction = direction.scale(intersectInfo.distance);
  13741. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13742. var pickedPoint = worldOrigin.add(worldDirection);
  13743. // Return result
  13744. pickingInfo.hit = true;
  13745. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13746. pickingInfo.pickedPoint = pickedPoint;
  13747. pickingInfo.pickedMesh = this;
  13748. pickingInfo.bu = intersectInfo.bu;
  13749. pickingInfo.bv = intersectInfo.bv;
  13750. pickingInfo.faceId = intersectInfo.faceId;
  13751. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13752. return pickingInfo;
  13753. }
  13754. return pickingInfo;
  13755. };
  13756. /**
  13757. * Clones the mesh, used by the class Mesh.
  13758. * Just returns `null` for an AbstractMesh.
  13759. */
  13760. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13761. return null;
  13762. };
  13763. /**
  13764. * Disposes all the mesh submeshes.
  13765. * Returns the AbstractMesh.
  13766. */
  13767. AbstractMesh.prototype.releaseSubMeshes = function () {
  13768. if (this.subMeshes) {
  13769. while (this.subMeshes.length) {
  13770. this.subMeshes[0].dispose();
  13771. }
  13772. }
  13773. else {
  13774. this.subMeshes = new Array();
  13775. }
  13776. return this;
  13777. };
  13778. /**
  13779. * Disposes the AbstractMesh.
  13780. * Some internal references are kept for further use.
  13781. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13782. * Returns nothing.
  13783. */
  13784. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13785. var _this = this;
  13786. var index;
  13787. // Action manager
  13788. if (this.actionManager) {
  13789. this.actionManager.dispose();
  13790. this.actionManager = null;
  13791. }
  13792. // Skeleton
  13793. this.skeleton = null;
  13794. // Animations
  13795. this.getScene().stopAnimation(this);
  13796. // Physics
  13797. if (this.physicsImpostor) {
  13798. this.physicsImpostor.dispose();
  13799. }
  13800. // Intersections in progress
  13801. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13802. var other = this._intersectionsInProgress[index];
  13803. var pos = other._intersectionsInProgress.indexOf(this);
  13804. other._intersectionsInProgress.splice(pos, 1);
  13805. }
  13806. this._intersectionsInProgress = [];
  13807. // Lights
  13808. var lights = this.getScene().lights;
  13809. lights.forEach(function (light) {
  13810. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13811. if (meshIndex !== -1) {
  13812. light.includedOnlyMeshes.splice(meshIndex, 1);
  13813. }
  13814. meshIndex = light.excludedMeshes.indexOf(_this);
  13815. if (meshIndex !== -1) {
  13816. light.excludedMeshes.splice(meshIndex, 1);
  13817. }
  13818. // Shadow generators
  13819. var generator = light.getShadowGenerator();
  13820. if (generator) {
  13821. var shadowMap = generator.getShadowMap();
  13822. meshIndex = shadowMap.renderList.indexOf(_this);
  13823. if (meshIndex !== -1) {
  13824. shadowMap.renderList.splice(meshIndex, 1);
  13825. }
  13826. }
  13827. });
  13828. // Edges
  13829. if (this._edgesRenderer) {
  13830. this._edgesRenderer.dispose();
  13831. this._edgesRenderer = null;
  13832. }
  13833. // SubMeshes
  13834. if (this.getClassName() !== "InstancedMesh") {
  13835. this.releaseSubMeshes();
  13836. }
  13837. // Octree
  13838. var sceneOctree = this.getScene().selectionOctree;
  13839. if (sceneOctree) {
  13840. var index = sceneOctree.dynamicContent.indexOf(this);
  13841. if (index !== -1) {
  13842. sceneOctree.dynamicContent.splice(index, 1);
  13843. }
  13844. }
  13845. // Query
  13846. var engine = this.getScene().getEngine();
  13847. if (this._occlusionQuery) {
  13848. this._isOcclusionQueryInProgress = false;
  13849. engine.deleteQuery(this._occlusionQuery);
  13850. this._occlusionQuery = null;
  13851. }
  13852. // Engine
  13853. engine.wipeCaches();
  13854. // Remove from scene
  13855. this.getScene().removeMesh(this);
  13856. if (!doNotRecurse) {
  13857. // Particles
  13858. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13859. if (this.getScene().particleSystems[index].emitter === this) {
  13860. this.getScene().particleSystems[index].dispose();
  13861. index--;
  13862. }
  13863. }
  13864. // Children
  13865. var objects = this.getDescendants(true);
  13866. for (index = 0; index < objects.length; index++) {
  13867. objects[index].dispose();
  13868. }
  13869. }
  13870. else {
  13871. var childMeshes = this.getChildMeshes(true);
  13872. for (index = 0; index < childMeshes.length; index++) {
  13873. var child = childMeshes[index];
  13874. child.parent = null;
  13875. child.computeWorldMatrix(true);
  13876. }
  13877. }
  13878. // facet data
  13879. if (this._facetDataEnabled) {
  13880. this.disableFacetData();
  13881. }
  13882. this.onAfterWorldMatrixUpdateObservable.clear();
  13883. this.onCollideObservable.clear();
  13884. this.onCollisionPositionChangeObservable.clear();
  13885. this._isDisposed = true;
  13886. _super.prototype.dispose.call(this);
  13887. };
  13888. /**
  13889. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13890. * This Vector3 is expressed in the World space.
  13891. */
  13892. AbstractMesh.prototype.getDirection = function (localAxis) {
  13893. var result = BABYLON.Vector3.Zero();
  13894. this.getDirectionToRef(localAxis, result);
  13895. return result;
  13896. };
  13897. /**
  13898. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13899. * localAxis is expressed in the mesh local space.
  13900. * result is computed in the Wordl space from the mesh World matrix.
  13901. * Returns the AbstractMesh.
  13902. */
  13903. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13904. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13905. return this;
  13906. };
  13907. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13908. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13909. if (this.getScene().getRenderId() == 0) {
  13910. this.computeWorldMatrix(true);
  13911. }
  13912. var wm = this.getWorldMatrix();
  13913. if (space == BABYLON.Space.WORLD) {
  13914. var tmat = BABYLON.Tmp.Matrix[0];
  13915. wm.invertToRef(tmat);
  13916. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13917. }
  13918. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13919. this._pivotMatrix.m[12] = -point.x;
  13920. this._pivotMatrix.m[13] = -point.y;
  13921. this._pivotMatrix.m[14] = -point.z;
  13922. this._cache.pivotMatrixUpdated = true;
  13923. return this;
  13924. };
  13925. /**
  13926. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13927. */
  13928. AbstractMesh.prototype.getPivotPoint = function () {
  13929. var point = BABYLON.Vector3.Zero();
  13930. this.getPivotPointToRef(point);
  13931. return point;
  13932. };
  13933. /**
  13934. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13935. * Returns the AbstractMesh.
  13936. */
  13937. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13938. result.x = -this._pivotMatrix.m[12];
  13939. result.y = -this._pivotMatrix.m[13];
  13940. result.z = -this._pivotMatrix.m[14];
  13941. return this;
  13942. };
  13943. /**
  13944. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13945. */
  13946. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13947. var point = BABYLON.Vector3.Zero();
  13948. this.getAbsolutePivotPointToRef(point);
  13949. return point;
  13950. };
  13951. /**
  13952. * Defines the passed mesh as the parent of the current mesh.
  13953. * Returns the AbstractMesh.
  13954. */
  13955. AbstractMesh.prototype.setParent = function (mesh) {
  13956. var child = this;
  13957. var parent = mesh;
  13958. if (mesh == null) {
  13959. var rotation = BABYLON.Tmp.Quaternion[0];
  13960. var position = BABYLON.Tmp.Vector3[0];
  13961. var scale = BABYLON.Tmp.Vector3[1];
  13962. child.getWorldMatrix().decompose(scale, rotation, position);
  13963. if (child.rotationQuaternion) {
  13964. child.rotationQuaternion.copyFrom(rotation);
  13965. }
  13966. else {
  13967. rotation.toEulerAnglesToRef(child.rotation);
  13968. }
  13969. child.position.x = position.x;
  13970. child.position.y = position.y;
  13971. child.position.z = position.z;
  13972. }
  13973. else {
  13974. var position = BABYLON.Tmp.Vector3[0];
  13975. var m1 = BABYLON.Tmp.Matrix[0];
  13976. parent.getWorldMatrix().invertToRef(m1);
  13977. BABYLON.Vector3.TransformCoordinatesToRef(child.position, m1, position);
  13978. child.position.copyFrom(position);
  13979. }
  13980. child.parent = parent;
  13981. return this;
  13982. };
  13983. /**
  13984. * Adds the passed mesh as a child to the current mesh.
  13985. * Returns the AbstractMesh.
  13986. */
  13987. AbstractMesh.prototype.addChild = function (mesh) {
  13988. mesh.setParent(this);
  13989. return this;
  13990. };
  13991. /**
  13992. * Removes the passed mesh from the current mesh children list.
  13993. * Returns the AbstractMesh.
  13994. */
  13995. AbstractMesh.prototype.removeChild = function (mesh) {
  13996. mesh.setParent(null);
  13997. return this;
  13998. };
  13999. /**
  14000. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14001. * Returns the AbstractMesh.
  14002. */
  14003. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14004. result.x = this._pivotMatrix.m[12];
  14005. result.y = this._pivotMatrix.m[13];
  14006. result.z = this._pivotMatrix.m[14];
  14007. this.getPivotPointToRef(result);
  14008. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14009. return this;
  14010. };
  14011. // Facet data
  14012. /**
  14013. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14014. * Returns the AbstractMesh.
  14015. */
  14016. AbstractMesh.prototype._initFacetData = function () {
  14017. if (!this._facetNormals) {
  14018. this._facetNormals = new Array();
  14019. }
  14020. if (!this._facetPositions) {
  14021. this._facetPositions = new Array();
  14022. }
  14023. if (!this._facetPartitioning) {
  14024. this._facetPartitioning = new Array();
  14025. }
  14026. this._facetNb = this.getIndices().length / 3;
  14027. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14028. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14029. for (var f = 0; f < this._facetNb; f++) {
  14030. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14031. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14032. }
  14033. this._facetDataEnabled = true;
  14034. return this;
  14035. };
  14036. /**
  14037. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14038. * This method can be called within the render loop.
  14039. * 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.
  14040. * Returns the AbstractMesh.
  14041. */
  14042. AbstractMesh.prototype.updateFacetData = function () {
  14043. if (!this._facetDataEnabled) {
  14044. this._initFacetData();
  14045. }
  14046. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14047. var indices = this.getIndices();
  14048. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14049. var bInfo = this.getBoundingInfo();
  14050. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14051. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14052. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14053. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14054. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14055. this._subDiv.max = this._partitioningSubdivisions;
  14056. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14057. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14058. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14059. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14060. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14061. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14062. // set the parameters for ComputeNormals()
  14063. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14064. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14065. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14066. this._facetParameters.bInfo = bInfo;
  14067. this._facetParameters.bbSize = this._bbSize;
  14068. this._facetParameters.subDiv = this._subDiv;
  14069. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14070. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14071. return this;
  14072. };
  14073. /**
  14074. * Returns the facetLocalNormals array.
  14075. * The normals are expressed in the mesh local space.
  14076. */
  14077. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14078. if (!this._facetNormals) {
  14079. this.updateFacetData();
  14080. }
  14081. return this._facetNormals;
  14082. };
  14083. /**
  14084. * Returns the facetLocalPositions array.
  14085. * The facet positions are expressed in the mesh local space.
  14086. */
  14087. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14088. if (!this._facetPositions) {
  14089. this.updateFacetData();
  14090. }
  14091. return this._facetPositions;
  14092. };
  14093. /**
  14094. * Returns the facetLocalPartioning array.
  14095. */
  14096. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14097. if (!this._facetPartitioning) {
  14098. this.updateFacetData();
  14099. }
  14100. return this._facetPartitioning;
  14101. };
  14102. /**
  14103. * Returns the i-th facet position in the world system.
  14104. * This method allocates a new Vector3 per call.
  14105. */
  14106. AbstractMesh.prototype.getFacetPosition = function (i) {
  14107. var pos = BABYLON.Vector3.Zero();
  14108. this.getFacetPositionToRef(i, pos);
  14109. return pos;
  14110. };
  14111. /**
  14112. * Sets the reference Vector3 with the i-th facet position in the world system.
  14113. * Returns the AbstractMesh.
  14114. */
  14115. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14116. var localPos = (this.getFacetLocalPositions())[i];
  14117. var world = this.getWorldMatrix();
  14118. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14119. return this;
  14120. };
  14121. /**
  14122. * Returns the i-th facet normal in the world system.
  14123. * This method allocates a new Vector3 per call.
  14124. */
  14125. AbstractMesh.prototype.getFacetNormal = function (i) {
  14126. var norm = BABYLON.Vector3.Zero();
  14127. this.getFacetNormalToRef(i, norm);
  14128. return norm;
  14129. };
  14130. /**
  14131. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14132. * Returns the AbstractMesh.
  14133. */
  14134. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14135. var localNorm = (this.getFacetLocalNormals())[i];
  14136. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14137. return this;
  14138. };
  14139. /**
  14140. * 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).
  14141. */
  14142. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14143. var bInfo = this.getBoundingInfo();
  14144. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14145. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14146. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14147. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14148. return null;
  14149. }
  14150. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14151. };
  14152. /**
  14153. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14154. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14155. * 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.
  14156. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14157. * 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.
  14158. */
  14159. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14160. if (checkFace === void 0) { checkFace = false; }
  14161. if (facing === void 0) { facing = true; }
  14162. var world = this.getWorldMatrix();
  14163. var invMat = BABYLON.Tmp.Matrix[5];
  14164. world.invertToRef(invMat);
  14165. var invVect = BABYLON.Tmp.Vector3[8];
  14166. var closest = null;
  14167. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14168. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14169. if (projected) {
  14170. // tranform the local computed projected vector to world coordinates
  14171. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14172. }
  14173. return closest;
  14174. };
  14175. /**
  14176. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14177. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14178. * 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.
  14179. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14180. * 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.
  14181. */
  14182. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14183. if (checkFace === void 0) { checkFace = false; }
  14184. if (facing === void 0) { facing = true; }
  14185. var closest = null;
  14186. var tmpx = 0.0;
  14187. var tmpy = 0.0;
  14188. var tmpz = 0.0;
  14189. var d = 0.0; // tmp dot facet normal * facet position
  14190. var t0 = 0.0;
  14191. var projx = 0.0;
  14192. var projy = 0.0;
  14193. var projz = 0.0;
  14194. // Get all the facets in the same partitioning block than (x, y, z)
  14195. var facetPositions = this.getFacetLocalPositions();
  14196. var facetNormals = this.getFacetLocalNormals();
  14197. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14198. if (!facetsInBlock) {
  14199. return null;
  14200. }
  14201. // Get the closest facet to (x, y, z)
  14202. var shortest = Number.MAX_VALUE; // init distance vars
  14203. var tmpDistance = shortest;
  14204. var fib; // current facet in the block
  14205. var norm; // current facet normal
  14206. var p0; // current facet barycenter position
  14207. // loop on all the facets in the current partitioning block
  14208. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14209. fib = facetsInBlock[idx];
  14210. norm = facetNormals[fib];
  14211. p0 = facetPositions[fib];
  14212. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14213. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14214. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14215. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14216. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14217. projx = x + norm.x * t0;
  14218. projy = y + norm.y * t0;
  14219. projz = z + norm.z * t0;
  14220. tmpx = projx - x;
  14221. tmpy = projy - y;
  14222. tmpz = projz - z;
  14223. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14224. if (tmpDistance < shortest) {
  14225. shortest = tmpDistance;
  14226. closest = fib;
  14227. if (projected) {
  14228. projected.x = projx;
  14229. projected.y = projy;
  14230. projected.z = projz;
  14231. }
  14232. }
  14233. }
  14234. }
  14235. return closest;
  14236. };
  14237. /**
  14238. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14239. */
  14240. AbstractMesh.prototype.getFacetDataParameters = function () {
  14241. return this._facetParameters;
  14242. };
  14243. /**
  14244. * Disables the feature FacetData and frees the related memory.
  14245. * Returns the AbstractMesh.
  14246. */
  14247. AbstractMesh.prototype.disableFacetData = function () {
  14248. if (this._facetDataEnabled) {
  14249. this._facetDataEnabled = false;
  14250. this._facetPositions = null;
  14251. this._facetNormals = null;
  14252. this._facetPartitioning = null;
  14253. this._facetParameters = null;
  14254. }
  14255. return this;
  14256. };
  14257. /**
  14258. * Creates new normals data for the mesh.
  14259. * @param updatable.
  14260. */
  14261. AbstractMesh.prototype.createNormals = function (updatable) {
  14262. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14263. var indices = this.getIndices();
  14264. var normals;
  14265. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14266. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14267. }
  14268. else {
  14269. normals = [];
  14270. }
  14271. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14272. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14273. };
  14274. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14275. var engine = this.getEngine();
  14276. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14277. this._isOccluded = false;
  14278. return;
  14279. }
  14280. if (this.isOcclusionQueryInProgress) {
  14281. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14282. if (isOcclusionQueryAvailable) {
  14283. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14284. this._isOcclusionQueryInProgress = false;
  14285. this._occlusionInternalRetryCounter = 0;
  14286. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14287. }
  14288. else {
  14289. this._occlusionInternalRetryCounter++;
  14290. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14291. this._isOcclusionQueryInProgress = false;
  14292. this._occlusionInternalRetryCounter = 0;
  14293. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14294. // if strict continue the last state of the object.
  14295. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14296. }
  14297. else {
  14298. return;
  14299. }
  14300. }
  14301. }
  14302. var scene = this.getScene();
  14303. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14304. if (!this._occlusionQuery) {
  14305. this._occlusionQuery = engine.createQuery();
  14306. }
  14307. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14308. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14309. engine.endQuery(this.occlusionQueryAlgorithmType);
  14310. this._isOcclusionQueryInProgress = true;
  14311. };
  14312. // Statics
  14313. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14314. AbstractMesh._BILLBOARDMODE_X = 1;
  14315. AbstractMesh._BILLBOARDMODE_Y = 2;
  14316. AbstractMesh._BILLBOARDMODE_Z = 4;
  14317. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14318. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14319. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14320. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14321. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14322. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14323. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14324. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14325. return AbstractMesh;
  14326. }(BABYLON.Node));
  14327. BABYLON.AbstractMesh = AbstractMesh;
  14328. })(BABYLON || (BABYLON = {}));
  14329. //# sourceMappingURL=babylon.abstractMesh.js.map
  14330. var BABYLON;
  14331. (function (BABYLON) {
  14332. var Light = (function (_super) {
  14333. __extends(Light, _super);
  14334. /**
  14335. * Creates a Light object in the scene.
  14336. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14337. */
  14338. function Light(name, scene) {
  14339. var _this = _super.call(this, name, scene) || this;
  14340. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14341. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14342. _this.intensity = 1.0;
  14343. _this.range = Number.MAX_VALUE;
  14344. /**
  14345. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14346. * of light.
  14347. */
  14348. _this._photometricScale = 1.0;
  14349. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14350. _this._radius = 0.00001;
  14351. _this.renderPriority = 0;
  14352. /**
  14353. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14354. * the current shadow generator.
  14355. */
  14356. _this.shadowEnabled = true;
  14357. _this._excludeWithLayerMask = 0;
  14358. _this._includeOnlyWithLayerMask = 0;
  14359. _this._lightmapMode = 0;
  14360. _this._excludedMeshesIds = new Array();
  14361. _this._includedOnlyMeshesIds = new Array();
  14362. _this.getScene().addLight(_this);
  14363. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14364. _this._buildUniformLayout();
  14365. _this.includedOnlyMeshes = new Array();
  14366. _this.excludedMeshes = new Array();
  14367. _this._resyncMeshes();
  14368. return _this;
  14369. }
  14370. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14371. /**
  14372. * If every light affecting the material is in this lightmapMode,
  14373. * material.lightmapTexture adds or multiplies
  14374. * (depends on material.useLightmapAsShadowmap)
  14375. * after every other light calculations.
  14376. */
  14377. get: function () {
  14378. return Light._LIGHTMAP_DEFAULT;
  14379. },
  14380. enumerable: true,
  14381. configurable: true
  14382. });
  14383. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14384. /**
  14385. * material.lightmapTexture as only diffuse lighting from this light
  14386. * adds pnly specular lighting from this light
  14387. * adds dynamic shadows
  14388. */
  14389. get: function () {
  14390. return Light._LIGHTMAP_SPECULAR;
  14391. },
  14392. enumerable: true,
  14393. configurable: true
  14394. });
  14395. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14396. /**
  14397. * material.lightmapTexture as only lighting
  14398. * no light calculation from this light
  14399. * only adds dynamic shadows from this light
  14400. */
  14401. get: function () {
  14402. return Light._LIGHTMAP_SHADOWSONLY;
  14403. },
  14404. enumerable: true,
  14405. configurable: true
  14406. });
  14407. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14408. /**
  14409. * Each light type uses the default quantity according to its type:
  14410. * point/spot lights use luminous intensity
  14411. * directional lights use illuminance
  14412. */
  14413. get: function () {
  14414. return Light._INTENSITYMODE_AUTOMATIC;
  14415. },
  14416. enumerable: true,
  14417. configurable: true
  14418. });
  14419. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14420. /**
  14421. * lumen (lm)
  14422. */
  14423. get: function () {
  14424. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14425. },
  14426. enumerable: true,
  14427. configurable: true
  14428. });
  14429. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14430. /**
  14431. * candela (lm/sr)
  14432. */
  14433. get: function () {
  14434. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14435. },
  14436. enumerable: true,
  14437. configurable: true
  14438. });
  14439. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14440. /**
  14441. * lux (lm/m^2)
  14442. */
  14443. get: function () {
  14444. return Light._INTENSITYMODE_ILLUMINANCE;
  14445. },
  14446. enumerable: true,
  14447. configurable: true
  14448. });
  14449. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14450. /**
  14451. * nit (cd/m^2)
  14452. */
  14453. get: function () {
  14454. return Light._INTENSITYMODE_LUMINANCE;
  14455. },
  14456. enumerable: true,
  14457. configurable: true
  14458. });
  14459. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14460. /**
  14461. * Light type const id of the point light.
  14462. */
  14463. get: function () {
  14464. return Light._LIGHTTYPEID_POINTLIGHT;
  14465. },
  14466. enumerable: true,
  14467. configurable: true
  14468. });
  14469. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14470. /**
  14471. * Light type const id of the directional light.
  14472. */
  14473. get: function () {
  14474. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14475. },
  14476. enumerable: true,
  14477. configurable: true
  14478. });
  14479. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14480. /**
  14481. * Light type const id of the spot light.
  14482. */
  14483. get: function () {
  14484. return Light._LIGHTTYPEID_SPOTLIGHT;
  14485. },
  14486. enumerable: true,
  14487. configurable: true
  14488. });
  14489. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14490. /**
  14491. * Light type const id of the hemispheric light.
  14492. */
  14493. get: function () {
  14494. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14495. },
  14496. enumerable: true,
  14497. configurable: true
  14498. });
  14499. Object.defineProperty(Light.prototype, "intensityMode", {
  14500. /**
  14501. * Gets the photometric scale used to interpret the intensity.
  14502. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14503. */
  14504. get: function () {
  14505. return this._intensityMode;
  14506. },
  14507. /**
  14508. * Sets the photometric scale used to interpret the intensity.
  14509. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14510. */
  14511. set: function (value) {
  14512. this._intensityMode = value;
  14513. this._computePhotometricScale();
  14514. },
  14515. enumerable: true,
  14516. configurable: true
  14517. });
  14518. ;
  14519. ;
  14520. Object.defineProperty(Light.prototype, "radius", {
  14521. /**
  14522. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14523. */
  14524. get: function () {
  14525. return this._radius;
  14526. },
  14527. /**
  14528. * sets the light radius used by PBR Materials to simulate soft area lights.
  14529. */
  14530. set: function (value) {
  14531. this._radius = value;
  14532. this._computePhotometricScale();
  14533. },
  14534. enumerable: true,
  14535. configurable: true
  14536. });
  14537. ;
  14538. ;
  14539. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14540. get: function () {
  14541. return this._includedOnlyMeshes;
  14542. },
  14543. set: function (value) {
  14544. this._includedOnlyMeshes = value;
  14545. this._hookArrayForIncludedOnly(value);
  14546. },
  14547. enumerable: true,
  14548. configurable: true
  14549. });
  14550. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14551. get: function () {
  14552. return this._excludedMeshes;
  14553. },
  14554. set: function (value) {
  14555. this._excludedMeshes = value;
  14556. this._hookArrayForExcluded(value);
  14557. },
  14558. enumerable: true,
  14559. configurable: true
  14560. });
  14561. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14562. get: function () {
  14563. return this._excludeWithLayerMask;
  14564. },
  14565. set: function (value) {
  14566. this._excludeWithLayerMask = value;
  14567. this._resyncMeshes();
  14568. },
  14569. enumerable: true,
  14570. configurable: true
  14571. });
  14572. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14573. get: function () {
  14574. return this._includeOnlyWithLayerMask;
  14575. },
  14576. set: function (value) {
  14577. this._includeOnlyWithLayerMask = value;
  14578. this._resyncMeshes();
  14579. },
  14580. enumerable: true,
  14581. configurable: true
  14582. });
  14583. Object.defineProperty(Light.prototype, "lightmapMode", {
  14584. get: function () {
  14585. return this._lightmapMode;
  14586. },
  14587. set: function (value) {
  14588. if (this._lightmapMode === value) {
  14589. return;
  14590. }
  14591. this._lightmapMode = value;
  14592. this._markMeshesAsLightDirty();
  14593. },
  14594. enumerable: true,
  14595. configurable: true
  14596. });
  14597. Light.prototype._buildUniformLayout = function () {
  14598. // Overridden
  14599. };
  14600. /**
  14601. * Returns the string "Light".
  14602. */
  14603. Light.prototype.getClassName = function () {
  14604. return "Light";
  14605. };
  14606. /**
  14607. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14608. */
  14609. Light.prototype.toString = function (fullDetails) {
  14610. var ret = "Name: " + this.name;
  14611. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14612. if (this.animations) {
  14613. for (var i = 0; i < this.animations.length; i++) {
  14614. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14615. }
  14616. }
  14617. if (fullDetails) {
  14618. }
  14619. return ret;
  14620. };
  14621. /**
  14622. * Set the enabled state of this node.
  14623. * @param {boolean} value - the new enabled state
  14624. * @see isEnabled
  14625. */
  14626. Light.prototype.setEnabled = function (value) {
  14627. _super.prototype.setEnabled.call(this, value);
  14628. this._resyncMeshes();
  14629. };
  14630. /**
  14631. * Returns the Light associated shadow generator.
  14632. */
  14633. Light.prototype.getShadowGenerator = function () {
  14634. return this._shadowGenerator;
  14635. };
  14636. /**
  14637. * Returns a Vector3, the absolute light position in the World.
  14638. */
  14639. Light.prototype.getAbsolutePosition = function () {
  14640. return BABYLON.Vector3.Zero();
  14641. };
  14642. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14643. };
  14644. Light.prototype._getWorldMatrix = function () {
  14645. return BABYLON.Matrix.Identity();
  14646. };
  14647. /**
  14648. * Boolean : True if the light will affect the passed mesh.
  14649. */
  14650. Light.prototype.canAffectMesh = function (mesh) {
  14651. if (!mesh) {
  14652. return true;
  14653. }
  14654. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14655. return false;
  14656. }
  14657. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14658. return false;
  14659. }
  14660. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14661. return false;
  14662. }
  14663. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14664. return false;
  14665. }
  14666. return true;
  14667. };
  14668. /**
  14669. * Returns the light World matrix.
  14670. */
  14671. Light.prototype.getWorldMatrix = function () {
  14672. this._currentRenderId = this.getScene().getRenderId();
  14673. var worldMatrix = this._getWorldMatrix();
  14674. if (this.parent && this.parent.getWorldMatrix) {
  14675. if (!this._parentedWorldMatrix) {
  14676. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14677. }
  14678. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14679. this._markSyncedWithParent();
  14680. return this._parentedWorldMatrix;
  14681. }
  14682. return worldMatrix;
  14683. };
  14684. /**
  14685. * Sort function to order lights for rendering.
  14686. * @param a First Light object to compare to second.
  14687. * @param b Second Light object to compare first.
  14688. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14689. */
  14690. Light.compareLightsPriority = function (a, b) {
  14691. //shadow-casting lights have priority over non-shadow-casting lights
  14692. //the renderPrioirty is a secondary sort criterion
  14693. if (a.shadowEnabled !== b.shadowEnabled) {
  14694. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14695. }
  14696. return b.renderPriority - a.renderPriority;
  14697. };
  14698. /**
  14699. * Disposes the light.
  14700. */
  14701. Light.prototype.dispose = function () {
  14702. if (this._shadowGenerator) {
  14703. this._shadowGenerator.dispose();
  14704. this._shadowGenerator = null;
  14705. }
  14706. // Animations
  14707. this.getScene().stopAnimation(this);
  14708. // Remove from meshes
  14709. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14710. var mesh = _a[_i];
  14711. mesh._removeLightSource(this);
  14712. }
  14713. this._uniformBuffer.dispose();
  14714. // Remove from scene
  14715. this.getScene().removeLight(this);
  14716. _super.prototype.dispose.call(this);
  14717. };
  14718. /**
  14719. * Returns the light type ID (integer).
  14720. */
  14721. Light.prototype.getTypeID = function () {
  14722. return 0;
  14723. };
  14724. /**
  14725. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14726. */
  14727. Light.prototype.getScaledIntensity = function () {
  14728. return this._photometricScale * this.intensity;
  14729. };
  14730. /**
  14731. * Returns a new Light object, named "name", from the current one.
  14732. */
  14733. Light.prototype.clone = function (name) {
  14734. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14735. };
  14736. /**
  14737. * Serializes the current light into a Serialization object.
  14738. * Returns the serialized object.
  14739. */
  14740. Light.prototype.serialize = function () {
  14741. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14742. // Type
  14743. serializationObject.type = this.getTypeID();
  14744. // Parent
  14745. if (this.parent) {
  14746. serializationObject.parentId = this.parent.id;
  14747. }
  14748. // Inclusion / exclusions
  14749. if (this.excludedMeshes.length > 0) {
  14750. serializationObject.excludedMeshesIds = [];
  14751. this.excludedMeshes.forEach(function (mesh) {
  14752. serializationObject.excludedMeshesIds.push(mesh.id);
  14753. });
  14754. }
  14755. if (this.includedOnlyMeshes.length > 0) {
  14756. serializationObject.includedOnlyMeshesIds = [];
  14757. this.includedOnlyMeshes.forEach(function (mesh) {
  14758. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14759. });
  14760. }
  14761. // Animations
  14762. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14763. serializationObject.ranges = this.serializeAnimationRanges();
  14764. return serializationObject;
  14765. };
  14766. /**
  14767. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14768. * This new light is named "name" and added to the passed scene.
  14769. */
  14770. Light.GetConstructorFromName = function (type, name, scene) {
  14771. switch (type) {
  14772. case 0:
  14773. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14774. case 1:
  14775. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14776. case 2:
  14777. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14778. case 3:
  14779. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14780. }
  14781. };
  14782. /**
  14783. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14784. */
  14785. Light.Parse = function (parsedLight, scene) {
  14786. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14787. // Inclusion / exclusions
  14788. if (parsedLight.excludedMeshesIds) {
  14789. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14790. }
  14791. if (parsedLight.includedOnlyMeshesIds) {
  14792. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14793. }
  14794. // Parent
  14795. if (parsedLight.parentId) {
  14796. light._waitingParentId = parsedLight.parentId;
  14797. }
  14798. // Animations
  14799. if (parsedLight.animations) {
  14800. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14801. var parsedAnimation = parsedLight.animations[animationIndex];
  14802. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14803. }
  14804. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14805. }
  14806. if (parsedLight.autoAnimate) {
  14807. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14808. }
  14809. return light;
  14810. };
  14811. Light.prototype._hookArrayForExcluded = function (array) {
  14812. var _this = this;
  14813. var oldPush = array.push;
  14814. array.push = function () {
  14815. var items = [];
  14816. for (var _i = 0; _i < arguments.length; _i++) {
  14817. items[_i] = arguments[_i];
  14818. }
  14819. var result = oldPush.apply(array, items);
  14820. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14821. var item = items_1[_a];
  14822. item._resyncLighSource(_this);
  14823. }
  14824. return result;
  14825. };
  14826. var oldSplice = array.splice;
  14827. array.splice = function (index, deleteCount) {
  14828. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14829. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14830. var item = deleted_1[_i];
  14831. item._resyncLighSource(_this);
  14832. }
  14833. return deleted;
  14834. };
  14835. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14836. var item = array_1[_i];
  14837. item._resyncLighSource(this);
  14838. }
  14839. };
  14840. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14841. var _this = this;
  14842. var oldPush = array.push;
  14843. array.push = function () {
  14844. var items = [];
  14845. for (var _i = 0; _i < arguments.length; _i++) {
  14846. items[_i] = arguments[_i];
  14847. }
  14848. var result = oldPush.apply(array, items);
  14849. _this._resyncMeshes();
  14850. return result;
  14851. };
  14852. var oldSplice = array.splice;
  14853. array.splice = function (index, deleteCount) {
  14854. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14855. _this._resyncMeshes();
  14856. return deleted;
  14857. };
  14858. this._resyncMeshes();
  14859. };
  14860. Light.prototype._resyncMeshes = function () {
  14861. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14862. var mesh = _a[_i];
  14863. mesh._resyncLighSource(this);
  14864. }
  14865. };
  14866. Light.prototype._markMeshesAsLightDirty = function () {
  14867. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14868. var mesh = _a[_i];
  14869. if (mesh._lightSources.indexOf(this) !== -1) {
  14870. mesh._markSubMeshesAsLightDirty();
  14871. }
  14872. }
  14873. };
  14874. /**
  14875. * Recomputes the cached photometric scale if needed.
  14876. */
  14877. Light.prototype._computePhotometricScale = function () {
  14878. this._photometricScale = this._getPhotometricScale();
  14879. this.getScene().resetCachedMaterial();
  14880. };
  14881. /**
  14882. * Returns the Photometric Scale according to the light type and intensity mode.
  14883. */
  14884. Light.prototype._getPhotometricScale = function () {
  14885. var photometricScale = 0.0;
  14886. var lightTypeID = this.getTypeID();
  14887. //get photometric mode
  14888. var photometricMode = this.intensityMode;
  14889. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14890. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14891. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14892. }
  14893. else {
  14894. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14895. }
  14896. }
  14897. //compute photometric scale
  14898. switch (lightTypeID) {
  14899. case Light.LIGHTTYPEID_POINTLIGHT:
  14900. case Light.LIGHTTYPEID_SPOTLIGHT:
  14901. switch (photometricMode) {
  14902. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14903. photometricScale = 1.0 / (4.0 * Math.PI);
  14904. break;
  14905. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14906. photometricScale = 1.0;
  14907. break;
  14908. case Light.INTENSITYMODE_LUMINANCE:
  14909. photometricScale = this.radius * this.radius;
  14910. break;
  14911. }
  14912. break;
  14913. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14914. switch (photometricMode) {
  14915. case Light.INTENSITYMODE_ILLUMINANCE:
  14916. photometricScale = 1.0;
  14917. break;
  14918. case Light.INTENSITYMODE_LUMINANCE:
  14919. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14920. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14921. var apexAngleRadians = this.radius;
  14922. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14923. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14924. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14925. photometricScale = solidAngle;
  14926. break;
  14927. }
  14928. break;
  14929. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14930. // No fall off in hemisperic light.
  14931. photometricScale = 1.0;
  14932. break;
  14933. }
  14934. return photometricScale;
  14935. };
  14936. Light.prototype._reorderLightsInScene = function () {
  14937. var scene = this.getScene();
  14938. if (this.renderPriority != 0) {
  14939. scene.requireLightSorting = true;
  14940. }
  14941. this.getScene().sortLightsByPriority();
  14942. };
  14943. //lightmapMode Consts
  14944. Light._LIGHTMAP_DEFAULT = 0;
  14945. Light._LIGHTMAP_SPECULAR = 1;
  14946. Light._LIGHTMAP_SHADOWSONLY = 2;
  14947. // Intensity Mode Consts
  14948. Light._INTENSITYMODE_AUTOMATIC = 0;
  14949. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14950. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14951. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14952. Light._INTENSITYMODE_LUMINANCE = 4;
  14953. // Light types ids const.
  14954. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14955. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14956. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14957. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14958. __decorate([
  14959. BABYLON.serializeAsColor3()
  14960. ], Light.prototype, "diffuse", void 0);
  14961. __decorate([
  14962. BABYLON.serializeAsColor3()
  14963. ], Light.prototype, "specular", void 0);
  14964. __decorate([
  14965. BABYLON.serialize()
  14966. ], Light.prototype, "intensity", void 0);
  14967. __decorate([
  14968. BABYLON.serialize()
  14969. ], Light.prototype, "range", void 0);
  14970. __decorate([
  14971. BABYLON.serialize()
  14972. ], Light.prototype, "intensityMode", null);
  14973. __decorate([
  14974. BABYLON.serialize()
  14975. ], Light.prototype, "radius", null);
  14976. __decorate([
  14977. BABYLON.serialize()
  14978. ], Light.prototype, "_renderPriority", void 0);
  14979. __decorate([
  14980. BABYLON.expandToProperty("_reorderLightsInScene")
  14981. ], Light.prototype, "renderPriority", void 0);
  14982. __decorate([
  14983. BABYLON.serialize()
  14984. ], Light.prototype, "shadowEnabled", void 0);
  14985. __decorate([
  14986. BABYLON.serialize("excludeWithLayerMask")
  14987. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14988. __decorate([
  14989. BABYLON.serialize("includeOnlyWithLayerMask")
  14990. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14991. __decorate([
  14992. BABYLON.serialize("lightmapMode")
  14993. ], Light.prototype, "_lightmapMode", void 0);
  14994. return Light;
  14995. }(BABYLON.Node));
  14996. BABYLON.Light = Light;
  14997. })(BABYLON || (BABYLON = {}));
  14998. //# sourceMappingURL=babylon.light.js.map
  14999. var BABYLON;
  15000. (function (BABYLON) {
  15001. var Camera = (function (_super) {
  15002. __extends(Camera, _super);
  15003. function Camera(name, position, scene) {
  15004. var _this = _super.call(this, name, scene) || this;
  15005. _this.upVector = BABYLON.Vector3.Up();
  15006. _this.orthoLeft = null;
  15007. _this.orthoRight = null;
  15008. _this.orthoBottom = null;
  15009. _this.orthoTop = null;
  15010. _this.fov = 0.8;
  15011. _this.minZ = 1;
  15012. _this.maxZ = 10000.0;
  15013. _this.inertia = 0.9;
  15014. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15015. _this.isIntermediate = false;
  15016. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15017. _this.layerMask = 0x0FFFFFFF;
  15018. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15019. // Camera rig members
  15020. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15021. _this._rigCameras = new Array();
  15022. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15023. _this._skipRendering = false;
  15024. _this.customRenderTargets = new Array();
  15025. // Observables
  15026. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15027. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15028. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15029. _this.onRestoreStateObservable = new BABYLON.Observable();
  15030. // Cache
  15031. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15032. _this._projectionMatrix = new BABYLON.Matrix();
  15033. _this._doNotComputeProjectionMatrix = false;
  15034. _this._postProcesses = new Array();
  15035. _this._transformMatrix = BABYLON.Matrix.Zero();
  15036. _this._activeMeshes = new BABYLON.SmartArray(256);
  15037. _this._globalPosition = BABYLON.Vector3.Zero();
  15038. _this._refreshFrustumPlanes = true;
  15039. _this.getScene().addCamera(_this);
  15040. if (!_this.getScene().activeCamera) {
  15041. _this.getScene().activeCamera = _this;
  15042. }
  15043. _this.position = position;
  15044. return _this;
  15045. }
  15046. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15047. get: function () {
  15048. return Camera._PERSPECTIVE_CAMERA;
  15049. },
  15050. enumerable: true,
  15051. configurable: true
  15052. });
  15053. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15054. get: function () {
  15055. return Camera._ORTHOGRAPHIC_CAMERA;
  15056. },
  15057. enumerable: true,
  15058. configurable: true
  15059. });
  15060. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15061. get: function () {
  15062. return Camera._FOVMODE_VERTICAL_FIXED;
  15063. },
  15064. enumerable: true,
  15065. configurable: true
  15066. });
  15067. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15068. get: function () {
  15069. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15070. },
  15071. enumerable: true,
  15072. configurable: true
  15073. });
  15074. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15075. get: function () {
  15076. return Camera._RIG_MODE_NONE;
  15077. },
  15078. enumerable: true,
  15079. configurable: true
  15080. });
  15081. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15082. get: function () {
  15083. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15084. },
  15085. enumerable: true,
  15086. configurable: true
  15087. });
  15088. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15089. get: function () {
  15090. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15091. },
  15092. enumerable: true,
  15093. configurable: true
  15094. });
  15095. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15096. get: function () {
  15097. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15098. },
  15099. enumerable: true,
  15100. configurable: true
  15101. });
  15102. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15103. get: function () {
  15104. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15105. },
  15106. enumerable: true,
  15107. configurable: true
  15108. });
  15109. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15110. get: function () {
  15111. return Camera._RIG_MODE_VR;
  15112. },
  15113. enumerable: true,
  15114. configurable: true
  15115. });
  15116. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15117. get: function () {
  15118. return Camera._RIG_MODE_WEBVR;
  15119. },
  15120. enumerable: true,
  15121. configurable: true
  15122. });
  15123. /**
  15124. * Store current camera state (fov, position, etc..)
  15125. */
  15126. Camera.prototype.storeState = function () {
  15127. this._stateStored = true;
  15128. this._storedFov = this.fov;
  15129. return this;
  15130. };
  15131. /**
  15132. * Restores the camera state values if it has been stored. You must call storeState() first
  15133. */
  15134. Camera.prototype._restoreStateValues = function () {
  15135. if (!this._stateStored) {
  15136. return false;
  15137. }
  15138. this.fov = this._storedFov;
  15139. return true;
  15140. };
  15141. /**
  15142. * Restored camera state. You must call storeState() first
  15143. */
  15144. Camera.prototype.restoreState = function () {
  15145. if (this._restoreStateValues()) {
  15146. this.onRestoreStateObservable.notifyObservers(this);
  15147. return true;
  15148. }
  15149. return false;
  15150. };
  15151. Camera.prototype.getClassName = function () {
  15152. return "Camera";
  15153. };
  15154. /**
  15155. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15156. */
  15157. Camera.prototype.toString = function (fullDetails) {
  15158. var ret = "Name: " + this.name;
  15159. ret += ", type: " + this.getClassName();
  15160. if (this.animations) {
  15161. for (var i = 0; i < this.animations.length; i++) {
  15162. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15163. }
  15164. }
  15165. if (fullDetails) {
  15166. }
  15167. return ret;
  15168. };
  15169. Object.defineProperty(Camera.prototype, "globalPosition", {
  15170. get: function () {
  15171. return this._globalPosition;
  15172. },
  15173. enumerable: true,
  15174. configurable: true
  15175. });
  15176. Camera.prototype.getActiveMeshes = function () {
  15177. return this._activeMeshes;
  15178. };
  15179. Camera.prototype.isActiveMesh = function (mesh) {
  15180. return (this._activeMeshes.indexOf(mesh) !== -1);
  15181. };
  15182. //Cache
  15183. Camera.prototype._initCache = function () {
  15184. _super.prototype._initCache.call(this);
  15185. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15186. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15187. this._cache.mode = undefined;
  15188. this._cache.minZ = undefined;
  15189. this._cache.maxZ = undefined;
  15190. this._cache.fov = undefined;
  15191. this._cache.fovMode = undefined;
  15192. this._cache.aspectRatio = undefined;
  15193. this._cache.orthoLeft = undefined;
  15194. this._cache.orthoRight = undefined;
  15195. this._cache.orthoBottom = undefined;
  15196. this._cache.orthoTop = undefined;
  15197. this._cache.renderWidth = undefined;
  15198. this._cache.renderHeight = undefined;
  15199. };
  15200. Camera.prototype._updateCache = function (ignoreParentClass) {
  15201. if (!ignoreParentClass) {
  15202. _super.prototype._updateCache.call(this);
  15203. }
  15204. var engine = this.getEngine();
  15205. this._cache.position.copyFrom(this.position);
  15206. this._cache.upVector.copyFrom(this.upVector);
  15207. };
  15208. // Synchronized
  15209. Camera.prototype._isSynchronized = function () {
  15210. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15211. };
  15212. Camera.prototype._isSynchronizedViewMatrix = function () {
  15213. if (!_super.prototype._isSynchronized.call(this))
  15214. return false;
  15215. return this._cache.position.equals(this.position)
  15216. && this._cache.upVector.equals(this.upVector)
  15217. && this.isSynchronizedWithParent();
  15218. };
  15219. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15220. var check = this._cache.mode === this.mode
  15221. && this._cache.minZ === this.minZ
  15222. && this._cache.maxZ === this.maxZ;
  15223. if (!check) {
  15224. return false;
  15225. }
  15226. var engine = this.getEngine();
  15227. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15228. check = this._cache.fov === this.fov
  15229. && this._cache.fovMode === this.fovMode
  15230. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15231. }
  15232. else {
  15233. check = this._cache.orthoLeft === this.orthoLeft
  15234. && this._cache.orthoRight === this.orthoRight
  15235. && this._cache.orthoBottom === this.orthoBottom
  15236. && this._cache.orthoTop === this.orthoTop
  15237. && this._cache.renderWidth === engine.getRenderWidth()
  15238. && this._cache.renderHeight === engine.getRenderHeight();
  15239. }
  15240. return check;
  15241. };
  15242. // Controls
  15243. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15244. };
  15245. Camera.prototype.detachControl = function (element) {
  15246. };
  15247. Camera.prototype.update = function () {
  15248. this._checkInputs();
  15249. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15250. this._updateRigCameras();
  15251. }
  15252. };
  15253. Camera.prototype._checkInputs = function () {
  15254. this.onAfterCheckInputsObservable.notifyObservers(this);
  15255. };
  15256. Object.defineProperty(Camera.prototype, "rigCameras", {
  15257. get: function () {
  15258. return this._rigCameras;
  15259. },
  15260. enumerable: true,
  15261. configurable: true
  15262. });
  15263. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15264. get: function () {
  15265. return this._rigPostProcess;
  15266. },
  15267. enumerable: true,
  15268. configurable: true
  15269. });
  15270. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15271. // invalidate framebuffer
  15272. if (this._postProcesses.length > 0) {
  15273. this._postProcesses[0].markTextureDirty();
  15274. }
  15275. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15276. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15277. var cam = this._rigCameras[i];
  15278. var rigPostProcess = cam._rigPostProcess;
  15279. // for VR rig, there does not have to be a post process
  15280. if (rigPostProcess) {
  15281. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15282. if (isPass) {
  15283. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15284. cam.isIntermediate = this._postProcesses.length === 0;
  15285. }
  15286. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15287. rigPostProcess.markTextureDirty();
  15288. }
  15289. else {
  15290. cam._postProcesses = this._postProcesses.slice(0);
  15291. }
  15292. }
  15293. };
  15294. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15295. if (insertAt === void 0) { insertAt = null; }
  15296. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15297. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15298. return 0;
  15299. }
  15300. if (insertAt == null || insertAt < 0) {
  15301. this._postProcesses.push(postProcess);
  15302. }
  15303. else {
  15304. this._postProcesses.splice(insertAt, 0, postProcess);
  15305. }
  15306. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15307. return this._postProcesses.indexOf(postProcess);
  15308. };
  15309. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15310. if (atIndices === void 0) { atIndices = null; }
  15311. var result = [];
  15312. var i;
  15313. var index;
  15314. if (!atIndices) {
  15315. var idx = this._postProcesses.indexOf(postProcess);
  15316. if (idx !== -1) {
  15317. this._postProcesses.splice(idx, 1);
  15318. }
  15319. }
  15320. else {
  15321. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15322. // iterate descending, so can just splice as we go
  15323. for (i = atIndices.length - 1; i >= 0; i--) {
  15324. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15325. result.push(i);
  15326. continue;
  15327. }
  15328. index = atIndices[i];
  15329. this._postProcesses.splice(index, 1);
  15330. }
  15331. }
  15332. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15333. return result;
  15334. };
  15335. Camera.prototype.getWorldMatrix = function () {
  15336. if (!this._worldMatrix) {
  15337. this._worldMatrix = BABYLON.Matrix.Identity();
  15338. }
  15339. var viewMatrix = this.getViewMatrix();
  15340. viewMatrix.invertToRef(this._worldMatrix);
  15341. return this._worldMatrix;
  15342. };
  15343. Camera.prototype._getViewMatrix = function () {
  15344. return BABYLON.Matrix.Identity();
  15345. };
  15346. Camera.prototype.getViewMatrix = function (force) {
  15347. if (!force && this._isSynchronizedViewMatrix()) {
  15348. return this._computedViewMatrix;
  15349. }
  15350. this.updateCache();
  15351. this._computedViewMatrix = this._getViewMatrix();
  15352. this._currentRenderId = this.getScene().getRenderId();
  15353. this._refreshFrustumPlanes = true;
  15354. if (!this.parent || !this.parent.getWorldMatrix) {
  15355. this._globalPosition.copyFrom(this.position);
  15356. }
  15357. else {
  15358. if (!this._worldMatrix) {
  15359. this._worldMatrix = BABYLON.Matrix.Identity();
  15360. }
  15361. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15362. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15363. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15364. this._computedViewMatrix.invert();
  15365. this._markSyncedWithParent();
  15366. }
  15367. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15368. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15369. }
  15370. this.onViewMatrixChangedObservable.notifyObservers(this);
  15371. return this._computedViewMatrix;
  15372. };
  15373. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15374. this._doNotComputeProjectionMatrix = true;
  15375. if (projection !== undefined) {
  15376. this._projectionMatrix = projection;
  15377. }
  15378. };
  15379. ;
  15380. Camera.prototype.unfreezeProjectionMatrix = function () {
  15381. this._doNotComputeProjectionMatrix = false;
  15382. };
  15383. ;
  15384. Camera.prototype.getProjectionMatrix = function (force) {
  15385. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15386. return this._projectionMatrix;
  15387. }
  15388. // Cache
  15389. this._cache.mode = this.mode;
  15390. this._cache.minZ = this.minZ;
  15391. this._cache.maxZ = this.maxZ;
  15392. // Matrix
  15393. this._refreshFrustumPlanes = true;
  15394. var engine = this.getEngine();
  15395. var scene = this.getScene();
  15396. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15397. this._cache.fov = this.fov;
  15398. this._cache.fovMode = this.fovMode;
  15399. this._cache.aspectRatio = engine.getAspectRatio(this);
  15400. if (this.minZ <= 0) {
  15401. this.minZ = 0.1;
  15402. }
  15403. if (scene.useRightHandedSystem) {
  15404. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15405. }
  15406. else {
  15407. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15408. }
  15409. }
  15410. else {
  15411. var halfWidth = engine.getRenderWidth() / 2.0;
  15412. var halfHeight = engine.getRenderHeight() / 2.0;
  15413. if (scene.useRightHandedSystem) {
  15414. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15415. }
  15416. else {
  15417. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15418. }
  15419. this._cache.orthoLeft = this.orthoLeft;
  15420. this._cache.orthoRight = this.orthoRight;
  15421. this._cache.orthoBottom = this.orthoBottom;
  15422. this._cache.orthoTop = this.orthoTop;
  15423. this._cache.renderWidth = engine.getRenderWidth();
  15424. this._cache.renderHeight = engine.getRenderHeight();
  15425. }
  15426. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15427. return this._projectionMatrix;
  15428. };
  15429. Camera.prototype.getTranformationMatrix = function () {
  15430. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15431. return this._transformMatrix;
  15432. };
  15433. Camera.prototype.updateFrustumPlanes = function () {
  15434. if (!this._refreshFrustumPlanes) {
  15435. return;
  15436. }
  15437. this.getTranformationMatrix();
  15438. if (!this._frustumPlanes) {
  15439. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15440. }
  15441. else {
  15442. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15443. }
  15444. this._refreshFrustumPlanes = false;
  15445. };
  15446. Camera.prototype.isInFrustum = function (target) {
  15447. this.updateFrustumPlanes();
  15448. return target.isInFrustum(this._frustumPlanes);
  15449. };
  15450. Camera.prototype.isCompletelyInFrustum = function (target) {
  15451. this.updateFrustumPlanes();
  15452. return target.isCompletelyInFrustum(this._frustumPlanes);
  15453. };
  15454. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15455. if (length === void 0) { length = 100; }
  15456. if (!transform) {
  15457. transform = this.getWorldMatrix();
  15458. }
  15459. if (!origin) {
  15460. origin = this.position;
  15461. }
  15462. var forward = new BABYLON.Vector3(0, 0, 1);
  15463. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15464. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15465. return new BABYLON.Ray(origin, direction, length);
  15466. };
  15467. Camera.prototype.dispose = function () {
  15468. // Observables
  15469. this.onViewMatrixChangedObservable.clear();
  15470. this.onProjectionMatrixChangedObservable.clear();
  15471. this.onAfterCheckInputsObservable.clear();
  15472. this.onRestoreStateObservable.clear();
  15473. // Inputs
  15474. if (this.inputs) {
  15475. this.inputs.clear();
  15476. }
  15477. // Animations
  15478. this.getScene().stopAnimation(this);
  15479. // Remove from scene
  15480. this.getScene().removeCamera(this);
  15481. while (this._rigCameras.length > 0) {
  15482. this._rigCameras.pop().dispose();
  15483. }
  15484. // Postprocesses
  15485. var i = this._postProcesses.length;
  15486. while (--i >= 0) {
  15487. this._postProcesses[i].dispose(this);
  15488. }
  15489. // Render targets
  15490. var i = this.customRenderTargets.length;
  15491. while (--i >= 0) {
  15492. this.customRenderTargets[i].dispose();
  15493. }
  15494. this.customRenderTargets = [];
  15495. // Active Meshes
  15496. this._activeMeshes.dispose();
  15497. _super.prototype.dispose.call(this);
  15498. };
  15499. Object.defineProperty(Camera.prototype, "leftCamera", {
  15500. // ---- Camera rigs section ----
  15501. get: function () {
  15502. if (this._rigCameras.length < 1) {
  15503. return undefined;
  15504. }
  15505. return this._rigCameras[0];
  15506. },
  15507. enumerable: true,
  15508. configurable: true
  15509. });
  15510. Object.defineProperty(Camera.prototype, "rightCamera", {
  15511. get: function () {
  15512. if (this._rigCameras.length < 2) {
  15513. return undefined;
  15514. }
  15515. return this._rigCameras[1];
  15516. },
  15517. enumerable: true,
  15518. configurable: true
  15519. });
  15520. Camera.prototype.getLeftTarget = function () {
  15521. if (this._rigCameras.length < 1) {
  15522. return undefined;
  15523. }
  15524. return this._rigCameras[0].getTarget();
  15525. };
  15526. Camera.prototype.getRightTarget = function () {
  15527. if (this._rigCameras.length < 2) {
  15528. return undefined;
  15529. }
  15530. return this._rigCameras[1].getTarget();
  15531. };
  15532. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15533. while (this._rigCameras.length > 0) {
  15534. this._rigCameras.pop().dispose();
  15535. }
  15536. this.cameraRigMode = mode;
  15537. this._cameraRigParams = {};
  15538. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15539. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15540. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15541. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15542. // create the rig cameras, unless none
  15543. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15544. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15545. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15546. }
  15547. switch (this.cameraRigMode) {
  15548. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15549. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15550. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15551. break;
  15552. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15553. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15554. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15555. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15556. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15557. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15558. break;
  15559. case Camera.RIG_MODE_VR:
  15560. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15561. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15562. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15563. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15564. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15565. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15566. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15567. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15568. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15569. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15570. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15571. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15572. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15573. if (metrics.compensateDistortion) {
  15574. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15575. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15576. }
  15577. break;
  15578. case Camera.RIG_MODE_WEBVR:
  15579. if (rigParams.vrDisplay) {
  15580. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15581. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15582. //Left eye
  15583. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15584. this._rigCameras[0].setCameraRigParameter("left", true);
  15585. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15586. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15587. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15588. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15589. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15590. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15591. this._rigCameras[0].parent = this;
  15592. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15593. //Right eye
  15594. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15595. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15596. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15597. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15598. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15599. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15600. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15601. this._rigCameras[1].parent = this;
  15602. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15603. if (Camera.UseAlternateWebVRRendering) {
  15604. this._rigCameras[1]._skipRendering = true;
  15605. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  15606. }
  15607. }
  15608. break;
  15609. }
  15610. this._cascadePostProcessesToRigCams();
  15611. this.update();
  15612. };
  15613. Camera.prototype._getVRProjectionMatrix = function () {
  15614. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15615. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15616. return this._projectionMatrix;
  15617. };
  15618. Camera.prototype._updateCameraRotationMatrix = function () {
  15619. //Here for WebVR
  15620. };
  15621. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15622. //Here for WebVR
  15623. };
  15624. /**
  15625. * This function MUST be overwritten by the different WebVR cameras available.
  15626. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15627. */
  15628. Camera.prototype._getWebVRProjectionMatrix = function () {
  15629. return BABYLON.Matrix.Identity();
  15630. };
  15631. /**
  15632. * This function MUST be overwritten by the different WebVR cameras available.
  15633. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15634. */
  15635. Camera.prototype._getWebVRViewMatrix = function () {
  15636. return BABYLON.Matrix.Identity();
  15637. };
  15638. Camera.prototype.setCameraRigParameter = function (name, value) {
  15639. if (!this._cameraRigParams) {
  15640. this._cameraRigParams = {};
  15641. }
  15642. this._cameraRigParams[name] = value;
  15643. //provisionnally:
  15644. if (name === "interaxialDistance") {
  15645. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15646. }
  15647. };
  15648. /**
  15649. * needs to be overridden by children so sub has required properties to be copied
  15650. */
  15651. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15652. return null;
  15653. };
  15654. /**
  15655. * May need to be overridden by children
  15656. */
  15657. Camera.prototype._updateRigCameras = function () {
  15658. for (var i = 0; i < this._rigCameras.length; i++) {
  15659. this._rigCameras[i].minZ = this.minZ;
  15660. this._rigCameras[i].maxZ = this.maxZ;
  15661. this._rigCameras[i].fov = this.fov;
  15662. }
  15663. // only update viewport when ANAGLYPH
  15664. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15665. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15666. }
  15667. };
  15668. Camera.prototype._setupInputs = function () {
  15669. };
  15670. Camera.prototype.serialize = function () {
  15671. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15672. // Type
  15673. serializationObject.type = this.getClassName();
  15674. // Parent
  15675. if (this.parent) {
  15676. serializationObject.parentId = this.parent.id;
  15677. }
  15678. if (this.inputs) {
  15679. this.inputs.serialize(serializationObject);
  15680. }
  15681. // Animations
  15682. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15683. serializationObject.ranges = this.serializeAnimationRanges();
  15684. return serializationObject;
  15685. };
  15686. Camera.prototype.clone = function (name) {
  15687. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15688. };
  15689. Camera.prototype.getDirection = function (localAxis) {
  15690. var result = BABYLON.Vector3.Zero();
  15691. this.getDirectionToRef(localAxis, result);
  15692. return result;
  15693. };
  15694. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15695. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15696. };
  15697. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15698. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15699. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15700. switch (type) {
  15701. case "ArcRotateCamera":
  15702. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15703. case "DeviceOrientationCamera":
  15704. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15705. case "FollowCamera":
  15706. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15707. case "ArcFollowCamera":
  15708. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15709. case "GamepadCamera":
  15710. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15711. case "TouchCamera":
  15712. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15713. case "VirtualJoysticksCamera":
  15714. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15715. case "WebVRFreeCamera":
  15716. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15717. case "WebVRGamepadCamera":
  15718. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15719. case "VRDeviceOrientationFreeCamera":
  15720. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15721. case "VRDeviceOrientationGamepadCamera":
  15722. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15723. case "AnaglyphArcRotateCamera":
  15724. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15725. case "AnaglyphFreeCamera":
  15726. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15727. case "AnaglyphGamepadCamera":
  15728. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15729. case "AnaglyphUniversalCamera":
  15730. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15731. case "StereoscopicArcRotateCamera":
  15732. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15733. case "StereoscopicFreeCamera":
  15734. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15735. case "StereoscopicGamepadCamera":
  15736. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15737. case "StereoscopicUniversalCamera":
  15738. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15739. case "FreeCamera":// Forcing Universal here
  15740. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15741. default:// Universal Camera is the default value
  15742. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15743. }
  15744. };
  15745. Camera.Parse = function (parsedCamera, scene) {
  15746. var type = parsedCamera.type;
  15747. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15748. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15749. // Parent
  15750. if (parsedCamera.parentId) {
  15751. camera._waitingParentId = parsedCamera.parentId;
  15752. }
  15753. //If camera has an input manager, let it parse inputs settings
  15754. if (camera.inputs) {
  15755. camera.inputs.parse(parsedCamera);
  15756. camera._setupInputs();
  15757. }
  15758. if (camera.setPosition) {
  15759. camera.position.copyFromFloats(0, 0, 0);
  15760. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15761. }
  15762. // Target
  15763. if (parsedCamera.target) {
  15764. if (camera.setTarget) {
  15765. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15766. }
  15767. }
  15768. // Apply 3d rig, when found
  15769. if (parsedCamera.cameraRigMode) {
  15770. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15771. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15772. }
  15773. // Animations
  15774. if (parsedCamera.animations) {
  15775. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15776. var parsedAnimation = parsedCamera.animations[animationIndex];
  15777. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15778. }
  15779. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15780. }
  15781. if (parsedCamera.autoAnimate) {
  15782. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15783. }
  15784. return camera;
  15785. };
  15786. // Statics
  15787. Camera._PERSPECTIVE_CAMERA = 0;
  15788. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15789. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15790. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15791. Camera._RIG_MODE_NONE = 0;
  15792. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15793. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15794. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15795. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15796. Camera._RIG_MODE_VR = 20;
  15797. Camera._RIG_MODE_WEBVR = 21;
  15798. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15799. Camera.UseAlternateWebVRRendering = false;
  15800. __decorate([
  15801. BABYLON.serializeAsVector3()
  15802. ], Camera.prototype, "position", void 0);
  15803. __decorate([
  15804. BABYLON.serializeAsVector3()
  15805. ], Camera.prototype, "upVector", void 0);
  15806. __decorate([
  15807. BABYLON.serialize()
  15808. ], Camera.prototype, "orthoLeft", void 0);
  15809. __decorate([
  15810. BABYLON.serialize()
  15811. ], Camera.prototype, "orthoRight", void 0);
  15812. __decorate([
  15813. BABYLON.serialize()
  15814. ], Camera.prototype, "orthoBottom", void 0);
  15815. __decorate([
  15816. BABYLON.serialize()
  15817. ], Camera.prototype, "orthoTop", void 0);
  15818. __decorate([
  15819. BABYLON.serialize()
  15820. ], Camera.prototype, "fov", void 0);
  15821. __decorate([
  15822. BABYLON.serialize()
  15823. ], Camera.prototype, "minZ", void 0);
  15824. __decorate([
  15825. BABYLON.serialize()
  15826. ], Camera.prototype, "maxZ", void 0);
  15827. __decorate([
  15828. BABYLON.serialize()
  15829. ], Camera.prototype, "inertia", void 0);
  15830. __decorate([
  15831. BABYLON.serialize()
  15832. ], Camera.prototype, "mode", void 0);
  15833. __decorate([
  15834. BABYLON.serialize()
  15835. ], Camera.prototype, "layerMask", void 0);
  15836. __decorate([
  15837. BABYLON.serialize()
  15838. ], Camera.prototype, "fovMode", void 0);
  15839. __decorate([
  15840. BABYLON.serialize()
  15841. ], Camera.prototype, "cameraRigMode", void 0);
  15842. __decorate([
  15843. BABYLON.serialize()
  15844. ], Camera.prototype, "interaxialDistance", void 0);
  15845. __decorate([
  15846. BABYLON.serialize()
  15847. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15848. return Camera;
  15849. }(BABYLON.Node));
  15850. BABYLON.Camera = Camera;
  15851. })(BABYLON || (BABYLON = {}));
  15852. //# sourceMappingURL=babylon.camera.js.map
  15853. var BABYLON;
  15854. (function (BABYLON) {
  15855. var RenderingManager = (function () {
  15856. function RenderingManager(scene) {
  15857. this._renderingGroups = new Array();
  15858. this._autoClearDepthStencil = {};
  15859. this._customOpaqueSortCompareFn = {};
  15860. this._customAlphaTestSortCompareFn = {};
  15861. this._customTransparentSortCompareFn = {};
  15862. this._renderinGroupInfo = null;
  15863. this._scene = scene;
  15864. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15865. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15866. }
  15867. }
  15868. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15869. if (depth === void 0) { depth = true; }
  15870. if (stencil === void 0) { stencil = true; }
  15871. if (this._depthStencilBufferAlreadyCleaned) {
  15872. return;
  15873. }
  15874. this._scene.getEngine().clear(null, false, depth, stencil);
  15875. this._depthStencilBufferAlreadyCleaned = true;
  15876. };
  15877. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15878. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15879. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15880. var info = null;
  15881. if (observable) {
  15882. if (!this._renderinGroupInfo) {
  15883. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15884. }
  15885. info = this._renderinGroupInfo;
  15886. info.scene = this._scene;
  15887. info.camera = this._scene.activeCamera;
  15888. }
  15889. // Dispatch sprites
  15890. if (renderSprites) {
  15891. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15892. var manager = this._scene.spriteManagers[index];
  15893. this.dispatchSprites(manager);
  15894. }
  15895. }
  15896. // Render
  15897. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15898. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15899. var renderingGroup = this._renderingGroups[index];
  15900. if (!renderingGroup && !observable)
  15901. continue;
  15902. this._currentIndex = index;
  15903. var renderingGroupMask = 0;
  15904. // Fire PRECLEAR stage
  15905. if (observable) {
  15906. renderingGroupMask = Math.pow(2, index);
  15907. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15908. info.renderingGroupId = index;
  15909. observable.notifyObservers(info, renderingGroupMask);
  15910. }
  15911. // Clear depth/stencil if needed
  15912. if (RenderingManager.AUTOCLEAR) {
  15913. var autoClear = this._autoClearDepthStencil[index];
  15914. if (autoClear && autoClear.autoClear) {
  15915. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15916. }
  15917. }
  15918. if (observable) {
  15919. // Fire PREOPAQUE stage
  15920. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15921. observable.notifyObservers(info, renderingGroupMask);
  15922. // Fire PRETRANSPARENT stage
  15923. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15924. observable.notifyObservers(info, renderingGroupMask);
  15925. }
  15926. if (renderingGroup)
  15927. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15928. // Fire POSTTRANSPARENT stage
  15929. if (observable) {
  15930. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15931. observable.notifyObservers(info, renderingGroupMask);
  15932. }
  15933. }
  15934. };
  15935. RenderingManager.prototype.reset = function () {
  15936. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15937. var renderingGroup = this._renderingGroups[index];
  15938. if (renderingGroup) {
  15939. renderingGroup.prepare();
  15940. }
  15941. }
  15942. };
  15943. RenderingManager.prototype.dispose = function () {
  15944. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15945. var renderingGroup = this._renderingGroups[index];
  15946. if (renderingGroup) {
  15947. renderingGroup.dispose();
  15948. }
  15949. }
  15950. this._renderingGroups.length = 0;
  15951. };
  15952. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15953. if (!this._renderingGroups[renderingGroupId]) {
  15954. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15955. }
  15956. };
  15957. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15958. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15959. this._prepareRenderingGroup(renderingGroupId);
  15960. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15961. };
  15962. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15963. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15964. this._prepareRenderingGroup(renderingGroupId);
  15965. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15966. };
  15967. RenderingManager.prototype.dispatch = function (subMesh) {
  15968. var mesh = subMesh.getMesh();
  15969. var renderingGroupId = mesh.renderingGroupId || 0;
  15970. this._prepareRenderingGroup(renderingGroupId);
  15971. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15972. };
  15973. /**
  15974. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15975. * This allowed control for front to back rendering or reversly depending of the special needs.
  15976. *
  15977. * @param renderingGroupId The rendering group id corresponding to its index
  15978. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15979. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15980. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15981. */
  15982. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15983. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15984. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15985. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15986. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15987. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15988. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15989. if (this._renderingGroups[renderingGroupId]) {
  15990. var group = this._renderingGroups[renderingGroupId];
  15991. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15992. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15993. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15994. }
  15995. };
  15996. /**
  15997. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15998. *
  15999. * @param renderingGroupId The rendering group id corresponding to its index
  16000. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16001. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16002. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16003. */
  16004. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16005. if (depth === void 0) { depth = true; }
  16006. if (stencil === void 0) { stencil = true; }
  16007. this._autoClearDepthStencil[renderingGroupId] = {
  16008. autoClear: autoClearDepthStencil,
  16009. depth: depth,
  16010. stencil: stencil
  16011. };
  16012. };
  16013. /**
  16014. * The max id used for rendering groups (not included)
  16015. */
  16016. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16017. /**
  16018. * The min id used for rendering groups (included)
  16019. */
  16020. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16021. /**
  16022. * Used to globally prevent autoclearing scenes.
  16023. */
  16024. RenderingManager.AUTOCLEAR = true;
  16025. return RenderingManager;
  16026. }());
  16027. BABYLON.RenderingManager = RenderingManager;
  16028. })(BABYLON || (BABYLON = {}));
  16029. //# sourceMappingURL=babylon.renderingManager.js.map
  16030. var BABYLON;
  16031. (function (BABYLON) {
  16032. var RenderingGroup = (function () {
  16033. /**
  16034. * Creates a new rendering group.
  16035. * @param index The rendering group index
  16036. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16037. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16038. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16039. */
  16040. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16041. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16042. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16043. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16044. this.index = index;
  16045. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16046. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16047. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16048. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16049. this._particleSystems = new BABYLON.SmartArray(256);
  16050. this._spriteManagers = new BABYLON.SmartArray(256);
  16051. this._edgesRenderers = new BABYLON.SmartArray(16);
  16052. this._scene = scene;
  16053. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16054. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16055. this.transparentSortCompareFn = transparentSortCompareFn;
  16056. }
  16057. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16058. /**
  16059. * Set the opaque sort comparison function.
  16060. * If null the sub meshes will be render in the order they were created
  16061. */
  16062. set: function (value) {
  16063. this._opaqueSortCompareFn = value;
  16064. if (value) {
  16065. this._renderOpaque = this.renderOpaqueSorted;
  16066. }
  16067. else {
  16068. this._renderOpaque = RenderingGroup.renderUnsorted;
  16069. }
  16070. },
  16071. enumerable: true,
  16072. configurable: true
  16073. });
  16074. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16075. /**
  16076. * Set the alpha test sort comparison function.
  16077. * If null the sub meshes will be render in the order they were created
  16078. */
  16079. set: function (value) {
  16080. this._alphaTestSortCompareFn = value;
  16081. if (value) {
  16082. this._renderAlphaTest = this.renderAlphaTestSorted;
  16083. }
  16084. else {
  16085. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16086. }
  16087. },
  16088. enumerable: true,
  16089. configurable: true
  16090. });
  16091. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16092. /**
  16093. * Set the transparent sort comparison function.
  16094. * If null the sub meshes will be render in the order they were created
  16095. */
  16096. set: function (value) {
  16097. if (value) {
  16098. this._transparentSortCompareFn = value;
  16099. }
  16100. else {
  16101. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16102. }
  16103. this._renderTransparent = this.renderTransparentSorted;
  16104. },
  16105. enumerable: true,
  16106. configurable: true
  16107. });
  16108. /**
  16109. * Render all the sub meshes contained in the group.
  16110. * @param customRenderFunction Used to override the default render behaviour of the group.
  16111. * @returns true if rendered some submeshes.
  16112. */
  16113. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16114. if (customRenderFunction) {
  16115. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16116. return;
  16117. }
  16118. var engine = this._scene.getEngine();
  16119. // Depth only
  16120. if (this._depthOnlySubMeshes.length !== 0) {
  16121. engine.setAlphaTesting(true);
  16122. engine.setColorWrite(false);
  16123. this._renderAlphaTest(this._depthOnlySubMeshes);
  16124. engine.setAlphaTesting(false);
  16125. engine.setColorWrite(true);
  16126. }
  16127. // Opaque
  16128. if (this._opaqueSubMeshes.length !== 0) {
  16129. this._renderOpaque(this._opaqueSubMeshes);
  16130. }
  16131. // Alpha test
  16132. if (this._alphaTestSubMeshes.length !== 0) {
  16133. engine.setAlphaTesting(true);
  16134. this._renderAlphaTest(this._alphaTestSubMeshes);
  16135. engine.setAlphaTesting(false);
  16136. }
  16137. var stencilState = engine.getStencilBuffer();
  16138. engine.setStencilBuffer(false);
  16139. // Sprites
  16140. if (renderSprites) {
  16141. this._renderSprites();
  16142. }
  16143. // Particles
  16144. if (renderParticles) {
  16145. this._renderParticles(activeMeshes);
  16146. }
  16147. if (this.onBeforeTransparentRendering) {
  16148. this.onBeforeTransparentRendering();
  16149. }
  16150. // Transparent
  16151. if (this._transparentSubMeshes.length !== 0) {
  16152. this._renderTransparent(this._transparentSubMeshes);
  16153. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16154. }
  16155. // Set back stencil to false in case it changes before the edge renderer.
  16156. engine.setStencilBuffer(false);
  16157. // Edges
  16158. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16159. this._edgesRenderers.data[edgesRendererIndex].render();
  16160. }
  16161. // Restore Stencil state.
  16162. engine.setStencilBuffer(stencilState);
  16163. };
  16164. /**
  16165. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16166. * @param subMeshes The submeshes to render
  16167. */
  16168. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16169. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16170. };
  16171. /**
  16172. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16173. * @param subMeshes The submeshes to render
  16174. */
  16175. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16176. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16177. };
  16178. /**
  16179. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16180. * @param subMeshes The submeshes to render
  16181. */
  16182. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16183. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16184. };
  16185. /**
  16186. * Renders the submeshes in a specified order.
  16187. * @param subMeshes The submeshes to sort before render
  16188. * @param sortCompareFn The comparison function use to sort
  16189. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16190. * @param transparent Specifies to activate blending if true
  16191. */
  16192. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16193. var subIndex = 0;
  16194. var subMesh;
  16195. for (; subIndex < subMeshes.length; subIndex++) {
  16196. subMesh = subMeshes.data[subIndex];
  16197. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16198. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16199. }
  16200. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16201. sortedArray.sort(sortCompareFn);
  16202. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16203. subMesh = sortedArray[subIndex];
  16204. if (transparent) {
  16205. var material = subMesh.getMaterial();
  16206. if (material.needDepthPrePass) {
  16207. var engine = material.getScene().getEngine();
  16208. engine.setColorWrite(false);
  16209. engine.setAlphaTesting(true);
  16210. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16211. subMesh.render(false);
  16212. engine.setAlphaTesting(false);
  16213. engine.setColorWrite(true);
  16214. }
  16215. }
  16216. subMesh.render(transparent);
  16217. }
  16218. };
  16219. /**
  16220. * Renders the submeshes in the order they were dispatched (no sort applied).
  16221. * @param subMeshes The submeshes to render
  16222. */
  16223. RenderingGroup.renderUnsorted = function (subMeshes) {
  16224. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16225. var submesh = subMeshes.data[subIndex];
  16226. submesh.render(false);
  16227. }
  16228. };
  16229. /**
  16230. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16231. * are rendered back to front if in the same alpha index.
  16232. *
  16233. * @param a The first submesh
  16234. * @param b The second submesh
  16235. * @returns The result of the comparison
  16236. */
  16237. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16238. // Alpha index first
  16239. if (a._alphaIndex > b._alphaIndex) {
  16240. return 1;
  16241. }
  16242. if (a._alphaIndex < b._alphaIndex) {
  16243. return -1;
  16244. }
  16245. // Then distance to camera
  16246. return RenderingGroup.backToFrontSortCompare(a, b);
  16247. };
  16248. /**
  16249. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16250. * are rendered back to front.
  16251. *
  16252. * @param a The first submesh
  16253. * @param b The second submesh
  16254. * @returns The result of the comparison
  16255. */
  16256. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16257. // Then distance to camera
  16258. if (a._distanceToCamera < b._distanceToCamera) {
  16259. return 1;
  16260. }
  16261. if (a._distanceToCamera > b._distanceToCamera) {
  16262. return -1;
  16263. }
  16264. return 0;
  16265. };
  16266. /**
  16267. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16268. * are rendered front to back (prevent overdraw).
  16269. *
  16270. * @param a The first submesh
  16271. * @param b The second submesh
  16272. * @returns The result of the comparison
  16273. */
  16274. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16275. // Then distance to camera
  16276. if (a._distanceToCamera < b._distanceToCamera) {
  16277. return -1;
  16278. }
  16279. if (a._distanceToCamera > b._distanceToCamera) {
  16280. return 1;
  16281. }
  16282. return 0;
  16283. };
  16284. /**
  16285. * Resets the different lists of submeshes to prepare a new frame.
  16286. */
  16287. RenderingGroup.prototype.prepare = function () {
  16288. this._opaqueSubMeshes.reset();
  16289. this._transparentSubMeshes.reset();
  16290. this._alphaTestSubMeshes.reset();
  16291. this._depthOnlySubMeshes.reset();
  16292. this._particleSystems.reset();
  16293. this._spriteManagers.reset();
  16294. this._edgesRenderers.reset();
  16295. };
  16296. RenderingGroup.prototype.dispose = function () {
  16297. this._opaqueSubMeshes.dispose();
  16298. this._transparentSubMeshes.dispose();
  16299. this._alphaTestSubMeshes.dispose();
  16300. this._depthOnlySubMeshes.dispose();
  16301. this._particleSystems.dispose();
  16302. this._spriteManagers.dispose();
  16303. this._edgesRenderers.dispose();
  16304. };
  16305. /**
  16306. * Inserts the submesh in its correct queue depending on its material.
  16307. * @param subMesh The submesh to dispatch
  16308. */
  16309. RenderingGroup.prototype.dispatch = function (subMesh) {
  16310. var material = subMesh.getMaterial();
  16311. var mesh = subMesh.getMesh();
  16312. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16313. this._transparentSubMeshes.push(subMesh);
  16314. }
  16315. else if (material.needAlphaTesting()) {
  16316. if (material.needDepthPrePass) {
  16317. this._depthOnlySubMeshes.push(subMesh);
  16318. }
  16319. this._alphaTestSubMeshes.push(subMesh);
  16320. }
  16321. else {
  16322. if (material.needDepthPrePass) {
  16323. this._depthOnlySubMeshes.push(subMesh);
  16324. }
  16325. this._opaqueSubMeshes.push(subMesh); // Opaque
  16326. }
  16327. if (mesh._edgesRenderer) {
  16328. this._edgesRenderers.push(mesh._edgesRenderer);
  16329. }
  16330. };
  16331. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16332. this._spriteManagers.push(spriteManager);
  16333. };
  16334. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16335. this._particleSystems.push(particleSystem);
  16336. };
  16337. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16338. if (this._particleSystems.length === 0) {
  16339. return;
  16340. }
  16341. // Particles
  16342. var activeCamera = this._scene.activeCamera;
  16343. this._scene._particlesDuration.beginMonitoring();
  16344. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16345. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16346. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16347. continue;
  16348. }
  16349. var emitter = particleSystem.emitter;
  16350. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16351. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16352. }
  16353. }
  16354. this._scene._particlesDuration.endMonitoring(false);
  16355. };
  16356. RenderingGroup.prototype._renderSprites = function () {
  16357. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16358. return;
  16359. }
  16360. // Sprites
  16361. var activeCamera = this._scene.activeCamera;
  16362. this._scene._spritesDuration.beginMonitoring();
  16363. for (var id = 0; id < this._spriteManagers.length; id++) {
  16364. var spriteManager = this._spriteManagers.data[id];
  16365. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16366. spriteManager.render();
  16367. }
  16368. }
  16369. this._scene._spritesDuration.endMonitoring(false);
  16370. };
  16371. return RenderingGroup;
  16372. }());
  16373. BABYLON.RenderingGroup = RenderingGroup;
  16374. })(BABYLON || (BABYLON = {}));
  16375. //# sourceMappingURL=babylon.renderingGroup.js.map
  16376. var BABYLON;
  16377. (function (BABYLON) {
  16378. var ClickInfo = (function () {
  16379. function ClickInfo() {
  16380. this._singleClick = false;
  16381. this._doubleClick = false;
  16382. this._hasSwiped = false;
  16383. this._ignore = false;
  16384. }
  16385. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16386. get: function () {
  16387. return this._singleClick;
  16388. },
  16389. set: function (b) {
  16390. this._singleClick = b;
  16391. },
  16392. enumerable: true,
  16393. configurable: true
  16394. });
  16395. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16396. get: function () {
  16397. return this._doubleClick;
  16398. },
  16399. set: function (b) {
  16400. this._doubleClick = b;
  16401. },
  16402. enumerable: true,
  16403. configurable: true
  16404. });
  16405. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16406. get: function () {
  16407. return this._hasSwiped;
  16408. },
  16409. set: function (b) {
  16410. this._hasSwiped = b;
  16411. },
  16412. enumerable: true,
  16413. configurable: true
  16414. });
  16415. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16416. get: function () {
  16417. return this._ignore;
  16418. },
  16419. set: function (b) {
  16420. this._ignore = b;
  16421. },
  16422. enumerable: true,
  16423. configurable: true
  16424. });
  16425. return ClickInfo;
  16426. }());
  16427. /**
  16428. * This class is used by the onRenderingGroupObservable
  16429. */
  16430. var RenderingGroupInfo = (function () {
  16431. function RenderingGroupInfo() {
  16432. }
  16433. /**
  16434. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16435. * This stage will be fired no matter what
  16436. */
  16437. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16438. /**
  16439. * Called before opaque object are rendered.
  16440. * This stage will be fired only if there's 3D Opaque content to render
  16441. */
  16442. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16443. /**
  16444. * Called after the opaque objects are rendered and before the transparent ones
  16445. * This stage will be fired only if there's 3D transparent content to render
  16446. */
  16447. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16448. /**
  16449. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16450. * This stage will be fired no matter what
  16451. */
  16452. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16453. return RenderingGroupInfo;
  16454. }());
  16455. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16456. /**
  16457. * Represents a scene to be rendered by the engine.
  16458. * @see http://doc.babylonjs.com/page.php?p=21911
  16459. */
  16460. var Scene = (function () {
  16461. /**
  16462. * @constructor
  16463. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16464. */
  16465. function Scene(engine) {
  16466. // Members
  16467. this.autoClear = true;
  16468. this.autoClearDepthAndStencil = true;
  16469. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16470. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16471. this.forceWireframe = false;
  16472. this._forcePointsCloud = false;
  16473. this.forceShowBoundingBoxes = false;
  16474. this.animationsEnabled = true;
  16475. this.constantlyUpdateMeshUnderPointer = false;
  16476. this.hoverCursor = "pointer";
  16477. this.defaultCursor = "";
  16478. // Metadata
  16479. this.metadata = null;
  16480. /**
  16481. * An event triggered when the scene is disposed.
  16482. * @type {BABYLON.Observable}
  16483. */
  16484. this.onDisposeObservable = new BABYLON.Observable();
  16485. /**
  16486. * An event triggered before rendering the scene
  16487. * @type {BABYLON.Observable}
  16488. */
  16489. this.onBeforeRenderObservable = new BABYLON.Observable();
  16490. /**
  16491. * An event triggered after rendering the scene
  16492. * @type {BABYLON.Observable}
  16493. */
  16494. this.onAfterRenderObservable = new BABYLON.Observable();
  16495. /**
  16496. * An event triggered when the scene is ready
  16497. * @type {BABYLON.Observable}
  16498. */
  16499. this.onReadyObservable = new BABYLON.Observable();
  16500. /**
  16501. * An event triggered before rendering a camera
  16502. * @type {BABYLON.Observable}
  16503. */
  16504. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16505. /**
  16506. * An event triggered after rendering a camera
  16507. * @type {BABYLON.Observable}
  16508. */
  16509. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16510. /**
  16511. * An event triggered when a camera is created
  16512. * @type {BABYLON.Observable}
  16513. */
  16514. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16515. /**
  16516. * An event triggered when a camera is removed
  16517. * @type {BABYLON.Observable}
  16518. */
  16519. this.onCameraRemovedObservable = new BABYLON.Observable();
  16520. /**
  16521. * An event triggered when a light is created
  16522. * @type {BABYLON.Observable}
  16523. */
  16524. this.onNewLightAddedObservable = new BABYLON.Observable();
  16525. /**
  16526. * An event triggered when a light is removed
  16527. * @type {BABYLON.Observable}
  16528. */
  16529. this.onLightRemovedObservable = new BABYLON.Observable();
  16530. /**
  16531. * An event triggered when a geometry is created
  16532. * @type {BABYLON.Observable}
  16533. */
  16534. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16535. /**
  16536. * An event triggered when a geometry is removed
  16537. * @type {BABYLON.Observable}
  16538. */
  16539. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16540. /**
  16541. * An event triggered when a mesh is created
  16542. * @type {BABYLON.Observable}
  16543. */
  16544. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16545. /**
  16546. * An event triggered when a mesh is removed
  16547. * @type {BABYLON.Observable}
  16548. */
  16549. this.onMeshRemovedObservable = new BABYLON.Observable();
  16550. /**
  16551. * An event triggered before calculating deterministic simulation step
  16552. * @type {BABYLON.Observable}
  16553. */
  16554. this.onBeforeStepObservable = new BABYLON.Observable();
  16555. /**
  16556. * An event triggered after calculating deterministic simulation step
  16557. * @type {BABYLON.Observable}
  16558. */
  16559. this.onAfterStepObservable = new BABYLON.Observable();
  16560. /**
  16561. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16562. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16563. * 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)
  16564. */
  16565. this.onRenderingGroupObservable = new BABYLON.Observable();
  16566. // Animations
  16567. this.animations = [];
  16568. /**
  16569. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  16570. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16571. */
  16572. this.onPrePointerObservable = new BABYLON.Observable();
  16573. /**
  16574. * Observable event triggered each time an input event is received from the rendering canvas
  16575. */
  16576. this.onPointerObservable = new BABYLON.Observable();
  16577. this._meshPickProceed = false;
  16578. this._previousHasSwiped = false;
  16579. this._currentPickResult = null;
  16580. this._previousPickResult = null;
  16581. this._isButtonPressed = false;
  16582. this._doubleClickOccured = false;
  16583. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16584. this.cameraToUseForPointers = null;
  16585. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16586. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16587. this._startingPointerTime = 0;
  16588. this._previousStartingPointerTime = 0;
  16589. // Deterministic lockstep
  16590. this._timeAccumulator = 0;
  16591. this._currentStepId = 0;
  16592. this._currentInternalStep = 0;
  16593. // Keyboard
  16594. /**
  16595. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16596. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16597. */
  16598. this.onPreKeyboardObservable = new BABYLON.Observable();
  16599. /**
  16600. * Observable event triggered each time an keyboard event is received from the hosting window
  16601. */
  16602. this.onKeyboardObservable = new BABYLON.Observable();
  16603. // Coordinate system
  16604. /**
  16605. * use right-handed coordinate system on this scene.
  16606. * @type {boolean}
  16607. */
  16608. this._useRightHandedSystem = false;
  16609. // Fog
  16610. this._fogEnabled = true;
  16611. this._fogMode = Scene.FOGMODE_NONE;
  16612. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16613. this.fogDensity = 0.1;
  16614. this.fogStart = 0;
  16615. this.fogEnd = 1000.0;
  16616. // Lights
  16617. /**
  16618. * is shadow enabled on this scene.
  16619. * @type {boolean}
  16620. */
  16621. this._shadowsEnabled = true;
  16622. /**
  16623. * is light enabled on this scene.
  16624. * @type {boolean}
  16625. */
  16626. this._lightsEnabled = true;
  16627. /**
  16628. * All of the lights added to this scene.
  16629. * @see BABYLON.Light
  16630. * @type {BABYLON.Light[]}
  16631. */
  16632. this.lights = new Array();
  16633. // Cameras
  16634. /** All of the cameras added to this scene. */
  16635. this.cameras = new Array();
  16636. /** All of the active cameras added to this scene. */
  16637. this.activeCameras = new Array();
  16638. // Meshes
  16639. /**
  16640. * All of the (abstract) meshes added to this scene.
  16641. * @see BABYLON.AbstractMesh
  16642. * @type {BABYLON.AbstractMesh[]}
  16643. */
  16644. this.meshes = new Array();
  16645. // Geometries
  16646. this._geometries = new Array();
  16647. this.materials = new Array();
  16648. this.multiMaterials = new Array();
  16649. // Textures
  16650. this._texturesEnabled = true;
  16651. this.textures = new Array();
  16652. // Particles
  16653. this.particlesEnabled = true;
  16654. this.particleSystems = new Array();
  16655. // Sprites
  16656. this.spritesEnabled = true;
  16657. this.spriteManagers = new Array();
  16658. // Layers
  16659. this.layers = new Array();
  16660. this.highlightLayers = new Array();
  16661. // Skeletons
  16662. this._skeletonsEnabled = true;
  16663. this.skeletons = new Array();
  16664. // Morph targets
  16665. this.morphTargetManagers = new Array();
  16666. // Lens flares
  16667. this.lensFlaresEnabled = true;
  16668. this.lensFlareSystems = new Array();
  16669. // Collisions
  16670. this.collisionsEnabled = true;
  16671. /** Defines the gravity applied to this scene */
  16672. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16673. // Postprocesses
  16674. this.postProcesses = new Array();
  16675. this.postProcessesEnabled = true;
  16676. // Customs render targets
  16677. this.renderTargetsEnabled = true;
  16678. this.dumpNextRenderTargets = false;
  16679. this.customRenderTargets = new Array();
  16680. // Imported meshes
  16681. this.importedMeshesFiles = new Array();
  16682. // Probes
  16683. this.probesEnabled = true;
  16684. this.reflectionProbes = new Array();
  16685. this._actionManagers = new Array();
  16686. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16687. // Procedural textures
  16688. this.proceduralTexturesEnabled = true;
  16689. this._proceduralTextures = new Array();
  16690. this.soundTracks = new Array();
  16691. this._audioEnabled = true;
  16692. this._headphone = false;
  16693. // Performance counters
  16694. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16695. this._totalLightsCounter = new BABYLON.PerfCounter();
  16696. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16697. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16698. this._totalVertices = new BABYLON.PerfCounter();
  16699. this._activeIndices = new BABYLON.PerfCounter();
  16700. this._activeParticles = new BABYLON.PerfCounter();
  16701. this._interFrameDuration = new BABYLON.PerfCounter();
  16702. this._lastFrameDuration = new BABYLON.PerfCounter();
  16703. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16704. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16705. this._particlesDuration = new BABYLON.PerfCounter();
  16706. this._renderDuration = new BABYLON.PerfCounter();
  16707. this._spritesDuration = new BABYLON.PerfCounter();
  16708. this._activeBones = new BABYLON.PerfCounter();
  16709. this._animationTime = 0;
  16710. this.animationTimeScale = 1;
  16711. this._renderId = 0;
  16712. this._executeWhenReadyTimeoutId = -1;
  16713. this._intermediateRendering = false;
  16714. this._viewUpdateFlag = -1;
  16715. this._projectionUpdateFlag = -1;
  16716. this._alternateViewUpdateFlag = -1;
  16717. this._alternateProjectionUpdateFlag = -1;
  16718. this._toBeDisposed = new BABYLON.SmartArray(256);
  16719. this._pendingData = []; //ANY
  16720. this._activeMeshes = new BABYLON.SmartArray(256);
  16721. this._processedMaterials = new BABYLON.SmartArray(256);
  16722. this._renderTargets = new BABYLON.SmartArray(256);
  16723. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16724. this._activeSkeletons = new BABYLON.SmartArray(32);
  16725. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16726. this._activeAnimatables = new Array();
  16727. this._transformMatrix = BABYLON.Matrix.Zero();
  16728. this._useAlternateCameraConfiguration = false;
  16729. this._alternateRendering = false;
  16730. this.requireLightSorting = false;
  16731. this._uniqueIdCounter = 0;
  16732. this._activeMeshesFrozen = false;
  16733. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16734. this._engine.scenes.push(this);
  16735. this._uid = null;
  16736. this._renderingManager = new BABYLON.RenderingManager(this);
  16737. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16738. if (BABYLON.OutlineRenderer) {
  16739. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16740. }
  16741. this.attachControl();
  16742. //simplification queue
  16743. if (BABYLON.SimplificationQueue) {
  16744. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16745. }
  16746. //collision coordinator initialization. For now legacy per default.
  16747. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16748. // Uniform Buffer
  16749. this._createUbo();
  16750. // Default Image processing definition.
  16751. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16752. }
  16753. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16754. /** The fog is deactivated */
  16755. get: function () {
  16756. return Scene._FOGMODE_NONE;
  16757. },
  16758. enumerable: true,
  16759. configurable: true
  16760. });
  16761. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16762. /** The fog density is following an exponential function */
  16763. get: function () {
  16764. return Scene._FOGMODE_EXP;
  16765. },
  16766. enumerable: true,
  16767. configurable: true
  16768. });
  16769. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16770. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16771. get: function () {
  16772. return Scene._FOGMODE_EXP2;
  16773. },
  16774. enumerable: true,
  16775. configurable: true
  16776. });
  16777. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16778. /** The fog density is following a linear function. */
  16779. get: function () {
  16780. return Scene._FOGMODE_LINEAR;
  16781. },
  16782. enumerable: true,
  16783. configurable: true
  16784. });
  16785. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16786. /**
  16787. * Texture used in all pbr material as the reflection texture.
  16788. * As in the majority of the scene they are the same (exception for multi room and so on),
  16789. * this is easier to reference from here than from all the materials.
  16790. */
  16791. get: function () {
  16792. return this._environmentTexture;
  16793. },
  16794. /**
  16795. * Texture used in all pbr material as the reflection texture.
  16796. * As in the majority of the scene they are the same (exception for multi room and so on),
  16797. * this is easier to set here than in all the materials.
  16798. */
  16799. set: function (value) {
  16800. this._environmentTexture = value;
  16801. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16802. },
  16803. enumerable: true,
  16804. configurable: true
  16805. });
  16806. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16807. /**
  16808. * Default image processing configuration used either in the rendering
  16809. * Forward main pass or through the imageProcessingPostProcess if present.
  16810. * As in the majority of the scene they are the same (exception for multi camera),
  16811. * this is easier to reference from here than from all the materials and post process.
  16812. *
  16813. * No setter as we it is a shared configuration, you can set the values instead.
  16814. */
  16815. get: function () {
  16816. return this._imageProcessingConfiguration;
  16817. },
  16818. enumerable: true,
  16819. configurable: true
  16820. });
  16821. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16822. get: function () {
  16823. return this._forcePointsCloud;
  16824. },
  16825. set: function (value) {
  16826. if (this._forcePointsCloud === value) {
  16827. return;
  16828. }
  16829. this._forcePointsCloud = value;
  16830. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16831. },
  16832. enumerable: true,
  16833. configurable: true
  16834. });
  16835. Object.defineProperty(Scene.prototype, "onDispose", {
  16836. /** A function to be executed when this scene is disposed. */
  16837. set: function (callback) {
  16838. if (this._onDisposeObserver) {
  16839. this.onDisposeObservable.remove(this._onDisposeObserver);
  16840. }
  16841. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16842. },
  16843. enumerable: true,
  16844. configurable: true
  16845. });
  16846. Object.defineProperty(Scene.prototype, "beforeRender", {
  16847. /** A function to be executed before rendering this scene */
  16848. set: function (callback) {
  16849. if (this._onBeforeRenderObserver) {
  16850. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16851. }
  16852. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16853. },
  16854. enumerable: true,
  16855. configurable: true
  16856. });
  16857. Object.defineProperty(Scene.prototype, "afterRender", {
  16858. /** A function to be executed after rendering this scene */
  16859. set: function (callback) {
  16860. if (this._onAfterRenderObserver) {
  16861. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16862. }
  16863. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16864. },
  16865. enumerable: true,
  16866. configurable: true
  16867. });
  16868. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16869. set: function (callback) {
  16870. if (this._onBeforeCameraRenderObserver) {
  16871. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16872. }
  16873. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16874. },
  16875. enumerable: true,
  16876. configurable: true
  16877. });
  16878. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16879. set: function (callback) {
  16880. if (this._onAfterCameraRenderObserver) {
  16881. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16882. }
  16883. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16884. },
  16885. enumerable: true,
  16886. configurable: true
  16887. });
  16888. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16889. get: function () {
  16890. if (!this._gamepadManager) {
  16891. this._gamepadManager = new BABYLON.GamepadManager();
  16892. }
  16893. return this._gamepadManager;
  16894. },
  16895. enumerable: true,
  16896. configurable: true
  16897. });
  16898. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16899. get: function () {
  16900. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16901. },
  16902. enumerable: true,
  16903. configurable: true
  16904. });
  16905. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16906. get: function () {
  16907. return this._useRightHandedSystem;
  16908. },
  16909. set: function (value) {
  16910. if (this._useRightHandedSystem === value) {
  16911. return;
  16912. }
  16913. this._useRightHandedSystem = value;
  16914. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16915. },
  16916. enumerable: true,
  16917. configurable: true
  16918. });
  16919. Scene.prototype.setStepId = function (newStepId) {
  16920. this._currentStepId = newStepId;
  16921. };
  16922. ;
  16923. Scene.prototype.getStepId = function () {
  16924. return this._currentStepId;
  16925. };
  16926. ;
  16927. Scene.prototype.getInternalStep = function () {
  16928. return this._currentInternalStep;
  16929. };
  16930. ;
  16931. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16932. get: function () {
  16933. return this._fogEnabled;
  16934. },
  16935. /**
  16936. * is fog enabled on this scene.
  16937. */
  16938. set: function (value) {
  16939. if (this._fogEnabled === value) {
  16940. return;
  16941. }
  16942. this._fogEnabled = value;
  16943. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16944. },
  16945. enumerable: true,
  16946. configurable: true
  16947. });
  16948. Object.defineProperty(Scene.prototype, "fogMode", {
  16949. get: function () {
  16950. return this._fogMode;
  16951. },
  16952. set: function (value) {
  16953. if (this._fogMode === value) {
  16954. return;
  16955. }
  16956. this._fogMode = value;
  16957. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16958. },
  16959. enumerable: true,
  16960. configurable: true
  16961. });
  16962. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16963. get: function () {
  16964. return this._shadowsEnabled;
  16965. },
  16966. set: function (value) {
  16967. if (this._shadowsEnabled === value) {
  16968. return;
  16969. }
  16970. this._shadowsEnabled = value;
  16971. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16972. },
  16973. enumerable: true,
  16974. configurable: true
  16975. });
  16976. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16977. get: function () {
  16978. return this._lightsEnabled;
  16979. },
  16980. set: function (value) {
  16981. if (this._lightsEnabled === value) {
  16982. return;
  16983. }
  16984. this._lightsEnabled = value;
  16985. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16986. },
  16987. enumerable: true,
  16988. configurable: true
  16989. });
  16990. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16991. /** The default material used on meshes when no material is affected */
  16992. get: function () {
  16993. if (!this._defaultMaterial) {
  16994. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16995. }
  16996. return this._defaultMaterial;
  16997. },
  16998. /** The default material used on meshes when no material is affected */
  16999. set: function (value) {
  17000. this._defaultMaterial = value;
  17001. },
  17002. enumerable: true,
  17003. configurable: true
  17004. });
  17005. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17006. get: function () {
  17007. return this._texturesEnabled;
  17008. },
  17009. set: function (value) {
  17010. if (this._texturesEnabled === value) {
  17011. return;
  17012. }
  17013. this._texturesEnabled = value;
  17014. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17015. },
  17016. enumerable: true,
  17017. configurable: true
  17018. });
  17019. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17020. get: function () {
  17021. return this._skeletonsEnabled;
  17022. },
  17023. set: function (value) {
  17024. if (this._skeletonsEnabled === value) {
  17025. return;
  17026. }
  17027. this._skeletonsEnabled = value;
  17028. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17029. },
  17030. enumerable: true,
  17031. configurable: true
  17032. });
  17033. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17034. get: function () {
  17035. if (!this._postProcessRenderPipelineManager) {
  17036. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17037. }
  17038. return this._postProcessRenderPipelineManager;
  17039. },
  17040. enumerable: true,
  17041. configurable: true
  17042. });
  17043. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17044. get: function () {
  17045. if (!this._mainSoundTrack) {
  17046. // this._mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  17047. }
  17048. return this._mainSoundTrack;
  17049. },
  17050. enumerable: true,
  17051. configurable: true
  17052. });
  17053. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17054. get: function () {
  17055. return this._alternateRendering;
  17056. },
  17057. enumerable: true,
  17058. configurable: true
  17059. });
  17060. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17061. get: function () {
  17062. return this._frustumPlanes;
  17063. },
  17064. enumerable: true,
  17065. configurable: true
  17066. });
  17067. Object.defineProperty(Scene.prototype, "debugLayer", {
  17068. // Properties
  17069. get: function () {
  17070. if (!this._debugLayer) {
  17071. this._debugLayer = new BABYLON.DebugLayer(this);
  17072. }
  17073. return this._debugLayer;
  17074. },
  17075. enumerable: true,
  17076. configurable: true
  17077. });
  17078. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17079. get: function () {
  17080. return this._workerCollisions;
  17081. },
  17082. set: function (enabled) {
  17083. if (!BABYLON.CollisionCoordinatorLegacy) {
  17084. return;
  17085. }
  17086. enabled = (enabled && !!Worker);
  17087. this._workerCollisions = enabled;
  17088. if (this.collisionCoordinator) {
  17089. this.collisionCoordinator.destroy();
  17090. }
  17091. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17092. this.collisionCoordinator.init(this);
  17093. },
  17094. enumerable: true,
  17095. configurable: true
  17096. });
  17097. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17098. get: function () {
  17099. return this._selectionOctree;
  17100. },
  17101. enumerable: true,
  17102. configurable: true
  17103. });
  17104. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17105. /**
  17106. * The mesh that is currently under the pointer.
  17107. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17108. */
  17109. get: function () {
  17110. return this._pointerOverMesh;
  17111. },
  17112. enumerable: true,
  17113. configurable: true
  17114. });
  17115. Object.defineProperty(Scene.prototype, "pointerX", {
  17116. /**
  17117. * Current on-screen X position of the pointer
  17118. * @return {number} X position of the pointer
  17119. */
  17120. get: function () {
  17121. return this._pointerX;
  17122. },
  17123. enumerable: true,
  17124. configurable: true
  17125. });
  17126. Object.defineProperty(Scene.prototype, "pointerY", {
  17127. /**
  17128. * Current on-screen Y position of the pointer
  17129. * @return {number} Y position of the pointer
  17130. */
  17131. get: function () {
  17132. return this._pointerY;
  17133. },
  17134. enumerable: true,
  17135. configurable: true
  17136. });
  17137. Scene.prototype.getCachedMaterial = function () {
  17138. return this._cachedMaterial;
  17139. };
  17140. Scene.prototype.getCachedEffect = function () {
  17141. return this._cachedEffect;
  17142. };
  17143. Scene.prototype.getCachedVisibility = function () {
  17144. return this._cachedVisibility;
  17145. };
  17146. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17147. if (visibility === void 0) { visibility = 1; }
  17148. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17149. };
  17150. Scene.prototype.getBoundingBoxRenderer = function () {
  17151. if (!this._boundingBoxRenderer) {
  17152. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17153. }
  17154. return this._boundingBoxRenderer;
  17155. };
  17156. Scene.prototype.getOutlineRenderer = function () {
  17157. return this._outlineRenderer;
  17158. };
  17159. Scene.prototype.getEngine = function () {
  17160. return this._engine;
  17161. };
  17162. Scene.prototype.getTotalVertices = function () {
  17163. return this._totalVertices.current;
  17164. };
  17165. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17166. get: function () {
  17167. return this._totalVertices;
  17168. },
  17169. enumerable: true,
  17170. configurable: true
  17171. });
  17172. Scene.prototype.getActiveIndices = function () {
  17173. return this._activeIndices.current;
  17174. };
  17175. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17176. get: function () {
  17177. return this._activeIndices;
  17178. },
  17179. enumerable: true,
  17180. configurable: true
  17181. });
  17182. Scene.prototype.getActiveParticles = function () {
  17183. return this._activeParticles.current;
  17184. };
  17185. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17186. get: function () {
  17187. return this._activeParticles;
  17188. },
  17189. enumerable: true,
  17190. configurable: true
  17191. });
  17192. Scene.prototype.getActiveBones = function () {
  17193. return this._activeBones.current;
  17194. };
  17195. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17196. get: function () {
  17197. return this._activeBones;
  17198. },
  17199. enumerable: true,
  17200. configurable: true
  17201. });
  17202. // Stats
  17203. Scene.prototype.getInterFramePerfCounter = function () {
  17204. return this._interFrameDuration.current;
  17205. };
  17206. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17207. get: function () {
  17208. return this._interFrameDuration;
  17209. },
  17210. enumerable: true,
  17211. configurable: true
  17212. });
  17213. Scene.prototype.getLastFrameDuration = function () {
  17214. return this._lastFrameDuration.current;
  17215. };
  17216. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17217. get: function () {
  17218. return this._lastFrameDuration;
  17219. },
  17220. enumerable: true,
  17221. configurable: true
  17222. });
  17223. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17224. return this._evaluateActiveMeshesDuration.current;
  17225. };
  17226. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17227. get: function () {
  17228. return this._evaluateActiveMeshesDuration;
  17229. },
  17230. enumerable: true,
  17231. configurable: true
  17232. });
  17233. Scene.prototype.getActiveMeshes = function () {
  17234. return this._activeMeshes;
  17235. };
  17236. Scene.prototype.getRenderTargetsDuration = function () {
  17237. return this._renderTargetsDuration.current;
  17238. };
  17239. Scene.prototype.getRenderDuration = function () {
  17240. return this._renderDuration.current;
  17241. };
  17242. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17243. get: function () {
  17244. return this._renderDuration;
  17245. },
  17246. enumerable: true,
  17247. configurable: true
  17248. });
  17249. Scene.prototype.getParticlesDuration = function () {
  17250. return this._particlesDuration.current;
  17251. };
  17252. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17253. get: function () {
  17254. return this._particlesDuration;
  17255. },
  17256. enumerable: true,
  17257. configurable: true
  17258. });
  17259. Scene.prototype.getSpritesDuration = function () {
  17260. return this._spritesDuration.current;
  17261. };
  17262. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17263. get: function () {
  17264. return this._spritesDuration;
  17265. },
  17266. enumerable: true,
  17267. configurable: true
  17268. });
  17269. Scene.prototype.getAnimationRatio = function () {
  17270. return this._animationRatio;
  17271. };
  17272. Scene.prototype.getRenderId = function () {
  17273. return this._renderId;
  17274. };
  17275. Scene.prototype.incrementRenderId = function () {
  17276. this._renderId++;
  17277. };
  17278. Scene.prototype._updatePointerPosition = function (evt) {
  17279. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17280. this._pointerX = evt.clientX - canvasRect.left;
  17281. this._pointerY = evt.clientY - canvasRect.top;
  17282. this._unTranslatedPointerX = this._pointerX;
  17283. this._unTranslatedPointerY = this._pointerY;
  17284. };
  17285. Scene.prototype._createUbo = function () {
  17286. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17287. this._sceneUbo.addUniform("viewProjection", 16);
  17288. this._sceneUbo.addUniform("view", 16);
  17289. };
  17290. Scene.prototype._createAlternateUbo = function () {
  17291. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17292. this._alternateSceneUbo.addUniform("viewProjection", 16);
  17293. this._alternateSceneUbo.addUniform("view", 16);
  17294. };
  17295. // Pointers handling
  17296. /**
  17297. * Use this method to simulate a pointer move on a mesh
  17298. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17299. */
  17300. Scene.prototype.simulatePointerMove = function (pickResult) {
  17301. var evt = new PointerEvent("pointermove");
  17302. return this._processPointerMove(pickResult, evt);
  17303. };
  17304. Scene.prototype._processPointerMove = function (pickResult, evt) {
  17305. var canvas = this._engine.getRenderingCanvas();
  17306. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17307. this.setPointerOverSprite(null);
  17308. this.setPointerOverMesh(pickResult.pickedMesh);
  17309. if (this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17310. if (this._pointerOverMesh.actionManager.hoverCursor) {
  17311. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  17312. }
  17313. else {
  17314. canvas.style.cursor = this.hoverCursor;
  17315. }
  17316. }
  17317. else {
  17318. canvas.style.cursor = this.defaultCursor;
  17319. }
  17320. }
  17321. else {
  17322. this.setPointerOverMesh(null);
  17323. // Sprites
  17324. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17325. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17326. this.setPointerOverSprite(pickResult.pickedSprite);
  17327. if (this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  17328. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  17329. }
  17330. else {
  17331. canvas.style.cursor = this.hoverCursor;
  17332. }
  17333. }
  17334. else {
  17335. this.setPointerOverSprite(null);
  17336. // Restore pointer
  17337. canvas.style.cursor = this.defaultCursor;
  17338. }
  17339. }
  17340. if (this.onPointerMove) {
  17341. this.onPointerMove(evt, pickResult);
  17342. }
  17343. if (this.onPointerObservable.hasObservers()) {
  17344. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17345. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17346. this.onPointerObservable.notifyObservers(pi, type);
  17347. }
  17348. return this;
  17349. };
  17350. /**
  17351. * Use this method to simulate a pointer down on a mesh
  17352. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17353. */
  17354. Scene.prototype.simulatePointerDown = function (pickResult) {
  17355. var evt = new PointerEvent("pointerdown");
  17356. return this._processPointerDown(pickResult, evt);
  17357. };
  17358. Scene.prototype._processPointerDown = function (pickResult, evt) {
  17359. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17360. this._pickedDownMesh = pickResult.pickedMesh;
  17361. var actionManager = pickResult.pickedMesh.actionManager;
  17362. if (actionManager) {
  17363. if (actionManager.hasPickTriggers) {
  17364. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17365. switch (evt.button) {
  17366. case 0:
  17367. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17368. break;
  17369. case 1:
  17370. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17371. break;
  17372. case 2:
  17373. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17374. break;
  17375. }
  17376. }
  17377. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17378. window.setTimeout((function () {
  17379. var _this = this;
  17380. 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);
  17381. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17382. if (this._isButtonPressed &&
  17383. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17384. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17385. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17386. this._startingPointerTime = 0;
  17387. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17388. }
  17389. }
  17390. }).bind(this), Scene.LongPressDelay);
  17391. }
  17392. }
  17393. }
  17394. if (this.onPointerDown) {
  17395. this.onPointerDown(evt, pickResult);
  17396. }
  17397. if (this.onPointerObservable.hasObservers()) {
  17398. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17399. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17400. this.onPointerObservable.notifyObservers(pi, type);
  17401. }
  17402. return this;
  17403. };
  17404. /**
  17405. * Use this method to simulate a pointer up on a mesh
  17406. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17407. */
  17408. Scene.prototype.simulatePointerUp = function (pickResult) {
  17409. var evt = new PointerEvent("pointerup");
  17410. var clickInfo = new ClickInfo();
  17411. clickInfo.singleClick = true;
  17412. return this._processPointerUp(pickResult, evt, clickInfo);
  17413. };
  17414. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  17415. if (pickResult && pickResult && pickResult.pickedMesh) {
  17416. this._pickedUpMesh = pickResult.pickedMesh;
  17417. if (this._pickedDownMesh === this._pickedUpMesh) {
  17418. if (this.onPointerPick) {
  17419. this.onPointerPick(evt, pickResult);
  17420. }
  17421. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17422. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17423. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17424. this.onPointerObservable.notifyObservers(pi, type);
  17425. }
  17426. }
  17427. if (pickResult.pickedMesh.actionManager) {
  17428. if (clickInfo.ignore) {
  17429. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17430. }
  17431. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17432. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17433. }
  17434. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17435. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17436. }
  17437. }
  17438. }
  17439. if (this._pickedDownMesh &&
  17440. this._pickedDownMesh.actionManager &&
  17441. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17442. this._pickedDownMesh !== this._pickedUpMesh) {
  17443. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17444. }
  17445. if (this.onPointerUp) {
  17446. this.onPointerUp(evt, pickResult);
  17447. }
  17448. if (this.onPointerObservable.hasObservers()) {
  17449. if (!clickInfo.ignore) {
  17450. if (!clickInfo.hasSwiped) {
  17451. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17452. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17453. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17454. this.onPointerObservable.notifyObservers(pi, type);
  17455. }
  17456. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17457. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17458. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17459. this.onPointerObservable.notifyObservers(pi, type);
  17460. }
  17461. }
  17462. }
  17463. else {
  17464. var type = BABYLON.PointerEventTypes.POINTERUP;
  17465. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17466. this.onPointerObservable.notifyObservers(pi, type);
  17467. }
  17468. }
  17469. return this;
  17470. };
  17471. /**
  17472. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17473. * @param attachUp defines if you want to attach events to pointerup
  17474. * @param attachDown defines if you want to attach events to pointerdown
  17475. * @param attachMove defines if you want to attach events to pointermove
  17476. */
  17477. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17478. var _this = this;
  17479. if (attachUp === void 0) { attachUp = true; }
  17480. if (attachDown === void 0) { attachDown = true; }
  17481. if (attachMove === void 0) { attachMove = true; }
  17482. this._initActionManager = function (act, clickInfo) {
  17483. if (!_this._meshPickProceed) {
  17484. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17485. _this._currentPickResult = pickResult;
  17486. if (pickResult) {
  17487. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17488. }
  17489. _this._meshPickProceed = true;
  17490. }
  17491. return act;
  17492. };
  17493. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17494. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17495. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17496. btn !== _this._previousButtonPressed) {
  17497. _this._doubleClickOccured = false;
  17498. clickInfo.singleClick = true;
  17499. clickInfo.ignore = false;
  17500. cb(clickInfo, _this._currentPickResult);
  17501. }
  17502. };
  17503. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17504. var clickInfo = new ClickInfo();
  17505. _this._currentPickResult = null;
  17506. var act;
  17507. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17508. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17509. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17510. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17511. act = _this._initActionManager(act, clickInfo);
  17512. if (act)
  17513. checkPicking = act.hasPickTriggers;
  17514. }
  17515. if (checkPicking) {
  17516. var btn = evt.button;
  17517. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17518. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17519. if (!clickInfo.hasSwiped) {
  17520. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17521. if (!checkSingleClickImmediately) {
  17522. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17523. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17524. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17525. act = _this._initActionManager(act, clickInfo);
  17526. if (act)
  17527. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17528. }
  17529. }
  17530. if (checkSingleClickImmediately) {
  17531. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17532. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17533. btn !== _this._previousButtonPressed) {
  17534. clickInfo.singleClick = true;
  17535. cb(clickInfo, _this._currentPickResult);
  17536. }
  17537. }
  17538. else {
  17539. // wait that no double click has been raised during the double click delay
  17540. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17541. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17542. }
  17543. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17544. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17545. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17546. act = _this._initActionManager(act, clickInfo);
  17547. if (act)
  17548. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17549. }
  17550. if (checkDoubleClick) {
  17551. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17552. if (btn === _this._previousButtonPressed &&
  17553. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17554. !_this._doubleClickOccured) {
  17555. // pointer has not moved for 2 clicks, it's a double click
  17556. if (!clickInfo.hasSwiped &&
  17557. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17558. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17559. _this._previousStartingPointerTime = 0;
  17560. _this._doubleClickOccured = true;
  17561. clickInfo.doubleClick = true;
  17562. clickInfo.ignore = false;
  17563. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17564. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17565. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17566. cb(clickInfo, _this._currentPickResult);
  17567. }
  17568. else {
  17569. _this._doubleClickOccured = false;
  17570. _this._previousStartingPointerTime = _this._startingPointerTime;
  17571. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17572. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17573. _this._previousButtonPressed = btn;
  17574. _this._previousHasSwiped = clickInfo.hasSwiped;
  17575. if (Scene.ExclusiveDoubleClickMode) {
  17576. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17577. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17578. }
  17579. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17580. cb(clickInfo, _this._previousPickResult);
  17581. }
  17582. else {
  17583. cb(clickInfo, _this._currentPickResult);
  17584. }
  17585. }
  17586. }
  17587. else {
  17588. _this._doubleClickOccured = false;
  17589. _this._previousStartingPointerTime = _this._startingPointerTime;
  17590. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17591. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17592. _this._previousButtonPressed = btn;
  17593. _this._previousHasSwiped = clickInfo.hasSwiped;
  17594. }
  17595. }
  17596. }
  17597. }
  17598. clickInfo.ignore = true;
  17599. cb(clickInfo, _this._currentPickResult);
  17600. };
  17601. this._spritePredicate = function (sprite) {
  17602. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17603. };
  17604. this._onPointerMove = function (evt) {
  17605. _this._updatePointerPosition(evt);
  17606. // PreObservable support
  17607. if (_this.onPrePointerObservable.hasObservers()) {
  17608. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17609. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17610. _this.onPrePointerObservable.notifyObservers(pi, type);
  17611. if (pi.skipOnPointerObservable) {
  17612. return;
  17613. }
  17614. }
  17615. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17616. return;
  17617. }
  17618. if (!_this.pointerMovePredicate) {
  17619. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17620. }
  17621. // Meshes
  17622. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17623. _this._processPointerMove(pickResult, evt);
  17624. };
  17625. this._onPointerDown = function (evt) {
  17626. _this._isButtonPressed = true;
  17627. _this._pickedDownMesh = null;
  17628. _this._meshPickProceed = false;
  17629. _this._updatePointerPosition(evt);
  17630. // PreObservable support
  17631. if (_this.onPrePointerObservable.hasObservers()) {
  17632. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17633. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17634. _this.onPrePointerObservable.notifyObservers(pi, type);
  17635. if (pi.skipOnPointerObservable) {
  17636. return;
  17637. }
  17638. }
  17639. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17640. return;
  17641. }
  17642. _this._startingPointerPosition.x = _this._pointerX;
  17643. _this._startingPointerPosition.y = _this._pointerY;
  17644. _this._startingPointerTime = new Date().getTime();
  17645. if (!_this.pointerDownPredicate) {
  17646. _this.pointerDownPredicate = function (mesh) {
  17647. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17648. };
  17649. }
  17650. // Meshes
  17651. _this._pickedDownMesh = null;
  17652. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17653. _this._processPointerDown(pickResult, evt);
  17654. // Sprites
  17655. _this._pickedDownSprite = null;
  17656. if (_this.spriteManagers.length > 0) {
  17657. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers);
  17658. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17659. if (pickResult.pickedSprite.actionManager) {
  17660. _this._pickedDownSprite = pickResult.pickedSprite;
  17661. switch (evt.button) {
  17662. case 0:
  17663. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17664. break;
  17665. case 1:
  17666. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17667. break;
  17668. case 2:
  17669. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17670. break;
  17671. }
  17672. if (pickResult.pickedSprite.actionManager) {
  17673. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17674. }
  17675. }
  17676. }
  17677. }
  17678. };
  17679. this._onPointerUp = function (evt) {
  17680. _this._isButtonPressed = false;
  17681. _this._pickedUpMesh = null;
  17682. _this._meshPickProceed = false;
  17683. _this._updatePointerPosition(evt);
  17684. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17685. // PreObservable support
  17686. if (this.onPrePointerObservable.hasObservers()) {
  17687. if (!clickInfo.ignore) {
  17688. if (!clickInfo.hasSwiped) {
  17689. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17690. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17691. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17692. this.onPrePointerObservable.notifyObservers(pi, type);
  17693. if (pi.skipOnPointerObservable) {
  17694. return;
  17695. }
  17696. }
  17697. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17698. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17699. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17700. this.onPrePointerObservable.notifyObservers(pi, type);
  17701. if (pi.skipOnPointerObservable) {
  17702. return;
  17703. }
  17704. }
  17705. }
  17706. }
  17707. else {
  17708. var type = BABYLON.PointerEventTypes.POINTERUP;
  17709. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17710. this.onPrePointerObservable.notifyObservers(pi, type);
  17711. if (pi.skipOnPointerObservable) {
  17712. return;
  17713. }
  17714. }
  17715. }
  17716. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17717. return;
  17718. }
  17719. if (!this.pointerUpPredicate) {
  17720. this.pointerUpPredicate = function (mesh) {
  17721. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17722. };
  17723. }
  17724. // Meshes
  17725. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17726. this._initActionManager(null, clickInfo);
  17727. }
  17728. if (!pickResult) {
  17729. pickResult = this._currentPickResult;
  17730. }
  17731. this._processPointerUp(pickResult, evt, clickInfo);
  17732. // Sprites
  17733. if (this.spriteManagers.length > 0) {
  17734. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17735. if (pickResult.hit && pickResult.pickedSprite) {
  17736. if (pickResult.pickedSprite.actionManager) {
  17737. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17738. if (pickResult.pickedSprite.actionManager) {
  17739. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17740. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17741. }
  17742. }
  17743. }
  17744. }
  17745. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17746. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17747. }
  17748. }
  17749. this._previousPickResult = this._currentPickResult;
  17750. }).bind(_this));
  17751. };
  17752. this._onKeyDown = function (evt) {
  17753. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  17754. if (_this.onPreKeyboardObservable.hasObservers()) {
  17755. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17756. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17757. if (pi.skipOnPointerObservable) {
  17758. return;
  17759. }
  17760. }
  17761. if (_this.onKeyboardObservable.hasObservers()) {
  17762. var pi = new BABYLON.KeyboardInfo(type, evt);
  17763. _this.onKeyboardObservable.notifyObservers(pi, type);
  17764. }
  17765. if (_this.actionManager) {
  17766. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17767. }
  17768. };
  17769. this._onKeyUp = function (evt) {
  17770. var type = BABYLON.KeyboardEventTypes.KEYUP;
  17771. if (_this.onPreKeyboardObservable.hasObservers()) {
  17772. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17773. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17774. if (pi.skipOnPointerObservable) {
  17775. return;
  17776. }
  17777. }
  17778. if (_this.onKeyboardObservable.hasObservers()) {
  17779. var pi = new BABYLON.KeyboardInfo(type, evt);
  17780. _this.onKeyboardObservable.notifyObservers(pi, type);
  17781. }
  17782. if (_this.actionManager) {
  17783. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17784. }
  17785. };
  17786. var engine = this.getEngine();
  17787. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  17788. canvas.addEventListener("keydown", _this._onKeyDown, false);
  17789. canvas.addEventListener("keyup", _this._onKeyUp, false);
  17790. });
  17791. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  17792. canvas.removeEventListener("keydown", _this._onKeyDown);
  17793. canvas.removeEventListener("keyup", _this._onKeyUp);
  17794. });
  17795. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17796. var canvas = this._engine.getRenderingCanvas();
  17797. if (attachMove) {
  17798. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17799. // Wheel
  17800. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17801. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17802. }
  17803. if (attachDown) {
  17804. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17805. }
  17806. if (attachUp) {
  17807. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17808. }
  17809. canvas.tabIndex = 1;
  17810. };
  17811. Scene.prototype.detachControl = function () {
  17812. var engine = this.getEngine();
  17813. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17814. var canvas = engine.getRenderingCanvas();
  17815. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17816. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17817. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17818. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  17819. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  17820. // Wheel
  17821. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17822. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17823. // Keyboard
  17824. canvas.removeEventListener("keydown", this._onKeyDown);
  17825. canvas.removeEventListener("keyup", this._onKeyUp);
  17826. // Observables
  17827. this.onKeyboardObservable.clear();
  17828. this.onPreKeyboardObservable.clear();
  17829. this.onPointerObservable.clear();
  17830. this.onPrePointerObservable.clear();
  17831. };
  17832. // Ready
  17833. Scene.prototype.isReady = function () {
  17834. if (this._pendingData.length > 0) {
  17835. return false;
  17836. }
  17837. var index;
  17838. // Geometries
  17839. for (index = 0; index < this._geometries.length; index++) {
  17840. var geometry = this._geometries[index];
  17841. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17842. return false;
  17843. }
  17844. }
  17845. // Meshes
  17846. for (index = 0; index < this.meshes.length; index++) {
  17847. var mesh = this.meshes[index];
  17848. if (!mesh.isEnabled()) {
  17849. continue;
  17850. }
  17851. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17852. continue;
  17853. }
  17854. if (!mesh.isReady()) {
  17855. return false;
  17856. }
  17857. var mat = mesh.material;
  17858. if (mat) {
  17859. if (!mat.isReady(mesh)) {
  17860. return false;
  17861. }
  17862. }
  17863. }
  17864. return true;
  17865. };
  17866. Scene.prototype.resetCachedMaterial = function () {
  17867. this._cachedMaterial = null;
  17868. this._cachedEffect = null;
  17869. this._cachedVisibility = null;
  17870. };
  17871. Scene.prototype.registerBeforeRender = function (func) {
  17872. this.onBeforeRenderObservable.add(func);
  17873. };
  17874. Scene.prototype.unregisterBeforeRender = function (func) {
  17875. this.onBeforeRenderObservable.removeCallback(func);
  17876. };
  17877. Scene.prototype.registerAfterRender = function (func) {
  17878. this.onAfterRenderObservable.add(func);
  17879. };
  17880. Scene.prototype.unregisterAfterRender = function (func) {
  17881. this.onAfterRenderObservable.removeCallback(func);
  17882. };
  17883. Scene.prototype._addPendingData = function (data) {
  17884. this._pendingData.push(data);
  17885. };
  17886. Scene.prototype._removePendingData = function (data) {
  17887. var index = this._pendingData.indexOf(data);
  17888. if (index !== -1) {
  17889. this._pendingData.splice(index, 1);
  17890. }
  17891. };
  17892. Scene.prototype.getWaitingItemsCount = function () {
  17893. return this._pendingData.length;
  17894. };
  17895. /**
  17896. * Registers a function to be executed when the scene is ready.
  17897. * @param {Function} func - the function to be executed.
  17898. */
  17899. Scene.prototype.executeWhenReady = function (func) {
  17900. var _this = this;
  17901. this.onReadyObservable.add(func);
  17902. if (this._executeWhenReadyTimeoutId !== -1) {
  17903. return;
  17904. }
  17905. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17906. _this._checkIsReady();
  17907. }, 150);
  17908. };
  17909. Scene.prototype._checkIsReady = function () {
  17910. var _this = this;
  17911. if (this.isReady()) {
  17912. this.onReadyObservable.notifyObservers(this);
  17913. this.onReadyObservable.clear();
  17914. this._executeWhenReadyTimeoutId = -1;
  17915. return;
  17916. }
  17917. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17918. _this._checkIsReady();
  17919. }, 150);
  17920. };
  17921. // Animations
  17922. /**
  17923. * Will start the animation sequence of a given target
  17924. * @param target - the target
  17925. * @param {number} from - from which frame should animation start
  17926. * @param {number} to - till which frame should animation run.
  17927. * @param {boolean} [loop] - should the animation loop
  17928. * @param {number} [speedRatio] - the speed in which to run the animation
  17929. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17930. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17931. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17932. * See BABYLON.Animatable
  17933. */
  17934. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17935. if (speedRatio === void 0) { speedRatio = 1.0; }
  17936. if (from > to && speedRatio > 0) {
  17937. speedRatio *= -1;
  17938. }
  17939. this.stopAnimation(target);
  17940. if (!animatable) {
  17941. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17942. }
  17943. // Local animations
  17944. if (target.animations) {
  17945. animatable.appendAnimations(target, target.animations);
  17946. }
  17947. // Children animations
  17948. if (target.getAnimatables) {
  17949. var animatables = target.getAnimatables();
  17950. for (var index = 0; index < animatables.length; index++) {
  17951. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17952. }
  17953. }
  17954. animatable.reset();
  17955. return animatable;
  17956. };
  17957. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17958. if (speedRatio === undefined) {
  17959. speedRatio = 1.0;
  17960. }
  17961. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17962. return animatable;
  17963. };
  17964. Scene.prototype.getAnimatableByTarget = function (target) {
  17965. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17966. if (this._activeAnimatables[index].target === target) {
  17967. return this._activeAnimatables[index];
  17968. }
  17969. }
  17970. return null;
  17971. };
  17972. Object.defineProperty(Scene.prototype, "Animatables", {
  17973. get: function () {
  17974. return this._activeAnimatables;
  17975. },
  17976. enumerable: true,
  17977. configurable: true
  17978. });
  17979. /**
  17980. * Will stop the animation of the given target
  17981. * @param target - the target
  17982. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17983. * @see beginAnimation
  17984. */
  17985. Scene.prototype.stopAnimation = function (target, animationName) {
  17986. var animatable = this.getAnimatableByTarget(target);
  17987. if (animatable) {
  17988. animatable.stop(animationName);
  17989. }
  17990. };
  17991. Scene.prototype._animate = function () {
  17992. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17993. return;
  17994. }
  17995. // Getting time
  17996. var now = BABYLON.Tools.Now;
  17997. if (!this._animationTimeLast) {
  17998. if (this._pendingData.length > 0) {
  17999. return;
  18000. }
  18001. this._animationTimeLast = now;
  18002. }
  18003. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18004. this._animationTime += deltaTime;
  18005. this._animationTimeLast = now;
  18006. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18007. this._activeAnimatables[index]._animate(this._animationTime);
  18008. }
  18009. };
  18010. // Matrix
  18011. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18012. this._useAlternateCameraConfiguration = active;
  18013. };
  18014. Scene.prototype.getViewMatrix = function () {
  18015. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18016. };
  18017. Scene.prototype.getProjectionMatrix = function () {
  18018. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18019. };
  18020. Scene.prototype.getTransformMatrix = function () {
  18021. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18022. };
  18023. Scene.prototype.setTransformMatrix = function (view, projection) {
  18024. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18025. return;
  18026. }
  18027. this._viewUpdateFlag = view.updateFlag;
  18028. this._projectionUpdateFlag = projection.updateFlag;
  18029. this._viewMatrix = view;
  18030. this._projectionMatrix = projection;
  18031. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18032. // Update frustum
  18033. if (!this._frustumPlanes) {
  18034. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18035. }
  18036. else {
  18037. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18038. }
  18039. if (this._sceneUbo.useUbo) {
  18040. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18041. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18042. this._sceneUbo.update();
  18043. }
  18044. };
  18045. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18046. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18047. return;
  18048. }
  18049. this._alternateViewUpdateFlag = view.updateFlag;
  18050. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18051. this._alternateViewMatrix = view;
  18052. this._alternateProjectionMatrix = projection;
  18053. if (!this._alternateTransformMatrix) {
  18054. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18055. }
  18056. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18057. if (!this._alternateSceneUbo) {
  18058. this._createAlternateUbo();
  18059. }
  18060. if (this._alternateSceneUbo.useUbo) {
  18061. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18062. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18063. this._alternateSceneUbo.update();
  18064. }
  18065. };
  18066. Scene.prototype.getSceneUniformBuffer = function () {
  18067. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18068. };
  18069. // Methods
  18070. Scene.prototype.getUniqueId = function () {
  18071. var result = this._uniqueIdCounter;
  18072. this._uniqueIdCounter++;
  18073. return result;
  18074. };
  18075. Scene.prototype.addMesh = function (newMesh) {
  18076. newMesh.uniqueId = this.getUniqueId();
  18077. var position = this.meshes.push(newMesh);
  18078. //notify the collision coordinator
  18079. if (this.collisionCoordinator) {
  18080. this.collisionCoordinator.onMeshAdded(newMesh);
  18081. }
  18082. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18083. };
  18084. Scene.prototype.removeMesh = function (toRemove) {
  18085. var index = this.meshes.indexOf(toRemove);
  18086. if (index !== -1) {
  18087. // Remove from the scene if mesh found
  18088. this.meshes.splice(index, 1);
  18089. }
  18090. //notify the collision coordinator
  18091. if (this.collisionCoordinator) {
  18092. this.collisionCoordinator.onMeshRemoved(toRemove);
  18093. }
  18094. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18095. return index;
  18096. };
  18097. Scene.prototype.removeSkeleton = function (toRemove) {
  18098. var index = this.skeletons.indexOf(toRemove);
  18099. if (index !== -1) {
  18100. // Remove from the scene if found
  18101. this.skeletons.splice(index, 1);
  18102. }
  18103. return index;
  18104. };
  18105. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18106. var index = this.morphTargetManagers.indexOf(toRemove);
  18107. if (index !== -1) {
  18108. // Remove from the scene if found
  18109. this.morphTargetManagers.splice(index, 1);
  18110. }
  18111. return index;
  18112. };
  18113. Scene.prototype.removeLight = function (toRemove) {
  18114. var index = this.lights.indexOf(toRemove);
  18115. if (index !== -1) {
  18116. // Remove from the scene if mesh found
  18117. this.lights.splice(index, 1);
  18118. this.sortLightsByPriority();
  18119. }
  18120. this.onLightRemovedObservable.notifyObservers(toRemove);
  18121. return index;
  18122. };
  18123. Scene.prototype.removeCamera = function (toRemove) {
  18124. var index = this.cameras.indexOf(toRemove);
  18125. if (index !== -1) {
  18126. // Remove from the scene if mesh found
  18127. this.cameras.splice(index, 1);
  18128. }
  18129. // Remove from activeCameras
  18130. var index2 = this.activeCameras.indexOf(toRemove);
  18131. if (index2 !== -1) {
  18132. // Remove from the scene if mesh found
  18133. this.activeCameras.splice(index2, 1);
  18134. }
  18135. // Reset the activeCamera
  18136. if (this.activeCamera === toRemove) {
  18137. if (this.cameras.length > 0) {
  18138. this.activeCamera = this.cameras[0];
  18139. }
  18140. else {
  18141. this.activeCamera = null;
  18142. }
  18143. }
  18144. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18145. return index;
  18146. };
  18147. Scene.prototype.addLight = function (newLight) {
  18148. newLight.uniqueId = this.getUniqueId();
  18149. this.lights.push(newLight);
  18150. this.sortLightsByPriority();
  18151. this.onNewLightAddedObservable.notifyObservers(newLight);
  18152. };
  18153. Scene.prototype.sortLightsByPriority = function () {
  18154. if (this.requireLightSorting) {
  18155. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18156. }
  18157. };
  18158. Scene.prototype.addCamera = function (newCamera) {
  18159. newCamera.uniqueId = this.getUniqueId();
  18160. var position = this.cameras.push(newCamera);
  18161. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18162. };
  18163. /**
  18164. * Switch active camera
  18165. * @param {Camera} newCamera - new active camera
  18166. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18167. */
  18168. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18169. if (attachControl === void 0) { attachControl = true; }
  18170. var canvas = this._engine.getRenderingCanvas();
  18171. this.activeCamera.detachControl(canvas);
  18172. this.activeCamera = newCamera;
  18173. if (attachControl) {
  18174. newCamera.attachControl(canvas);
  18175. }
  18176. };
  18177. /**
  18178. * sets the active camera of the scene using its ID
  18179. * @param {string} id - the camera's ID
  18180. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18181. * @see activeCamera
  18182. */
  18183. Scene.prototype.setActiveCameraByID = function (id) {
  18184. var camera = this.getCameraByID(id);
  18185. if (camera) {
  18186. this.activeCamera = camera;
  18187. return camera;
  18188. }
  18189. return null;
  18190. };
  18191. /**
  18192. * sets the active camera of the scene using its name
  18193. * @param {string} name - the camera's name
  18194. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18195. * @see activeCamera
  18196. */
  18197. Scene.prototype.setActiveCameraByName = function (name) {
  18198. var camera = this.getCameraByName(name);
  18199. if (camera) {
  18200. this.activeCamera = camera;
  18201. return camera;
  18202. }
  18203. return null;
  18204. };
  18205. /**
  18206. * get a material using its id
  18207. * @param {string} the material's ID
  18208. * @return {BABYLON.Material|null} the material or null if none found.
  18209. */
  18210. Scene.prototype.getMaterialByID = function (id) {
  18211. for (var index = 0; index < this.materials.length; index++) {
  18212. if (this.materials[index].id === id) {
  18213. return this.materials[index];
  18214. }
  18215. }
  18216. return null;
  18217. };
  18218. /**
  18219. * get a material using its name
  18220. * @param {string} the material's name
  18221. * @return {BABYLON.Material|null} the material or null if none found.
  18222. */
  18223. Scene.prototype.getMaterialByName = function (name) {
  18224. for (var index = 0; index < this.materials.length; index++) {
  18225. if (this.materials[index].name === name) {
  18226. return this.materials[index];
  18227. }
  18228. }
  18229. return null;
  18230. };
  18231. Scene.prototype.getLensFlareSystemByName = function (name) {
  18232. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18233. if (this.lensFlareSystems[index].name === name) {
  18234. return this.lensFlareSystems[index];
  18235. }
  18236. }
  18237. return null;
  18238. };
  18239. Scene.prototype.getLensFlareSystemByID = function (id) {
  18240. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18241. if (this.lensFlareSystems[index].id === id) {
  18242. return this.lensFlareSystems[index];
  18243. }
  18244. }
  18245. return null;
  18246. };
  18247. Scene.prototype.getCameraByID = function (id) {
  18248. for (var index = 0; index < this.cameras.length; index++) {
  18249. if (this.cameras[index].id === id) {
  18250. return this.cameras[index];
  18251. }
  18252. }
  18253. return null;
  18254. };
  18255. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18256. for (var index = 0; index < this.cameras.length; index++) {
  18257. if (this.cameras[index].uniqueId === uniqueId) {
  18258. return this.cameras[index];
  18259. }
  18260. }
  18261. return null;
  18262. };
  18263. /**
  18264. * get a camera using its name
  18265. * @param {string} the camera's name
  18266. * @return {BABYLON.Camera|null} the camera or null if none found.
  18267. */
  18268. Scene.prototype.getCameraByName = function (name) {
  18269. for (var index = 0; index < this.cameras.length; index++) {
  18270. if (this.cameras[index].name === name) {
  18271. return this.cameras[index];
  18272. }
  18273. }
  18274. return null;
  18275. };
  18276. /**
  18277. * get a bone using its id
  18278. * @param {string} the bone's id
  18279. * @return {BABYLON.Bone|null} the bone or null if not found
  18280. */
  18281. Scene.prototype.getBoneByID = function (id) {
  18282. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18283. var skeleton = this.skeletons[skeletonIndex];
  18284. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18285. if (skeleton.bones[boneIndex].id === id) {
  18286. return skeleton.bones[boneIndex];
  18287. }
  18288. }
  18289. }
  18290. return null;
  18291. };
  18292. /**
  18293. * get a bone using its id
  18294. * @param {string} the bone's name
  18295. * @return {BABYLON.Bone|null} the bone or null if not found
  18296. */
  18297. Scene.prototype.getBoneByName = function (name) {
  18298. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18299. var skeleton = this.skeletons[skeletonIndex];
  18300. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18301. if (skeleton.bones[boneIndex].name === name) {
  18302. return skeleton.bones[boneIndex];
  18303. }
  18304. }
  18305. }
  18306. return null;
  18307. };
  18308. /**
  18309. * get a light node using its name
  18310. * @param {string} the light's name
  18311. * @return {BABYLON.Light|null} the light or null if none found.
  18312. */
  18313. Scene.prototype.getLightByName = function (name) {
  18314. for (var index = 0; index < this.lights.length; index++) {
  18315. if (this.lights[index].name === name) {
  18316. return this.lights[index];
  18317. }
  18318. }
  18319. return null;
  18320. };
  18321. /**
  18322. * get a light node using its ID
  18323. * @param {string} the light's id
  18324. * @return {BABYLON.Light|null} the light or null if none found.
  18325. */
  18326. Scene.prototype.getLightByID = function (id) {
  18327. for (var index = 0; index < this.lights.length; index++) {
  18328. if (this.lights[index].id === id) {
  18329. return this.lights[index];
  18330. }
  18331. }
  18332. return null;
  18333. };
  18334. /**
  18335. * get a light node using its scene-generated unique ID
  18336. * @param {number} the light's unique id
  18337. * @return {BABYLON.Light|null} the light or null if none found.
  18338. */
  18339. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18340. for (var index = 0; index < this.lights.length; index++) {
  18341. if (this.lights[index].uniqueId === uniqueId) {
  18342. return this.lights[index];
  18343. }
  18344. }
  18345. return null;
  18346. };
  18347. /**
  18348. * get a particle system by id
  18349. * @param id {number} the particle system id
  18350. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18351. */
  18352. Scene.prototype.getParticleSystemByID = function (id) {
  18353. for (var index = 0; index < this.particleSystems.length; index++) {
  18354. if (this.particleSystems[index].id === id) {
  18355. return this.particleSystems[index];
  18356. }
  18357. }
  18358. return null;
  18359. };
  18360. /**
  18361. * get a geometry using its ID
  18362. * @param {string} the geometry's id
  18363. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18364. */
  18365. Scene.prototype.getGeometryByID = function (id) {
  18366. for (var index = 0; index < this._geometries.length; index++) {
  18367. if (this._geometries[index].id === id) {
  18368. return this._geometries[index];
  18369. }
  18370. }
  18371. return null;
  18372. };
  18373. /**
  18374. * add a new geometry to this scene.
  18375. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18376. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18377. * @return {boolean} was the geometry added or not
  18378. */
  18379. Scene.prototype.pushGeometry = function (geometry, force) {
  18380. if (!force && this.getGeometryByID(geometry.id)) {
  18381. return false;
  18382. }
  18383. this._geometries.push(geometry);
  18384. //notify the collision coordinator
  18385. if (this.collisionCoordinator) {
  18386. this.collisionCoordinator.onGeometryAdded(geometry);
  18387. }
  18388. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18389. return true;
  18390. };
  18391. /**
  18392. * Removes an existing geometry
  18393. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18394. * @return {boolean} was the geometry removed or not
  18395. */
  18396. Scene.prototype.removeGeometry = function (geometry) {
  18397. var index = this._geometries.indexOf(geometry);
  18398. if (index > -1) {
  18399. this._geometries.splice(index, 1);
  18400. //notify the collision coordinator
  18401. if (this.collisionCoordinator) {
  18402. this.collisionCoordinator.onGeometryDeleted(geometry);
  18403. }
  18404. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18405. return true;
  18406. }
  18407. return false;
  18408. };
  18409. Scene.prototype.getGeometries = function () {
  18410. return this._geometries;
  18411. };
  18412. /**
  18413. * Get the first added mesh found of a given ID
  18414. * @param {string} id - the id to search for
  18415. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18416. */
  18417. Scene.prototype.getMeshByID = function (id) {
  18418. for (var index = 0; index < this.meshes.length; index++) {
  18419. if (this.meshes[index].id === id) {
  18420. return this.meshes[index];
  18421. }
  18422. }
  18423. return null;
  18424. };
  18425. Scene.prototype.getMeshesByID = function (id) {
  18426. return this.meshes.filter(function (m) {
  18427. return m.id === id;
  18428. });
  18429. };
  18430. /**
  18431. * Get a mesh with its auto-generated unique id
  18432. * @param {number} uniqueId - the unique id to search for
  18433. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18434. */
  18435. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18436. for (var index = 0; index < this.meshes.length; index++) {
  18437. if (this.meshes[index].uniqueId === uniqueId) {
  18438. return this.meshes[index];
  18439. }
  18440. }
  18441. return null;
  18442. };
  18443. /**
  18444. * Get a the last added mesh found of a given ID
  18445. * @param {string} id - the id to search for
  18446. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18447. */
  18448. Scene.prototype.getLastMeshByID = function (id) {
  18449. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18450. if (this.meshes[index].id === id) {
  18451. return this.meshes[index];
  18452. }
  18453. }
  18454. return null;
  18455. };
  18456. /**
  18457. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18458. * @param {string} id - the id to search for
  18459. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18460. */
  18461. Scene.prototype.getLastEntryByID = function (id) {
  18462. var index;
  18463. for (index = this.meshes.length - 1; index >= 0; index--) {
  18464. if (this.meshes[index].id === id) {
  18465. return this.meshes[index];
  18466. }
  18467. }
  18468. for (index = this.cameras.length - 1; index >= 0; index--) {
  18469. if (this.cameras[index].id === id) {
  18470. return this.cameras[index];
  18471. }
  18472. }
  18473. for (index = this.lights.length - 1; index >= 0; index--) {
  18474. if (this.lights[index].id === id) {
  18475. return this.lights[index];
  18476. }
  18477. }
  18478. return null;
  18479. };
  18480. Scene.prototype.getNodeByID = function (id) {
  18481. var mesh = this.getMeshByID(id);
  18482. if (mesh) {
  18483. return mesh;
  18484. }
  18485. var light = this.getLightByID(id);
  18486. if (light) {
  18487. return light;
  18488. }
  18489. var camera = this.getCameraByID(id);
  18490. if (camera) {
  18491. return camera;
  18492. }
  18493. var bone = this.getBoneByID(id);
  18494. return bone;
  18495. };
  18496. Scene.prototype.getNodeByName = function (name) {
  18497. var mesh = this.getMeshByName(name);
  18498. if (mesh) {
  18499. return mesh;
  18500. }
  18501. var light = this.getLightByName(name);
  18502. if (light) {
  18503. return light;
  18504. }
  18505. var camera = this.getCameraByName(name);
  18506. if (camera) {
  18507. return camera;
  18508. }
  18509. var bone = this.getBoneByName(name);
  18510. return bone;
  18511. };
  18512. Scene.prototype.getMeshByName = function (name) {
  18513. for (var index = 0; index < this.meshes.length; index++) {
  18514. if (this.meshes[index].name === name) {
  18515. return this.meshes[index];
  18516. }
  18517. }
  18518. return null;
  18519. };
  18520. Scene.prototype.getSoundByName = function (name) {
  18521. var index;
  18522. if (BABYLON.AudioEngine) {
  18523. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18524. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18525. return this.mainSoundTrack.soundCollection[index];
  18526. }
  18527. }
  18528. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18529. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18530. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18531. return this.soundTracks[sdIndex].soundCollection[index];
  18532. }
  18533. }
  18534. }
  18535. }
  18536. return null;
  18537. };
  18538. Scene.prototype.getLastSkeletonByID = function (id) {
  18539. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18540. if (this.skeletons[index].id === id) {
  18541. return this.skeletons[index];
  18542. }
  18543. }
  18544. return null;
  18545. };
  18546. Scene.prototype.getSkeletonById = function (id) {
  18547. for (var index = 0; index < this.skeletons.length; index++) {
  18548. if (this.skeletons[index].id === id) {
  18549. return this.skeletons[index];
  18550. }
  18551. }
  18552. return null;
  18553. };
  18554. Scene.prototype.getSkeletonByName = function (name) {
  18555. for (var index = 0; index < this.skeletons.length; index++) {
  18556. if (this.skeletons[index].name === name) {
  18557. return this.skeletons[index];
  18558. }
  18559. }
  18560. return null;
  18561. };
  18562. Scene.prototype.getMorphTargetManagerById = function (id) {
  18563. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18564. if (this.morphTargetManagers[index].uniqueId === id) {
  18565. return this.morphTargetManagers[index];
  18566. }
  18567. }
  18568. return null;
  18569. };
  18570. Scene.prototype.isActiveMesh = function (mesh) {
  18571. return (this._activeMeshes.indexOf(mesh) !== -1);
  18572. };
  18573. /**
  18574. * Return a the first highlight layer of the scene with a given name.
  18575. * @param name The name of the highlight layer to look for.
  18576. * @return The highlight layer if found otherwise null.
  18577. */
  18578. Scene.prototype.getHighlightLayerByName = function (name) {
  18579. for (var index = 0; index < this.highlightLayers.length; index++) {
  18580. if (this.highlightLayers[index].name === name) {
  18581. return this.highlightLayers[index];
  18582. }
  18583. }
  18584. return null;
  18585. };
  18586. Object.defineProperty(Scene.prototype, "uid", {
  18587. /**
  18588. * Return a unique id as a string which can serve as an identifier for the scene
  18589. */
  18590. get: function () {
  18591. if (!this._uid) {
  18592. this._uid = BABYLON.Tools.RandomId();
  18593. }
  18594. return this._uid;
  18595. },
  18596. enumerable: true,
  18597. configurable: true
  18598. });
  18599. /**
  18600. * Add an externaly attached data from its key.
  18601. * This method call will fail and return false, if such key already exists.
  18602. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18603. * @param key the unique key that identifies the data
  18604. * @param data the data object to associate to the key for this Engine instance
  18605. * @return true if no such key were already present and the data was added successfully, false otherwise
  18606. */
  18607. Scene.prototype.addExternalData = function (key, data) {
  18608. if (!this._externalData) {
  18609. this._externalData = new BABYLON.StringDictionary();
  18610. }
  18611. return this._externalData.add(key, data);
  18612. };
  18613. /**
  18614. * Get an externaly attached data from its key
  18615. * @param key the unique key that identifies the data
  18616. * @return the associated data, if present (can be null), or undefined if not present
  18617. */
  18618. Scene.prototype.getExternalData = function (key) {
  18619. if (!this._externalData) {
  18620. return null;
  18621. }
  18622. return this._externalData.get(key);
  18623. };
  18624. /**
  18625. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18626. * @param key the unique key that identifies the data
  18627. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18628. * @return the associated data, can be null if the factory returned null.
  18629. */
  18630. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18631. if (!this._externalData) {
  18632. this._externalData = new BABYLON.StringDictionary();
  18633. }
  18634. return this._externalData.getOrAddWithFactory(key, factory);
  18635. };
  18636. /**
  18637. * Remove an externaly attached data from the Engine instance
  18638. * @param key the unique key that identifies the data
  18639. * @return true if the data was successfully removed, false if it doesn't exist
  18640. */
  18641. Scene.prototype.removeExternalData = function (key) {
  18642. return this._externalData.remove(key);
  18643. };
  18644. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18645. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18646. var material = subMesh.getMaterial();
  18647. if (mesh.showSubMeshesBoundingBox) {
  18648. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18649. }
  18650. if (material) {
  18651. // Render targets
  18652. if (material.getRenderTargetTextures) {
  18653. if (this._processedMaterials.indexOf(material) === -1) {
  18654. this._processedMaterials.push(material);
  18655. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18656. }
  18657. }
  18658. // Dispatch
  18659. this._activeIndices.addCount(subMesh.indexCount, false);
  18660. this._renderingManager.dispatch(subMesh);
  18661. }
  18662. }
  18663. };
  18664. Scene.prototype._isInIntermediateRendering = function () {
  18665. return this._intermediateRendering;
  18666. };
  18667. /**
  18668. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  18669. */
  18670. Scene.prototype.freezeActiveMeshes = function () {
  18671. this._evaluateActiveMeshes();
  18672. this._activeMeshesFrozen = true;
  18673. return this;
  18674. };
  18675. /**
  18676. * Use this function to restart evaluating active meshes on every frame
  18677. */
  18678. Scene.prototype.unfreezeActiveMeshes = function () {
  18679. this._activeMeshesFrozen = false;
  18680. return this;
  18681. };
  18682. Scene.prototype._evaluateActiveMeshes = function () {
  18683. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  18684. return;
  18685. }
  18686. this.activeCamera._activeMeshes.reset();
  18687. this._activeMeshes.reset();
  18688. this._renderingManager.reset();
  18689. this._processedMaterials.reset();
  18690. this._activeParticleSystems.reset();
  18691. this._activeSkeletons.reset();
  18692. this._softwareSkinnedMeshes.reset();
  18693. if (this._boundingBoxRenderer) {
  18694. this._boundingBoxRenderer.reset();
  18695. }
  18696. // Meshes
  18697. var meshes;
  18698. var len;
  18699. if (this._selectionOctree) {
  18700. var selection = this._selectionOctree.select(this._frustumPlanes);
  18701. meshes = selection.data;
  18702. len = selection.length;
  18703. }
  18704. else {
  18705. len = this.meshes.length;
  18706. meshes = this.meshes;
  18707. }
  18708. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18709. var mesh = meshes[meshIndex];
  18710. if (mesh.isBlocked) {
  18711. continue;
  18712. }
  18713. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18714. if (!mesh.isReady() || !mesh.isEnabled()) {
  18715. continue;
  18716. }
  18717. mesh.computeWorldMatrix();
  18718. // Intersections
  18719. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18720. this._meshesForIntersections.pushNoDuplicate(mesh);
  18721. }
  18722. // Switch to current LOD
  18723. var meshLOD = mesh.getLOD(this.activeCamera);
  18724. if (!meshLOD) {
  18725. continue;
  18726. }
  18727. mesh._preActivate();
  18728. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18729. this._activeMeshes.push(mesh);
  18730. this.activeCamera._activeMeshes.push(mesh);
  18731. mesh._activate(this._renderId);
  18732. if (meshLOD !== mesh) {
  18733. meshLOD._activate(this._renderId);
  18734. }
  18735. this._activeMesh(mesh, meshLOD);
  18736. }
  18737. }
  18738. // Particle systems
  18739. this._particlesDuration.beginMonitoring();
  18740. var beforeParticlesDate = BABYLON.Tools.Now;
  18741. if (this.particlesEnabled) {
  18742. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18743. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18744. var particleSystem = this.particleSystems[particleIndex];
  18745. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18746. continue;
  18747. }
  18748. var emitter = particleSystem.emitter;
  18749. if (!emitter.position || emitter.isEnabled()) {
  18750. this._activeParticleSystems.push(particleSystem);
  18751. particleSystem.animate();
  18752. this._renderingManager.dispatchParticles(particleSystem);
  18753. }
  18754. }
  18755. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18756. }
  18757. this._particlesDuration.endMonitoring(false);
  18758. };
  18759. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18760. if (mesh.skeleton && this.skeletonsEnabled) {
  18761. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18762. mesh.skeleton.prepare();
  18763. }
  18764. if (!mesh.computeBonesUsingShaders) {
  18765. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18766. }
  18767. }
  18768. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18769. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18770. }
  18771. if (mesh && mesh.subMeshes) {
  18772. // Submeshes Octrees
  18773. var len;
  18774. var subMeshes;
  18775. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18776. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18777. len = intersections.length;
  18778. subMeshes = intersections.data;
  18779. }
  18780. else {
  18781. subMeshes = mesh.subMeshes;
  18782. len = subMeshes.length;
  18783. }
  18784. for (var subIndex = 0; subIndex < len; subIndex++) {
  18785. var subMesh = subMeshes[subIndex];
  18786. this._evaluateSubMesh(subMesh, mesh);
  18787. }
  18788. }
  18789. };
  18790. Scene.prototype.updateTransformMatrix = function (force) {
  18791. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18792. };
  18793. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  18794. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  18795. };
  18796. Scene.prototype._renderForCamera = function (camera) {
  18797. if (camera && camera._skipRendering) {
  18798. return;
  18799. }
  18800. var engine = this._engine;
  18801. var startTime = BABYLON.Tools.Now;
  18802. this.activeCamera = camera;
  18803. if (!this.activeCamera)
  18804. throw new Error("Active camera not set");
  18805. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18806. // Viewport
  18807. engine.setViewport(this.activeCamera.viewport);
  18808. // Camera
  18809. this.resetCachedMaterial();
  18810. this._renderId++;
  18811. this.activeCamera.update();
  18812. this.updateTransformMatrix();
  18813. if (camera._alternateCamera) {
  18814. this.updateAlternateTransformMatrix(camera._alternateCamera);
  18815. this._alternateRendering = true;
  18816. }
  18817. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18818. // Meshes
  18819. this._evaluateActiveMeshesDuration.beginMonitoring();
  18820. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18821. this._evaluateActiveMeshes();
  18822. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18823. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18824. // Software skinning
  18825. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18826. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18827. mesh.applySkeleton(mesh.skeleton);
  18828. }
  18829. // Render targets
  18830. this._renderTargetsDuration.beginMonitoring();
  18831. var needsRestoreFrameBuffer = false;
  18832. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18833. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18834. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18835. }
  18836. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18837. this._intermediateRendering = true;
  18838. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18839. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18840. var renderTarget = this._renderTargets.data[renderIndex];
  18841. if (renderTarget._shouldRender()) {
  18842. this._renderId++;
  18843. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18844. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18845. }
  18846. }
  18847. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18848. this._intermediateRendering = false;
  18849. this._renderId++;
  18850. needsRestoreFrameBuffer = true; // Restore back buffer
  18851. }
  18852. // Render HighlightLayer Texture
  18853. var stencilState = this._engine.getStencilBuffer();
  18854. var renderhighlights = false;
  18855. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18856. this._intermediateRendering = true;
  18857. for (var i = 0; i < this.highlightLayers.length; i++) {
  18858. var highlightLayer = this.highlightLayers[i];
  18859. if (highlightLayer.shouldRender() &&
  18860. (!highlightLayer.camera ||
  18861. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18862. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18863. renderhighlights = true;
  18864. var renderTarget = highlightLayer._mainTexture;
  18865. if (renderTarget._shouldRender()) {
  18866. this._renderId++;
  18867. renderTarget.render(false, false);
  18868. needsRestoreFrameBuffer = true;
  18869. }
  18870. }
  18871. }
  18872. this._intermediateRendering = false;
  18873. this._renderId++;
  18874. }
  18875. if (needsRestoreFrameBuffer) {
  18876. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18877. }
  18878. this._renderTargetsDuration.endMonitoring(false);
  18879. // Prepare Frame
  18880. this.postProcessManager._prepareFrame();
  18881. this._renderDuration.beginMonitoring();
  18882. // Backgrounds
  18883. var layerIndex;
  18884. var layer;
  18885. if (this.layers.length) {
  18886. engine.setDepthBuffer(false);
  18887. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18888. layer = this.layers[layerIndex];
  18889. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18890. layer.render();
  18891. }
  18892. }
  18893. engine.setDepthBuffer(true);
  18894. }
  18895. // Render
  18896. BABYLON.Tools.StartPerformanceCounter("Main render");
  18897. // Activate HighlightLayer stencil
  18898. if (renderhighlights) {
  18899. this._engine.setStencilBuffer(true);
  18900. }
  18901. this._renderingManager.render(null, null, true, true);
  18902. // Restore HighlightLayer stencil
  18903. if (renderhighlights) {
  18904. this._engine.setStencilBuffer(stencilState);
  18905. }
  18906. BABYLON.Tools.EndPerformanceCounter("Main render");
  18907. // Bounding boxes
  18908. if (this._boundingBoxRenderer) {
  18909. this._boundingBoxRenderer.render();
  18910. }
  18911. // Lens flares
  18912. if (this.lensFlaresEnabled) {
  18913. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18914. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18915. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18916. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18917. lensFlareSystem.render();
  18918. }
  18919. }
  18920. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18921. }
  18922. // Foregrounds
  18923. if (this.layers.length) {
  18924. engine.setDepthBuffer(false);
  18925. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18926. layer = this.layers[layerIndex];
  18927. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18928. layer.render();
  18929. }
  18930. }
  18931. engine.setDepthBuffer(true);
  18932. }
  18933. // Highlight Layer
  18934. if (renderhighlights) {
  18935. engine.setDepthBuffer(false);
  18936. for (var i = 0; i < this.highlightLayers.length; i++) {
  18937. if (this.highlightLayers[i].shouldRender()) {
  18938. this.highlightLayers[i].render();
  18939. }
  18940. }
  18941. engine.setDepthBuffer(true);
  18942. }
  18943. this._renderDuration.endMonitoring(false);
  18944. // Finalize frame
  18945. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18946. // Reset some special arrays
  18947. this._renderTargets.reset();
  18948. this._alternateRendering = false;
  18949. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18950. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18951. };
  18952. Scene.prototype._processSubCameras = function (camera) {
  18953. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18954. this._renderForCamera(camera);
  18955. return;
  18956. }
  18957. // Update camera
  18958. this.activeCamera.update();
  18959. // rig cameras
  18960. for (var index = 0; index < camera._rigCameras.length; index++) {
  18961. this._renderForCamera(camera._rigCameras[index]);
  18962. }
  18963. this.activeCamera = camera;
  18964. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18965. };
  18966. Scene.prototype._checkIntersections = function () {
  18967. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18968. var sourceMesh = this._meshesForIntersections.data[index];
  18969. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18970. var action = sourceMesh.actionManager.actions[actionIndex];
  18971. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18972. var parameters = action.getTriggerParameter();
  18973. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18974. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18975. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18976. if (areIntersecting && currentIntersectionInProgress === -1) {
  18977. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18978. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18979. sourceMesh._intersectionsInProgress.push(otherMesh);
  18980. }
  18981. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18982. sourceMesh._intersectionsInProgress.push(otherMesh);
  18983. }
  18984. }
  18985. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18986. //They intersected, and now they don't.
  18987. //is this trigger an exit trigger? execute an event.
  18988. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18989. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18990. }
  18991. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18992. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18993. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18994. }
  18995. }
  18996. }
  18997. }
  18998. }
  18999. };
  19000. Scene.prototype.render = function () {
  19001. if (this.isDisposed) {
  19002. return;
  19003. }
  19004. this._interFrameDuration.endMonitoring();
  19005. this._lastFrameDuration.beginMonitoring();
  19006. this._particlesDuration.fetchNewFrame();
  19007. this._spritesDuration.fetchNewFrame();
  19008. this._activeParticles.fetchNewFrame();
  19009. this._renderDuration.fetchNewFrame();
  19010. this._renderTargetsDuration.fetchNewFrame();
  19011. this._evaluateActiveMeshesDuration.fetchNewFrame();
  19012. this._totalVertices.fetchNewFrame();
  19013. this._activeIndices.fetchNewFrame();
  19014. this._activeBones.fetchNewFrame();
  19015. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19016. this._meshesForIntersections.reset();
  19017. this.resetCachedMaterial();
  19018. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19019. // Actions
  19020. if (this.actionManager) {
  19021. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  19022. }
  19023. //Simplification Queue
  19024. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19025. this.simplificationQueue.executeNext();
  19026. }
  19027. if (this._engine.isDeterministicLockStep()) {
  19028. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19029. var defaultTimeStep = (60.0 / 1000.0);
  19030. if (this._physicsEngine) {
  19031. defaultTimeStep = this._physicsEngine.getTimeStep();
  19032. }
  19033. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19034. this._timeAccumulator += deltaTime;
  19035. // compute the amount of fixed steps we should have taken since the last step
  19036. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19037. internalSteps = Math.min(internalSteps, maxSubSteps);
  19038. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19039. this.onBeforeStepObservable.notifyObservers(this);
  19040. // Animations
  19041. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19042. this._animate();
  19043. // Physics
  19044. if (this._physicsEngine) {
  19045. BABYLON.Tools.StartPerformanceCounter("Physics");
  19046. this._physicsEngine._step(defaultTimeStep);
  19047. BABYLON.Tools.EndPerformanceCounter("Physics");
  19048. }
  19049. this._timeAccumulator -= defaultTimeStep;
  19050. this.onAfterStepObservable.notifyObservers(this);
  19051. this._currentStepId++;
  19052. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19053. this._evaluateActiveMeshes();
  19054. }
  19055. }
  19056. }
  19057. else {
  19058. // Animations
  19059. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19060. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19061. this._animate();
  19062. // Physics
  19063. if (this._physicsEngine) {
  19064. BABYLON.Tools.StartPerformanceCounter("Physics");
  19065. this._physicsEngine._step(deltaTime / 1000.0);
  19066. BABYLON.Tools.EndPerformanceCounter("Physics");
  19067. }
  19068. }
  19069. // Before render
  19070. this.onBeforeRenderObservable.notifyObservers(this);
  19071. // Customs render targets
  19072. this._renderTargetsDuration.beginMonitoring();
  19073. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19074. var engine = this.getEngine();
  19075. var currentActiveCamera = this.activeCamera;
  19076. if (this.renderTargetsEnabled) {
  19077. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19078. this._intermediateRendering = true;
  19079. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19080. var renderTarget = this.customRenderTargets[customIndex];
  19081. if (renderTarget._shouldRender()) {
  19082. this._renderId++;
  19083. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19084. if (!this.activeCamera)
  19085. throw new Error("Active camera not set");
  19086. // Viewport
  19087. engine.setViewport(this.activeCamera.viewport);
  19088. // Camera
  19089. this.updateTransformMatrix();
  19090. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19091. }
  19092. }
  19093. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19094. this._intermediateRendering = false;
  19095. this._renderId++;
  19096. }
  19097. // Restore back buffer
  19098. if (this.customRenderTargets.length > 0) {
  19099. engine.restoreDefaultFramebuffer();
  19100. }
  19101. this._renderTargetsDuration.endMonitoring();
  19102. this.activeCamera = currentActiveCamera;
  19103. // Procedural textures
  19104. if (this.proceduralTexturesEnabled) {
  19105. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19106. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19107. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19108. if (proceduralTexture._shouldRender()) {
  19109. proceduralTexture.render();
  19110. }
  19111. }
  19112. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19113. }
  19114. // Clear
  19115. if (this.autoClearDepthAndStencil || this.autoClear) {
  19116. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19117. }
  19118. // Shadows
  19119. if (this.shadowsEnabled) {
  19120. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19121. var light = this.lights[lightIndex];
  19122. var shadowGenerator = light.getShadowGenerator();
  19123. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19124. var shadowMap = shadowGenerator.getShadowMap();
  19125. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  19126. this._renderTargets.push(shadowMap);
  19127. }
  19128. }
  19129. }
  19130. }
  19131. // Depth renderer
  19132. if (this._depthRenderer) {
  19133. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19134. }
  19135. // Geometry renderer
  19136. if (this._geometryBufferRenderer) {
  19137. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19138. }
  19139. // RenderPipeline
  19140. if (this._postProcessRenderPipelineManager) {
  19141. this._postProcessRenderPipelineManager.update();
  19142. }
  19143. // Multi-cameras?
  19144. if (this.activeCameras.length > 0) {
  19145. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19146. if (cameraIndex > 0) {
  19147. this._engine.clear(null, false, true, true);
  19148. }
  19149. this._processSubCameras(this.activeCameras[cameraIndex]);
  19150. }
  19151. }
  19152. else {
  19153. if (!this.activeCamera) {
  19154. throw new Error("No camera defined");
  19155. }
  19156. this._processSubCameras(this.activeCamera);
  19157. }
  19158. // Intersection checks
  19159. this._checkIntersections();
  19160. // Update the audio listener attached to the camera
  19161. if (BABYLON.AudioEngine) {
  19162. this._updateAudioParameters();
  19163. }
  19164. // After render
  19165. if (this.afterRender) {
  19166. this.afterRender();
  19167. }
  19168. this.onAfterRenderObservable.notifyObservers(this);
  19169. // Cleaning
  19170. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19171. this._toBeDisposed.data[index].dispose();
  19172. this._toBeDisposed[index] = null;
  19173. }
  19174. this._toBeDisposed.reset();
  19175. if (this.dumpNextRenderTargets) {
  19176. this.dumpNextRenderTargets = false;
  19177. }
  19178. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19179. this._interFrameDuration.beginMonitoring();
  19180. this._lastFrameDuration.endMonitoring();
  19181. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19182. this._totalLightsCounter.addCount(this.lights.length, true);
  19183. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19184. this._totalTexturesCounter.addCount(this.textures.length, true);
  19185. this._activeBones.addCount(0, true);
  19186. this._activeIndices.addCount(0, true);
  19187. this._activeParticles.addCount(0, true);
  19188. };
  19189. Scene.prototype._updateAudioParameters = function () {
  19190. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19191. return;
  19192. }
  19193. var listeningCamera;
  19194. var audioEngine = BABYLON.Engine.audioEngine;
  19195. if (this.activeCameras.length > 0) {
  19196. listeningCamera = this.activeCameras[0];
  19197. }
  19198. else {
  19199. listeningCamera = this.activeCamera;
  19200. }
  19201. if (listeningCamera && audioEngine.canUseWebAudio) {
  19202. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19203. // for VR cameras
  19204. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  19205. listeningCamera = listeningCamera.rigCameras[0];
  19206. }
  19207. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19208. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19209. cameraDirection.normalize();
  19210. // To avoid some errors on GearVR
  19211. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  19212. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19213. }
  19214. var i;
  19215. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19216. var sound = this.mainSoundTrack.soundCollection[i];
  19217. if (sound.useCustomAttenuation) {
  19218. sound.updateDistanceFromListener();
  19219. }
  19220. }
  19221. for (i = 0; i < this.soundTracks.length; i++) {
  19222. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19223. sound = this.soundTracks[i].soundCollection[j];
  19224. if (sound.useCustomAttenuation) {
  19225. sound.updateDistanceFromListener();
  19226. }
  19227. }
  19228. }
  19229. }
  19230. };
  19231. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19232. // Audio
  19233. get: function () {
  19234. return this._audioEnabled;
  19235. },
  19236. set: function (value) {
  19237. this._audioEnabled = value;
  19238. if (BABYLON.AudioEngine) {
  19239. if (this._audioEnabled) {
  19240. this._enableAudio();
  19241. }
  19242. else {
  19243. this._disableAudio();
  19244. }
  19245. }
  19246. },
  19247. enumerable: true,
  19248. configurable: true
  19249. });
  19250. Scene.prototype._disableAudio = function () {
  19251. var i;
  19252. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19253. this.mainSoundTrack.soundCollection[i].pause();
  19254. }
  19255. for (i = 0; i < this.soundTracks.length; i++) {
  19256. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19257. this.soundTracks[i].soundCollection[j].pause();
  19258. }
  19259. }
  19260. };
  19261. Scene.prototype._enableAudio = function () {
  19262. var i;
  19263. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19264. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19265. this.mainSoundTrack.soundCollection[i].play();
  19266. }
  19267. }
  19268. for (i = 0; i < this.soundTracks.length; i++) {
  19269. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19270. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19271. this.soundTracks[i].soundCollection[j].play();
  19272. }
  19273. }
  19274. }
  19275. };
  19276. Object.defineProperty(Scene.prototype, "headphone", {
  19277. get: function () {
  19278. return this._headphone;
  19279. },
  19280. set: function (value) {
  19281. this._headphone = value;
  19282. if (BABYLON.AudioEngine) {
  19283. if (this._headphone) {
  19284. this._switchAudioModeForHeadphones();
  19285. }
  19286. else {
  19287. this._switchAudioModeForNormalSpeakers();
  19288. }
  19289. }
  19290. },
  19291. enumerable: true,
  19292. configurable: true
  19293. });
  19294. Scene.prototype._switchAudioModeForHeadphones = function () {
  19295. this.mainSoundTrack.switchPanningModelToHRTF();
  19296. for (var i = 0; i < this.soundTracks.length; i++) {
  19297. this.soundTracks[i].switchPanningModelToHRTF();
  19298. }
  19299. };
  19300. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19301. this.mainSoundTrack.switchPanningModelToEqualPower();
  19302. for (var i = 0; i < this.soundTracks.length; i++) {
  19303. this.soundTracks[i].switchPanningModelToEqualPower();
  19304. }
  19305. };
  19306. Scene.prototype.enableDepthRenderer = function () {
  19307. if (this._depthRenderer) {
  19308. return this._depthRenderer;
  19309. }
  19310. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19311. return this._depthRenderer;
  19312. };
  19313. Scene.prototype.disableDepthRenderer = function () {
  19314. if (!this._depthRenderer) {
  19315. return;
  19316. }
  19317. this._depthRenderer.dispose();
  19318. this._depthRenderer = null;
  19319. };
  19320. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19321. if (ratio === void 0) { ratio = 1; }
  19322. if (this._geometryBufferRenderer) {
  19323. return this._geometryBufferRenderer;
  19324. }
  19325. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19326. if (!this._geometryBufferRenderer.isSupported) {
  19327. this._geometryBufferRenderer = null;
  19328. }
  19329. return this._geometryBufferRenderer;
  19330. };
  19331. Scene.prototype.disableGeometryBufferRenderer = function () {
  19332. if (!this._geometryBufferRenderer) {
  19333. return;
  19334. }
  19335. this._geometryBufferRenderer.dispose();
  19336. this._geometryBufferRenderer = null;
  19337. };
  19338. Scene.prototype.freezeMaterials = function () {
  19339. for (var i = 0; i < this.materials.length; i++) {
  19340. this.materials[i].freeze();
  19341. }
  19342. };
  19343. Scene.prototype.unfreezeMaterials = function () {
  19344. for (var i = 0; i < this.materials.length; i++) {
  19345. this.materials[i].unfreeze();
  19346. }
  19347. };
  19348. Scene.prototype.dispose = function () {
  19349. this.beforeRender = null;
  19350. this.afterRender = null;
  19351. this.skeletons = [];
  19352. this.morphTargetManagers = [];
  19353. this.importedMeshesFiles = new Array();
  19354. this.resetCachedMaterial();
  19355. if (this._depthRenderer) {
  19356. this._depthRenderer.dispose();
  19357. }
  19358. if (this._gamepadManager) {
  19359. this._gamepadManager.dispose();
  19360. this._gamepadManager = null;
  19361. }
  19362. // Smart arrays
  19363. if (this.activeCamera) {
  19364. this.activeCamera._activeMeshes.dispose();
  19365. this.activeCamera = null;
  19366. }
  19367. this._activeMeshes.dispose();
  19368. this._renderingManager.dispose();
  19369. this._processedMaterials.dispose();
  19370. this._activeParticleSystems.dispose();
  19371. this._activeSkeletons.dispose();
  19372. this._softwareSkinnedMeshes.dispose();
  19373. this._renderTargets.dispose();
  19374. if (this._boundingBoxRenderer) {
  19375. this._boundingBoxRenderer.dispose();
  19376. }
  19377. this._meshesForIntersections.dispose();
  19378. this._toBeDisposed.dispose();
  19379. // Debug layer
  19380. if (this._debugLayer) {
  19381. this._debugLayer.hide();
  19382. }
  19383. // Events
  19384. this.onDisposeObservable.notifyObservers(this);
  19385. this.onDisposeObservable.clear();
  19386. this.onBeforeRenderObservable.clear();
  19387. this.onAfterRenderObservable.clear();
  19388. this.detachControl();
  19389. // Release sounds & sounds tracks
  19390. if (BABYLON.AudioEngine) {
  19391. this.disposeSounds();
  19392. }
  19393. // VR Helper
  19394. if (this.VRHelper) {
  19395. this.VRHelper.dispose();
  19396. }
  19397. // Detach cameras
  19398. var canvas = this._engine.getRenderingCanvas();
  19399. var index;
  19400. for (index = 0; index < this.cameras.length; index++) {
  19401. this.cameras[index].detachControl(canvas);
  19402. }
  19403. // Release lights
  19404. while (this.lights.length) {
  19405. this.lights[0].dispose();
  19406. }
  19407. // Release meshes
  19408. while (this.meshes.length) {
  19409. this.meshes[0].dispose(true);
  19410. }
  19411. // Release cameras
  19412. while (this.cameras.length) {
  19413. this.cameras[0].dispose();
  19414. }
  19415. // Release materials
  19416. if (this.defaultMaterial) {
  19417. this.defaultMaterial.dispose();
  19418. }
  19419. while (this.multiMaterials.length) {
  19420. this.multiMaterials[0].dispose();
  19421. }
  19422. while (this.materials.length) {
  19423. this.materials[0].dispose();
  19424. }
  19425. // Release particles
  19426. while (this.particleSystems.length) {
  19427. this.particleSystems[0].dispose();
  19428. }
  19429. // Release sprites
  19430. while (this.spriteManagers.length) {
  19431. this.spriteManagers[0].dispose();
  19432. }
  19433. // Release postProcesses
  19434. while (this.postProcesses.length) {
  19435. this.postProcesses[0].dispose();
  19436. }
  19437. // Release layers
  19438. while (this.layers.length) {
  19439. this.layers[0].dispose();
  19440. }
  19441. while (this.highlightLayers.length) {
  19442. this.highlightLayers[0].dispose();
  19443. }
  19444. // Release textures
  19445. while (this.textures.length) {
  19446. this.textures[0].dispose();
  19447. }
  19448. // Release UBO
  19449. this._sceneUbo.dispose();
  19450. if (this._alternateSceneUbo) {
  19451. this._alternateSceneUbo.dispose();
  19452. }
  19453. // Post-processes
  19454. this.postProcessManager.dispose();
  19455. if (this._postProcessRenderPipelineManager) {
  19456. this._postProcessRenderPipelineManager.dispose();
  19457. }
  19458. // Physics
  19459. if (this._physicsEngine) {
  19460. this.disablePhysicsEngine();
  19461. }
  19462. // Remove from engine
  19463. index = this._engine.scenes.indexOf(this);
  19464. if (index > -1) {
  19465. this._engine.scenes.splice(index, 1);
  19466. }
  19467. this._engine.wipeCaches();
  19468. this._engine = null;
  19469. this.defaultMaterial = null;
  19470. this.multiMaterials = null;
  19471. this.materials = null;
  19472. };
  19473. Object.defineProperty(Scene.prototype, "isDisposed", {
  19474. get: function () {
  19475. return !this._engine;
  19476. },
  19477. enumerable: true,
  19478. configurable: true
  19479. });
  19480. // Release sounds & sounds tracks
  19481. Scene.prototype.disposeSounds = function () {
  19482. if (!this._mainSoundTrack) {
  19483. return;
  19484. }
  19485. this.mainSoundTrack.dispose();
  19486. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19487. this.soundTracks[scIndex].dispose();
  19488. }
  19489. };
  19490. // Octrees
  19491. Scene.prototype.getWorldExtends = function () {
  19492. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19493. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19494. for (var index = 0; index < this.meshes.length; index++) {
  19495. var mesh = this.meshes[index];
  19496. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19497. continue;
  19498. }
  19499. mesh.computeWorldMatrix(true);
  19500. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19501. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19502. BABYLON.Tools.CheckExtends(minBox, min, max);
  19503. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19504. }
  19505. return {
  19506. min: min,
  19507. max: max
  19508. };
  19509. };
  19510. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19511. if (maxCapacity === void 0) { maxCapacity = 64; }
  19512. if (maxDepth === void 0) { maxDepth = 2; }
  19513. if (!this._selectionOctree) {
  19514. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19515. }
  19516. var worldExtends = this.getWorldExtends();
  19517. // Update octree
  19518. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19519. return this._selectionOctree;
  19520. };
  19521. // Picking
  19522. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19523. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19524. var engine = this._engine;
  19525. if (!camera) {
  19526. if (!this.activeCamera)
  19527. throw new Error("Active camera not set");
  19528. camera = this.activeCamera;
  19529. }
  19530. var cameraViewport = camera.viewport;
  19531. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19532. // Moving coordinates to local viewport world
  19533. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19534. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19535. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19536. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19537. };
  19538. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19539. if (!BABYLON.PickingInfo) {
  19540. return null;
  19541. }
  19542. var engine = this._engine;
  19543. if (!camera) {
  19544. if (!this.activeCamera)
  19545. throw new Error("Active camera not set");
  19546. camera = this.activeCamera;
  19547. }
  19548. var cameraViewport = camera.viewport;
  19549. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19550. var identity = BABYLON.Matrix.Identity();
  19551. // Moving coordinates to local viewport world
  19552. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19553. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19554. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19555. };
  19556. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19557. if (!BABYLON.PickingInfo) {
  19558. return null;
  19559. }
  19560. var pickingInfo = null;
  19561. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19562. var mesh = this.meshes[meshIndex];
  19563. if (predicate) {
  19564. if (!predicate(mesh)) {
  19565. continue;
  19566. }
  19567. }
  19568. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19569. continue;
  19570. }
  19571. var world = mesh.getWorldMatrix();
  19572. var ray = rayFunction(world);
  19573. var result = mesh.intersects(ray, fastCheck);
  19574. if (!result || !result.hit)
  19575. continue;
  19576. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19577. continue;
  19578. pickingInfo = result;
  19579. if (fastCheck) {
  19580. break;
  19581. }
  19582. }
  19583. return pickingInfo || new BABYLON.PickingInfo();
  19584. };
  19585. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19586. if (!BABYLON.PickingInfo) {
  19587. return null;
  19588. }
  19589. var pickingInfos = new Array();
  19590. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19591. var mesh = this.meshes[meshIndex];
  19592. if (predicate) {
  19593. if (!predicate(mesh)) {
  19594. continue;
  19595. }
  19596. }
  19597. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19598. continue;
  19599. }
  19600. var world = mesh.getWorldMatrix();
  19601. var ray = rayFunction(world);
  19602. var result = mesh.intersects(ray, false);
  19603. if (!result || !result.hit)
  19604. continue;
  19605. pickingInfos.push(result);
  19606. }
  19607. return pickingInfos;
  19608. };
  19609. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19610. if (!BABYLON.PickingInfo) {
  19611. return null;
  19612. }
  19613. var pickingInfo = null;
  19614. camera = camera || this.activeCamera;
  19615. if (this.spriteManagers.length > 0) {
  19616. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19617. var spriteManager = this.spriteManagers[spriteIndex];
  19618. if (!spriteManager.isPickable) {
  19619. continue;
  19620. }
  19621. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19622. if (!result || !result.hit)
  19623. continue;
  19624. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19625. continue;
  19626. pickingInfo = result;
  19627. if (fastCheck) {
  19628. break;
  19629. }
  19630. }
  19631. }
  19632. return pickingInfo || new BABYLON.PickingInfo();
  19633. };
  19634. /** Launch a ray to try to pick a mesh in the scene
  19635. * @param x position on screen
  19636. * @param y position on screen
  19637. * @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
  19638. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19639. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19640. */
  19641. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19642. var _this = this;
  19643. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19644. };
  19645. /** Launch a ray to try to pick a sprite in the scene
  19646. * @param x position on screen
  19647. * @param y position on screen
  19648. * @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
  19649. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19650. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19651. */
  19652. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19653. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19654. };
  19655. /** Use the given ray to pick a mesh in the scene
  19656. * @param ray The ray to use to pick meshes
  19657. * @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
  19658. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19659. */
  19660. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19661. var _this = this;
  19662. return this._internalPick(function (world) {
  19663. if (!_this._pickWithRayInverseMatrix) {
  19664. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19665. }
  19666. world.invertToRef(_this._pickWithRayInverseMatrix);
  19667. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19668. }, predicate, fastCheck);
  19669. };
  19670. /**
  19671. * Launch a ray to try to pick a mesh in the scene
  19672. * @param x X position on screen
  19673. * @param y Y position on screen
  19674. * @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
  19675. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19676. */
  19677. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19678. var _this = this;
  19679. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19680. };
  19681. /**
  19682. * Launch a ray to try to pick a mesh in the scene
  19683. * @param ray Ray to use
  19684. * @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
  19685. */
  19686. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19687. var _this = this;
  19688. return this._internalMultiPick(function (world) {
  19689. if (!_this._pickWithRayInverseMatrix) {
  19690. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19691. }
  19692. world.invertToRef(_this._pickWithRayInverseMatrix);
  19693. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19694. }, predicate);
  19695. };
  19696. Scene.prototype.setPointerOverMesh = function (mesh) {
  19697. if (this._pointerOverMesh === mesh) {
  19698. return;
  19699. }
  19700. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19701. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19702. }
  19703. this._pointerOverMesh = mesh;
  19704. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19705. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19706. }
  19707. };
  19708. Scene.prototype.getPointerOverMesh = function () {
  19709. return this._pointerOverMesh;
  19710. };
  19711. Scene.prototype.setPointerOverSprite = function (sprite) {
  19712. if (this._pointerOverSprite === sprite) {
  19713. return;
  19714. }
  19715. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19716. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19717. }
  19718. this._pointerOverSprite = sprite;
  19719. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19720. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19721. }
  19722. };
  19723. Scene.prototype.getPointerOverSprite = function () {
  19724. return this._pointerOverSprite;
  19725. };
  19726. // Physics
  19727. Scene.prototype.getPhysicsEngine = function () {
  19728. return this._physicsEngine;
  19729. };
  19730. /**
  19731. * Enables physics to the current scene
  19732. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19733. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19734. * @return {boolean} was the physics engine initialized
  19735. */
  19736. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19737. if (this._physicsEngine) {
  19738. return true;
  19739. }
  19740. try {
  19741. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19742. return true;
  19743. }
  19744. catch (e) {
  19745. BABYLON.Tools.Error(e.message);
  19746. return false;
  19747. }
  19748. };
  19749. Scene.prototype.disablePhysicsEngine = function () {
  19750. if (!this._physicsEngine) {
  19751. return;
  19752. }
  19753. this._physicsEngine.dispose();
  19754. this._physicsEngine = undefined;
  19755. };
  19756. Scene.prototype.isPhysicsEnabled = function () {
  19757. return this._physicsEngine !== undefined;
  19758. };
  19759. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19760. var mesh = compound.parts[0].mesh;
  19761. mesh.physicsImpostor.dispose();
  19762. mesh.physicsImpostor = null;
  19763. };
  19764. // Misc.
  19765. Scene.prototype._rebuildGeometries = function () {
  19766. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19767. var geometry = _a[_i];
  19768. geometry._rebuild();
  19769. }
  19770. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19771. var mesh = _c[_b];
  19772. mesh._rebuild();
  19773. }
  19774. if (this.postProcessManager) {
  19775. this.postProcessManager._rebuild();
  19776. }
  19777. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19778. var layer = _e[_d];
  19779. layer._rebuild();
  19780. }
  19781. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19782. var highlightLayer = _g[_f];
  19783. highlightLayer._rebuild();
  19784. }
  19785. if (this._boundingBoxRenderer) {
  19786. this._boundingBoxRenderer._rebuild();
  19787. }
  19788. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19789. var system = _j[_h];
  19790. system.rebuild();
  19791. }
  19792. if (this._postProcessRenderPipelineManager) {
  19793. this._postProcessRenderPipelineManager._rebuild();
  19794. }
  19795. };
  19796. Scene.prototype._rebuildTextures = function () {
  19797. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19798. var texture = _a[_i];
  19799. texture._rebuild();
  19800. }
  19801. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19802. };
  19803. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19804. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19805. if (replace === void 0) { replace = false; }
  19806. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19807. // Dispose existing camera or light in replace mode.
  19808. if (replace) {
  19809. if (this.activeCamera) {
  19810. this.activeCamera.dispose();
  19811. this.activeCamera = null;
  19812. }
  19813. if (this.lights) {
  19814. for (var i = 0; i < this.lights.length; i++) {
  19815. this.lights[i].dispose();
  19816. }
  19817. }
  19818. }
  19819. // Light
  19820. if (this.lights.length === 0) {
  19821. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19822. }
  19823. // Camera
  19824. if (!this.activeCamera) {
  19825. var worldExtends = this.getWorldExtends();
  19826. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19827. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19828. var camera;
  19829. var radius = worldSize.length() * 1.5;
  19830. if (createArcRotateCamera) {
  19831. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19832. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19833. arcRotateCamera.wheelPrecision = 100 / radius;
  19834. camera = arcRotateCamera;
  19835. }
  19836. else {
  19837. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19838. freeCamera.setTarget(worldCenter);
  19839. camera = freeCamera;
  19840. }
  19841. camera.minZ = radius * 0.01;
  19842. camera.maxZ = radius * 100;
  19843. camera.speed = radius * 0.2;
  19844. this.activeCamera = camera;
  19845. if (attachCameraControls) {
  19846. camera.attachControl(this.getEngine().getRenderingCanvas());
  19847. }
  19848. }
  19849. };
  19850. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19851. if (pbr === void 0) { pbr = false; }
  19852. if (scale === void 0) { scale = 1000; }
  19853. if (blur === void 0) { blur = 0; }
  19854. if (environmentTexture) {
  19855. this.environmentTexture = environmentTexture;
  19856. }
  19857. if (!this.environmentTexture) {
  19858. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19859. return;
  19860. }
  19861. // Skybox
  19862. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19863. if (pbr) {
  19864. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19865. hdrSkyboxMaterial.backFaceCulling = false;
  19866. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19867. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19868. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19869. hdrSkyboxMaterial.disableLighting = true;
  19870. hdrSkyboxMaterial.twoSidedLighting = true;
  19871. hdrSkybox.infiniteDistance = true;
  19872. hdrSkybox.material = hdrSkyboxMaterial;
  19873. }
  19874. else {
  19875. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19876. skyboxMaterial.backFaceCulling = false;
  19877. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19878. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19879. skyboxMaterial.disableLighting = true;
  19880. hdrSkybox.infiniteDistance = true;
  19881. hdrSkybox.material = skyboxMaterial;
  19882. }
  19883. return hdrSkybox;
  19884. };
  19885. Scene.prototype.createDefaultVRExperience = function () {
  19886. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19887. };
  19888. // Tags
  19889. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19890. if (tagsQuery === undefined) {
  19891. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19892. return list;
  19893. }
  19894. var listByTags = [];
  19895. forEach = forEach || (function (item) { return; });
  19896. for (var i in list) {
  19897. var item = list[i];
  19898. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19899. listByTags.push(item);
  19900. forEach(item);
  19901. }
  19902. }
  19903. return listByTags;
  19904. };
  19905. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19906. return this._getByTags(this.meshes, tagsQuery, forEach);
  19907. };
  19908. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19909. return this._getByTags(this.cameras, tagsQuery, forEach);
  19910. };
  19911. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19912. return this._getByTags(this.lights, tagsQuery, forEach);
  19913. };
  19914. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19915. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19916. };
  19917. /**
  19918. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19919. * This allowed control for front to back rendering or reversly depending of the special needs.
  19920. *
  19921. * @param renderingGroupId The rendering group id corresponding to its index
  19922. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19923. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19924. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19925. */
  19926. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19927. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19928. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19929. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19930. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19931. };
  19932. /**
  19933. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19934. *
  19935. * @param renderingGroupId The rendering group id corresponding to its index
  19936. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19937. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19938. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19939. */
  19940. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19941. if (depth === void 0) { depth = true; }
  19942. if (stencil === void 0) { stencil = true; }
  19943. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19944. };
  19945. /**
  19946. * Will flag all materials as dirty to trigger new shader compilation
  19947. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19948. */
  19949. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19950. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19951. var material = _a[_i];
  19952. if (predicate && !predicate(material)) {
  19953. continue;
  19954. }
  19955. material.markAsDirty(flag);
  19956. }
  19957. };
  19958. // Statics
  19959. Scene._FOGMODE_NONE = 0;
  19960. Scene._FOGMODE_EXP = 1;
  19961. Scene._FOGMODE_EXP2 = 2;
  19962. Scene._FOGMODE_LINEAR = 3;
  19963. Scene.MinDeltaTime = 1.0;
  19964. Scene.MaxDeltaTime = 1000.0;
  19965. /** The distance in pixel that you have to move to prevent some events */
  19966. Scene.DragMovementThreshold = 10; // in pixels
  19967. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19968. Scene.LongPressDelay = 500; // in milliseconds
  19969. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19970. Scene.DoubleClickDelay = 300; // in milliseconds
  19971. /** If you need to check double click without raising a single click at first click, enable this flag */
  19972. Scene.ExclusiveDoubleClickMode = false;
  19973. return Scene;
  19974. }());
  19975. BABYLON.Scene = Scene;
  19976. })(BABYLON || (BABYLON = {}));
  19977. //# sourceMappingURL=babylon.scene.js.map
  19978. var BABYLON;
  19979. (function (BABYLON) {
  19980. var Buffer = (function () {
  19981. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19982. if (engine instanceof BABYLON.Mesh) {
  19983. this._engine = engine.getScene().getEngine();
  19984. }
  19985. else {
  19986. this._engine = engine;
  19987. }
  19988. this._updatable = updatable;
  19989. this._data = data;
  19990. this._strideSize = stride;
  19991. if (!postponeInternalCreation) {
  19992. this.create();
  19993. }
  19994. this._instanced = instanced;
  19995. this._instanceDivisor = instanced ? 1 : 0;
  19996. }
  19997. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19998. // a lot of these parameters are ignored as they are overriden by the buffer
  19999. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20000. };
  20001. // Properties
  20002. Buffer.prototype.isUpdatable = function () {
  20003. return this._updatable;
  20004. };
  20005. Buffer.prototype.getData = function () {
  20006. return this._data;
  20007. };
  20008. Buffer.prototype.getBuffer = function () {
  20009. return this._buffer;
  20010. };
  20011. Buffer.prototype.getStrideSize = function () {
  20012. return this._strideSize;
  20013. };
  20014. Buffer.prototype.getIsInstanced = function () {
  20015. return this._instanced;
  20016. };
  20017. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  20018. get: function () {
  20019. return this._instanceDivisor;
  20020. },
  20021. set: function (value) {
  20022. this._instanceDivisor = value;
  20023. if (value == 0) {
  20024. this._instanced = false;
  20025. }
  20026. else {
  20027. this._instanced = true;
  20028. }
  20029. },
  20030. enumerable: true,
  20031. configurable: true
  20032. });
  20033. // Methods
  20034. Buffer.prototype.create = function (data) {
  20035. if (!data && this._buffer) {
  20036. return; // nothing to do
  20037. }
  20038. data = data || this._data;
  20039. if (!this._buffer) {
  20040. if (this._updatable) {
  20041. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20042. this._data = data;
  20043. }
  20044. else {
  20045. this._buffer = this._engine.createVertexBuffer(data);
  20046. }
  20047. }
  20048. else if (this._updatable) {
  20049. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20050. this._data = data;
  20051. }
  20052. };
  20053. Buffer.prototype._rebuild = function () {
  20054. this._buffer = null;
  20055. this.create(this._data);
  20056. };
  20057. Buffer.prototype.update = function (data) {
  20058. this.create(data);
  20059. };
  20060. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20061. if (!this._buffer) {
  20062. return;
  20063. }
  20064. if (this._updatable) {
  20065. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20066. this._data = null;
  20067. }
  20068. };
  20069. Buffer.prototype.dispose = function () {
  20070. if (!this._buffer) {
  20071. return;
  20072. }
  20073. if (this._engine._releaseBuffer(this._buffer)) {
  20074. this._buffer = null;
  20075. }
  20076. };
  20077. return Buffer;
  20078. }());
  20079. BABYLON.Buffer = Buffer;
  20080. })(BABYLON || (BABYLON = {}));
  20081. //# sourceMappingURL=babylon.buffer.js.map
  20082. var BABYLON;
  20083. (function (BABYLON) {
  20084. var VertexBuffer = (function () {
  20085. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20086. if (!stride) {
  20087. // Deduce stride from kind
  20088. switch (kind) {
  20089. case VertexBuffer.PositionKind:
  20090. stride = 3;
  20091. break;
  20092. case VertexBuffer.NormalKind:
  20093. stride = 3;
  20094. break;
  20095. case VertexBuffer.UVKind:
  20096. case VertexBuffer.UV2Kind:
  20097. case VertexBuffer.UV3Kind:
  20098. case VertexBuffer.UV4Kind:
  20099. case VertexBuffer.UV5Kind:
  20100. case VertexBuffer.UV6Kind:
  20101. stride = 2;
  20102. break;
  20103. case VertexBuffer.TangentKind:
  20104. case VertexBuffer.ColorKind:
  20105. stride = 4;
  20106. break;
  20107. case VertexBuffer.MatricesIndicesKind:
  20108. case VertexBuffer.MatricesIndicesExtraKind:
  20109. stride = 4;
  20110. break;
  20111. case VertexBuffer.MatricesWeightsKind:
  20112. case VertexBuffer.MatricesWeightsExtraKind:
  20113. stride = 4;
  20114. break;
  20115. }
  20116. }
  20117. if (data instanceof BABYLON.Buffer) {
  20118. if (!stride) {
  20119. stride = data.getStrideSize();
  20120. }
  20121. this._buffer = data;
  20122. this._ownsBuffer = false;
  20123. }
  20124. else {
  20125. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  20126. this._ownsBuffer = true;
  20127. }
  20128. this._stride = stride;
  20129. this._offset = offset ? offset : 0;
  20130. this._size = size ? size : stride;
  20131. this._kind = kind;
  20132. }
  20133. VertexBuffer.prototype._rebuild = function () {
  20134. if (!this._buffer) {
  20135. return;
  20136. }
  20137. this._buffer._rebuild();
  20138. };
  20139. /**
  20140. * Returns the kind of the VertexBuffer (string).
  20141. */
  20142. VertexBuffer.prototype.getKind = function () {
  20143. return this._kind;
  20144. };
  20145. // Properties
  20146. /**
  20147. * Boolean : is the VertexBuffer updatable ?
  20148. */
  20149. VertexBuffer.prototype.isUpdatable = function () {
  20150. return this._buffer.isUpdatable();
  20151. };
  20152. /**
  20153. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  20154. */
  20155. VertexBuffer.prototype.getData = function () {
  20156. return this._buffer.getData();
  20157. };
  20158. /**
  20159. * Returns the WebGLBuffer associated to the VertexBuffer.
  20160. */
  20161. VertexBuffer.prototype.getBuffer = function () {
  20162. return this._buffer.getBuffer();
  20163. };
  20164. /**
  20165. * Returns the stride of the VertexBuffer (integer).
  20166. */
  20167. VertexBuffer.prototype.getStrideSize = function () {
  20168. return this._stride;
  20169. };
  20170. /**
  20171. * Returns the offset (integer).
  20172. */
  20173. VertexBuffer.prototype.getOffset = function () {
  20174. return this._offset;
  20175. };
  20176. /**
  20177. * Returns the VertexBuffer total size (integer).
  20178. */
  20179. VertexBuffer.prototype.getSize = function () {
  20180. return this._size;
  20181. };
  20182. /**
  20183. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  20184. */
  20185. VertexBuffer.prototype.getIsInstanced = function () {
  20186. return this._buffer.getIsInstanced();
  20187. };
  20188. /**
  20189. * Returns the instancing divisor, zero for non-instanced (integer).
  20190. */
  20191. VertexBuffer.prototype.getInstanceDivisor = function () {
  20192. return this._buffer.instanceDivisor;
  20193. };
  20194. // Methods
  20195. /**
  20196. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  20197. * Returns the created WebGLBuffer.
  20198. */
  20199. VertexBuffer.prototype.create = function (data) {
  20200. return this._buffer.create(data);
  20201. };
  20202. /**
  20203. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20204. * Returns the updated WebGLBuffer.
  20205. */
  20206. VertexBuffer.prototype.update = function (data) {
  20207. return this._buffer.update(data);
  20208. };
  20209. /**
  20210. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20211. * Returns the directly updated WebGLBuffer.
  20212. */
  20213. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20214. return this._buffer.updateDirectly(data, offset);
  20215. };
  20216. /**
  20217. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  20218. */
  20219. VertexBuffer.prototype.dispose = function () {
  20220. if (this._ownsBuffer) {
  20221. this._buffer.dispose();
  20222. }
  20223. };
  20224. Object.defineProperty(VertexBuffer, "PositionKind", {
  20225. get: function () {
  20226. return VertexBuffer._PositionKind;
  20227. },
  20228. enumerable: true,
  20229. configurable: true
  20230. });
  20231. Object.defineProperty(VertexBuffer, "NormalKind", {
  20232. get: function () {
  20233. return VertexBuffer._NormalKind;
  20234. },
  20235. enumerable: true,
  20236. configurable: true
  20237. });
  20238. Object.defineProperty(VertexBuffer, "TangentKind", {
  20239. get: function () {
  20240. return VertexBuffer._TangentKind;
  20241. },
  20242. enumerable: true,
  20243. configurable: true
  20244. });
  20245. Object.defineProperty(VertexBuffer, "UVKind", {
  20246. get: function () {
  20247. return VertexBuffer._UVKind;
  20248. },
  20249. enumerable: true,
  20250. configurable: true
  20251. });
  20252. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20253. get: function () {
  20254. return VertexBuffer._UV2Kind;
  20255. },
  20256. enumerable: true,
  20257. configurable: true
  20258. });
  20259. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20260. get: function () {
  20261. return VertexBuffer._UV3Kind;
  20262. },
  20263. enumerable: true,
  20264. configurable: true
  20265. });
  20266. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20267. get: function () {
  20268. return VertexBuffer._UV4Kind;
  20269. },
  20270. enumerable: true,
  20271. configurable: true
  20272. });
  20273. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20274. get: function () {
  20275. return VertexBuffer._UV5Kind;
  20276. },
  20277. enumerable: true,
  20278. configurable: true
  20279. });
  20280. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20281. get: function () {
  20282. return VertexBuffer._UV6Kind;
  20283. },
  20284. enumerable: true,
  20285. configurable: true
  20286. });
  20287. Object.defineProperty(VertexBuffer, "ColorKind", {
  20288. get: function () {
  20289. return VertexBuffer._ColorKind;
  20290. },
  20291. enumerable: true,
  20292. configurable: true
  20293. });
  20294. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20295. get: function () {
  20296. return VertexBuffer._MatricesIndicesKind;
  20297. },
  20298. enumerable: true,
  20299. configurable: true
  20300. });
  20301. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20302. get: function () {
  20303. return VertexBuffer._MatricesWeightsKind;
  20304. },
  20305. enumerable: true,
  20306. configurable: true
  20307. });
  20308. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20309. get: function () {
  20310. return VertexBuffer._MatricesIndicesExtraKind;
  20311. },
  20312. enumerable: true,
  20313. configurable: true
  20314. });
  20315. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20316. get: function () {
  20317. return VertexBuffer._MatricesWeightsExtraKind;
  20318. },
  20319. enumerable: true,
  20320. configurable: true
  20321. });
  20322. // Enums
  20323. VertexBuffer._PositionKind = "position";
  20324. VertexBuffer._NormalKind = "normal";
  20325. VertexBuffer._TangentKind = "tangent";
  20326. VertexBuffer._UVKind = "uv";
  20327. VertexBuffer._UV2Kind = "uv2";
  20328. VertexBuffer._UV3Kind = "uv3";
  20329. VertexBuffer._UV4Kind = "uv4";
  20330. VertexBuffer._UV5Kind = "uv5";
  20331. VertexBuffer._UV6Kind = "uv6";
  20332. VertexBuffer._ColorKind = "color";
  20333. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20334. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20335. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20336. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20337. return VertexBuffer;
  20338. }());
  20339. BABYLON.VertexBuffer = VertexBuffer;
  20340. })(BABYLON || (BABYLON = {}));
  20341. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20342. var BABYLON;
  20343. (function (BABYLON) {
  20344. var InternalTexture = (function () {
  20345. function InternalTexture(engine, dataSource) {
  20346. this.onLoadedObservable = new BABYLON.Observable();
  20347. // Private
  20348. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20349. this._references = 1;
  20350. this._engine = engine;
  20351. this._dataSource = dataSource;
  20352. this._webGLTexture = engine._createTexture();
  20353. }
  20354. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20355. get: function () {
  20356. return this._dataSource;
  20357. },
  20358. enumerable: true,
  20359. configurable: true
  20360. });
  20361. InternalTexture.prototype.incrementReferences = function () {
  20362. this._references++;
  20363. };
  20364. InternalTexture.prototype.updateSize = function (width, height) {
  20365. this.width = width;
  20366. this.height = height;
  20367. this._size = width * height;
  20368. this.baseWidth = width;
  20369. this.baseHeight = height;
  20370. };
  20371. InternalTexture.prototype._rebuild = function () {
  20372. var _this = this;
  20373. var proxy;
  20374. this.isReady = false;
  20375. this._cachedCoordinatesMode = null;
  20376. this._cachedWrapU = null;
  20377. this._cachedWrapV = null;
  20378. this._cachedAnisotropicFilteringLevel = null;
  20379. switch (this._dataSource) {
  20380. case InternalTexture.DATASOURCE_TEMP:
  20381. return;
  20382. case InternalTexture.DATASOURCE_URL:
  20383. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20384. _this.isReady = true;
  20385. }, null, this._buffer, null, this.format);
  20386. proxy._swapAndDie(this);
  20387. return;
  20388. case InternalTexture.DATASOURCE_RAW:
  20389. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20390. proxy._swapAndDie(this);
  20391. this.isReady = true;
  20392. return;
  20393. case InternalTexture.DATASOURCE_DYNAMIC:
  20394. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20395. proxy._swapAndDie(this);
  20396. // The engine will make sure to update content so no need to flag it as isReady = true
  20397. return;
  20398. case InternalTexture.DATASOURCE_RENDERTARGET:
  20399. var options = new BABYLON.RenderTargetCreationOptions();
  20400. options.generateDepthBuffer = this._generateDepthBuffer;
  20401. options.generateMipMaps = this.generateMipMaps;
  20402. options.generateStencilBuffer = this._generateStencilBuffer;
  20403. options.samplingMode = this.samplingMode;
  20404. options.type = this.type;
  20405. if (this.isCube) {
  20406. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20407. }
  20408. else {
  20409. var size = {
  20410. width: this.width,
  20411. height: this.height
  20412. };
  20413. proxy = this._engine.createRenderTargetTexture(size, options);
  20414. }
  20415. proxy._swapAndDie(this);
  20416. this.isReady = true;
  20417. return;
  20418. case InternalTexture.DATASOURCE_CUBE:
  20419. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20420. _this.isReady = true;
  20421. }, null, this.format, this._extension);
  20422. proxy._swapAndDie(this);
  20423. return;
  20424. case InternalTexture.DATASOURCE_CUBERAW:
  20425. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20426. proxy._swapAndDie(this);
  20427. this.isReady = true;
  20428. return;
  20429. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20430. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20431. proxy._swapAndDie(_this);
  20432. _this.isReady = true;
  20433. }, null, this.format, this._extension);
  20434. return;
  20435. }
  20436. };
  20437. InternalTexture.prototype._swapAndDie = function (target) {
  20438. target._webGLTexture = this._webGLTexture;
  20439. if (this._framebuffer) {
  20440. target._framebuffer = this._framebuffer;
  20441. }
  20442. if (this._depthStencilBuffer) {
  20443. target._depthStencilBuffer = this._depthStencilBuffer;
  20444. }
  20445. if (this._lodTextureHigh) {
  20446. if (target._lodTextureHigh) {
  20447. target._lodTextureHigh.dispose();
  20448. }
  20449. target._lodTextureHigh = this._lodTextureHigh;
  20450. }
  20451. if (this._lodTextureMid) {
  20452. if (target._lodTextureMid) {
  20453. target._lodTextureMid.dispose();
  20454. }
  20455. target._lodTextureMid = this._lodTextureMid;
  20456. }
  20457. if (this._lodTextureLow) {
  20458. if (target._lodTextureLow) {
  20459. target._lodTextureLow.dispose();
  20460. }
  20461. target._lodTextureLow = this._lodTextureLow;
  20462. }
  20463. var cache = this._engine.getLoadedTexturesCache();
  20464. var index = cache.indexOf(this);
  20465. if (index !== -1) {
  20466. cache.splice(index, 1);
  20467. }
  20468. };
  20469. InternalTexture.prototype.dispose = function () {
  20470. if (!this._webGLTexture) {
  20471. return;
  20472. }
  20473. this._references--;
  20474. if (this._references === 0) {
  20475. this._engine._releaseTexture(this);
  20476. this._webGLTexture = null;
  20477. }
  20478. };
  20479. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20480. InternalTexture.DATASOURCE_URL = 1;
  20481. InternalTexture.DATASOURCE_TEMP = 2;
  20482. InternalTexture.DATASOURCE_RAW = 3;
  20483. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20484. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20485. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20486. InternalTexture.DATASOURCE_CUBE = 7;
  20487. InternalTexture.DATASOURCE_CUBERAW = 8;
  20488. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20489. return InternalTexture;
  20490. }());
  20491. BABYLON.InternalTexture = InternalTexture;
  20492. })(BABYLON || (BABYLON = {}));
  20493. //# sourceMappingURL=babylon.internalTexture.js.map
  20494. var BABYLON;
  20495. (function (BABYLON) {
  20496. var BaseTexture = (function () {
  20497. function BaseTexture(scene) {
  20498. this._hasAlpha = false;
  20499. this.getAlphaFromRGB = false;
  20500. this.level = 1;
  20501. this.coordinatesIndex = 0;
  20502. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20503. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20504. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20505. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20506. this.isCube = false;
  20507. this.gammaSpace = true;
  20508. this.invertZ = false;
  20509. this.lodLevelInAlpha = false;
  20510. this.lodGenerationOffset = 0.0;
  20511. this.lodGenerationScale = 0.8;
  20512. this.isRenderTarget = false;
  20513. this.animations = new Array();
  20514. /**
  20515. * An event triggered when the texture is disposed.
  20516. * @type {BABYLON.Observable}
  20517. */
  20518. this.onDisposeObservable = new BABYLON.Observable();
  20519. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20520. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20521. this._scene.textures.push(this);
  20522. this._uid = null;
  20523. }
  20524. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20525. get: function () {
  20526. return this._hasAlpha;
  20527. },
  20528. set: function (value) {
  20529. if (this._hasAlpha === value) {
  20530. return;
  20531. }
  20532. this._hasAlpha = value;
  20533. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20534. },
  20535. enumerable: true,
  20536. configurable: true
  20537. });
  20538. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20539. get: function () {
  20540. return this._coordinatesMode;
  20541. },
  20542. set: function (value) {
  20543. if (this._coordinatesMode === value) {
  20544. return;
  20545. }
  20546. this._coordinatesMode = value;
  20547. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20548. },
  20549. enumerable: true,
  20550. configurable: true
  20551. });
  20552. Object.defineProperty(BaseTexture.prototype, "uid", {
  20553. get: function () {
  20554. if (!this._uid) {
  20555. this._uid = BABYLON.Tools.RandomId();
  20556. }
  20557. return this._uid;
  20558. },
  20559. enumerable: true,
  20560. configurable: true
  20561. });
  20562. BaseTexture.prototype.toString = function () {
  20563. return this.name;
  20564. };
  20565. BaseTexture.prototype.getClassName = function () {
  20566. return "BaseTexture";
  20567. };
  20568. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20569. set: function (callback) {
  20570. if (this._onDisposeObserver) {
  20571. this.onDisposeObservable.remove(this._onDisposeObserver);
  20572. }
  20573. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20574. },
  20575. enumerable: true,
  20576. configurable: true
  20577. });
  20578. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20579. get: function () {
  20580. return true;
  20581. },
  20582. enumerable: true,
  20583. configurable: true
  20584. });
  20585. BaseTexture.prototype.getScene = function () {
  20586. return this._scene;
  20587. };
  20588. BaseTexture.prototype.getTextureMatrix = function () {
  20589. return null;
  20590. };
  20591. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20592. return null;
  20593. };
  20594. BaseTexture.prototype.getInternalTexture = function () {
  20595. return this._texture;
  20596. };
  20597. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20598. return !this.isBlocking || this.isReady();
  20599. };
  20600. BaseTexture.prototype.isReady = function () {
  20601. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20602. this.delayLoad();
  20603. return false;
  20604. }
  20605. if (this._texture) {
  20606. return this._texture.isReady;
  20607. }
  20608. return false;
  20609. };
  20610. BaseTexture.prototype.getSize = function () {
  20611. if (this._texture.width) {
  20612. return new BABYLON.Size(this._texture.width, this._texture.height);
  20613. }
  20614. if (this._texture._size) {
  20615. return new BABYLON.Size(this._texture._size, this._texture._size);
  20616. }
  20617. return BABYLON.Size.Zero();
  20618. };
  20619. BaseTexture.prototype.getBaseSize = function () {
  20620. if (!this.isReady() || !this._texture)
  20621. return BABYLON.Size.Zero();
  20622. if (this._texture._size) {
  20623. return new BABYLON.Size(this._texture._size, this._texture._size);
  20624. }
  20625. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20626. };
  20627. BaseTexture.prototype.scale = function (ratio) {
  20628. };
  20629. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20630. get: function () {
  20631. return false;
  20632. },
  20633. enumerable: true,
  20634. configurable: true
  20635. });
  20636. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20637. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20638. for (var index = 0; index < texturesCache.length; index++) {
  20639. var texturesCacheEntry = texturesCache[index];
  20640. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20641. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20642. texturesCacheEntry.incrementReferences();
  20643. return texturesCacheEntry;
  20644. }
  20645. }
  20646. }
  20647. return null;
  20648. };
  20649. BaseTexture.prototype._rebuild = function () {
  20650. };
  20651. BaseTexture.prototype.delayLoad = function () {
  20652. };
  20653. BaseTexture.prototype.clone = function () {
  20654. return null;
  20655. };
  20656. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20657. get: function () {
  20658. if (!this._texture) {
  20659. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20660. }
  20661. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20662. },
  20663. enumerable: true,
  20664. configurable: true
  20665. });
  20666. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20667. get: function () {
  20668. if (!this._texture) {
  20669. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20670. }
  20671. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20672. },
  20673. enumerable: true,
  20674. configurable: true
  20675. });
  20676. BaseTexture.prototype.readPixels = function (faceIndex) {
  20677. if (faceIndex === void 0) { faceIndex = 0; }
  20678. if (!this._texture) {
  20679. return null;
  20680. }
  20681. var size = this.getSize();
  20682. var engine = this.getScene().getEngine();
  20683. if (this._texture.isCube) {
  20684. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20685. }
  20686. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20687. };
  20688. BaseTexture.prototype.releaseInternalTexture = function () {
  20689. if (this._texture) {
  20690. this._texture.dispose();
  20691. this._texture = null;
  20692. }
  20693. };
  20694. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20695. get: function () {
  20696. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20697. return null;
  20698. }
  20699. if (!this._texture._sphericalPolynomial) {
  20700. this._texture._sphericalPolynomial =
  20701. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20702. }
  20703. return this._texture._sphericalPolynomial;
  20704. },
  20705. set: function (value) {
  20706. if (this._texture) {
  20707. this._texture._sphericalPolynomial = value;
  20708. }
  20709. },
  20710. enumerable: true,
  20711. configurable: true
  20712. });
  20713. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20714. get: function () {
  20715. if (this._texture) {
  20716. return this._texture._lodTextureHigh;
  20717. }
  20718. return null;
  20719. },
  20720. enumerable: true,
  20721. configurable: true
  20722. });
  20723. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20724. get: function () {
  20725. if (this._texture) {
  20726. return this._texture._lodTextureMid;
  20727. }
  20728. return null;
  20729. },
  20730. enumerable: true,
  20731. configurable: true
  20732. });
  20733. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20734. get: function () {
  20735. if (this._texture) {
  20736. return this._texture._lodTextureLow;
  20737. }
  20738. return null;
  20739. },
  20740. enumerable: true,
  20741. configurable: true
  20742. });
  20743. BaseTexture.prototype.dispose = function () {
  20744. // Animations
  20745. this.getScene().stopAnimation(this);
  20746. // Remove from scene
  20747. this._scene._removePendingData(this);
  20748. var index = this._scene.textures.indexOf(this);
  20749. if (index >= 0) {
  20750. this._scene.textures.splice(index, 1);
  20751. }
  20752. if (this._texture === undefined) {
  20753. return;
  20754. }
  20755. // Release
  20756. this.releaseInternalTexture();
  20757. // Callback
  20758. this.onDisposeObservable.notifyObservers(this);
  20759. this.onDisposeObservable.clear();
  20760. };
  20761. BaseTexture.prototype.serialize = function () {
  20762. if (!this.name) {
  20763. return null;
  20764. }
  20765. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20766. // Animations
  20767. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20768. return serializationObject;
  20769. };
  20770. BaseTexture.WhenAllReady = function (textures, callback) {
  20771. var numRemaining = textures.length;
  20772. if (numRemaining === 0) {
  20773. callback();
  20774. return;
  20775. }
  20776. var _loop_1 = function () {
  20777. texture = textures[i];
  20778. if (texture.isReady()) {
  20779. if (--numRemaining === 0) {
  20780. callback();
  20781. }
  20782. }
  20783. else {
  20784. onLoadObservable = texture.onLoadObservable;
  20785. var onLoadCallback_1 = function () {
  20786. onLoadObservable.removeCallback(onLoadCallback_1);
  20787. if (--numRemaining === 0) {
  20788. callback();
  20789. }
  20790. };
  20791. onLoadObservable.add(onLoadCallback_1);
  20792. }
  20793. };
  20794. var texture, onLoadObservable;
  20795. for (var i = 0; i < textures.length; i++) {
  20796. _loop_1();
  20797. }
  20798. };
  20799. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20800. __decorate([
  20801. BABYLON.serialize()
  20802. ], BaseTexture.prototype, "name", void 0);
  20803. __decorate([
  20804. BABYLON.serialize("hasAlpha")
  20805. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20806. __decorate([
  20807. BABYLON.serialize()
  20808. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20809. __decorate([
  20810. BABYLON.serialize()
  20811. ], BaseTexture.prototype, "level", void 0);
  20812. __decorate([
  20813. BABYLON.serialize()
  20814. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20815. __decorate([
  20816. BABYLON.serialize("coordinatesMode")
  20817. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20818. __decorate([
  20819. BABYLON.serialize()
  20820. ], BaseTexture.prototype, "wrapU", void 0);
  20821. __decorate([
  20822. BABYLON.serialize()
  20823. ], BaseTexture.prototype, "wrapV", void 0);
  20824. __decorate([
  20825. BABYLON.serialize()
  20826. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20827. __decorate([
  20828. BABYLON.serialize()
  20829. ], BaseTexture.prototype, "isCube", void 0);
  20830. __decorate([
  20831. BABYLON.serialize()
  20832. ], BaseTexture.prototype, "gammaSpace", void 0);
  20833. __decorate([
  20834. BABYLON.serialize()
  20835. ], BaseTexture.prototype, "invertZ", void 0);
  20836. __decorate([
  20837. BABYLON.serialize()
  20838. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20839. __decorate([
  20840. BABYLON.serialize()
  20841. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20842. __decorate([
  20843. BABYLON.serialize()
  20844. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20845. __decorate([
  20846. BABYLON.serialize()
  20847. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20848. return BaseTexture;
  20849. }());
  20850. BABYLON.BaseTexture = BaseTexture;
  20851. })(BABYLON || (BABYLON = {}));
  20852. //# sourceMappingURL=babylon.baseTexture.js.map
  20853. var BABYLON;
  20854. (function (BABYLON) {
  20855. var Texture = (function (_super) {
  20856. __extends(Texture, _super);
  20857. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20858. if (noMipmap === void 0) { noMipmap = false; }
  20859. if (invertY === void 0) { invertY = true; }
  20860. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20861. if (onLoad === void 0) { onLoad = null; }
  20862. if (onError === void 0) { onError = null; }
  20863. if (buffer === void 0) { buffer = null; }
  20864. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20865. var _this = _super.call(this, scene) || this;
  20866. _this.uOffset = 0;
  20867. _this.vOffset = 0;
  20868. _this.uScale = 1.0;
  20869. _this.vScale = 1.0;
  20870. _this.uAng = 0;
  20871. _this.vAng = 0;
  20872. _this.wAng = 0;
  20873. _this._isBlocking = true;
  20874. _this.name = url;
  20875. _this.url = url;
  20876. _this._noMipmap = noMipmap;
  20877. _this._invertY = invertY;
  20878. _this._samplingMode = samplingMode;
  20879. _this._buffer = buffer;
  20880. _this._deleteBuffer = deleteBuffer;
  20881. _this._format = format;
  20882. scene = _this.getScene();
  20883. var load = function () {
  20884. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20885. _this.onLoadObservable.notifyObservers(_this);
  20886. }
  20887. if (onLoad) {
  20888. onLoad();
  20889. }
  20890. if (!_this.isBlocking) {
  20891. scene.resetCachedMaterial();
  20892. }
  20893. };
  20894. if (!url) {
  20895. _this._delayedOnLoad = load;
  20896. _this._delayedOnError = onError;
  20897. return _this;
  20898. }
  20899. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20900. if (!_this._texture) {
  20901. if (!scene.useDelayedTextureLoading) {
  20902. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20903. if (deleteBuffer) {
  20904. delete _this._buffer;
  20905. }
  20906. }
  20907. else {
  20908. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20909. _this._delayedOnLoad = load;
  20910. _this._delayedOnError = onError;
  20911. }
  20912. }
  20913. else {
  20914. if (_this._texture.isReady) {
  20915. BABYLON.Tools.SetImmediate(function () { return load(); });
  20916. }
  20917. else {
  20918. _this._texture.onLoadedObservable.add(load);
  20919. }
  20920. }
  20921. return _this;
  20922. }
  20923. Object.defineProperty(Texture.prototype, "noMipmap", {
  20924. get: function () {
  20925. return this._noMipmap;
  20926. },
  20927. enumerable: true,
  20928. configurable: true
  20929. });
  20930. Object.defineProperty(Texture.prototype, "isBlocking", {
  20931. get: function () {
  20932. return this._isBlocking;
  20933. },
  20934. set: function (value) {
  20935. this._isBlocking = value;
  20936. },
  20937. enumerable: true,
  20938. configurable: true
  20939. });
  20940. Object.defineProperty(Texture.prototype, "samplingMode", {
  20941. get: function () {
  20942. return this._samplingMode;
  20943. },
  20944. enumerable: true,
  20945. configurable: true
  20946. });
  20947. Texture.prototype.updateURL = function (url) {
  20948. this.url = url;
  20949. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20950. this.delayLoad();
  20951. };
  20952. Texture.prototype.delayLoad = function () {
  20953. var _this = this;
  20954. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20955. return;
  20956. }
  20957. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20958. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20959. if (!this._texture) {
  20960. 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);
  20961. if (this._deleteBuffer) {
  20962. delete this._buffer;
  20963. }
  20964. }
  20965. else {
  20966. if (this._texture.isReady) {
  20967. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20968. }
  20969. else {
  20970. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20971. }
  20972. }
  20973. };
  20974. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20975. if (!this._texture) {
  20976. return;
  20977. }
  20978. this._samplingMode = samplingMode;
  20979. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20980. };
  20981. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20982. x *= this.uScale;
  20983. y *= this.vScale;
  20984. x -= 0.5 * this.uScale;
  20985. y -= 0.5 * this.vScale;
  20986. z -= 0.5;
  20987. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20988. t.x += 0.5 * this.uScale + this.uOffset;
  20989. t.y += 0.5 * this.vScale + this.vOffset;
  20990. t.z += 0.5;
  20991. };
  20992. Texture.prototype.getTextureMatrix = function () {
  20993. var _this = this;
  20994. if (this.uOffset === this._cachedUOffset &&
  20995. this.vOffset === this._cachedVOffset &&
  20996. this.uScale === this._cachedUScale &&
  20997. this.vScale === this._cachedVScale &&
  20998. this.uAng === this._cachedUAng &&
  20999. this.vAng === this._cachedVAng &&
  21000. this.wAng === this._cachedWAng) {
  21001. return this._cachedTextureMatrix;
  21002. }
  21003. this._cachedUOffset = this.uOffset;
  21004. this._cachedVOffset = this.vOffset;
  21005. this._cachedUScale = this.uScale;
  21006. this._cachedVScale = this.vScale;
  21007. this._cachedUAng = this.uAng;
  21008. this._cachedVAng = this.vAng;
  21009. this._cachedWAng = this.wAng;
  21010. if (!this._cachedTextureMatrix) {
  21011. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21012. this._rowGenerationMatrix = new BABYLON.Matrix();
  21013. this._t0 = BABYLON.Vector3.Zero();
  21014. this._t1 = BABYLON.Vector3.Zero();
  21015. this._t2 = BABYLON.Vector3.Zero();
  21016. }
  21017. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21018. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21019. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21020. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21021. this._t1.subtractInPlace(this._t0);
  21022. this._t2.subtractInPlace(this._t0);
  21023. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21024. this._cachedTextureMatrix.m[0] = this._t1.x;
  21025. this._cachedTextureMatrix.m[1] = this._t1.y;
  21026. this._cachedTextureMatrix.m[2] = this._t1.z;
  21027. this._cachedTextureMatrix.m[4] = this._t2.x;
  21028. this._cachedTextureMatrix.m[5] = this._t2.y;
  21029. this._cachedTextureMatrix.m[6] = this._t2.z;
  21030. this._cachedTextureMatrix.m[8] = this._t0.x;
  21031. this._cachedTextureMatrix.m[9] = this._t0.y;
  21032. this._cachedTextureMatrix.m[10] = this._t0.z;
  21033. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21034. return mat.hasTexture(_this);
  21035. });
  21036. return this._cachedTextureMatrix;
  21037. };
  21038. Texture.prototype.getReflectionTextureMatrix = function () {
  21039. var _this = this;
  21040. var scene = this.getScene();
  21041. if (this.uOffset === this._cachedUOffset &&
  21042. this.vOffset === this._cachedVOffset &&
  21043. this.uScale === this._cachedUScale &&
  21044. this.vScale === this._cachedVScale &&
  21045. this.coordinatesMode === this._cachedCoordinatesMode) {
  21046. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21047. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21048. return this._cachedTextureMatrix;
  21049. }
  21050. }
  21051. else {
  21052. return this._cachedTextureMatrix;
  21053. }
  21054. }
  21055. if (!this._cachedTextureMatrix) {
  21056. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21057. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21058. }
  21059. this._cachedUOffset = this.uOffset;
  21060. this._cachedVOffset = this.vOffset;
  21061. this._cachedUScale = this.uScale;
  21062. this._cachedVScale = this.vScale;
  21063. this._cachedCoordinatesMode = this.coordinatesMode;
  21064. switch (this.coordinatesMode) {
  21065. case Texture.PLANAR_MODE:
  21066. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21067. this._cachedTextureMatrix[0] = this.uScale;
  21068. this._cachedTextureMatrix[5] = this.vScale;
  21069. this._cachedTextureMatrix[12] = this.uOffset;
  21070. this._cachedTextureMatrix[13] = this.vOffset;
  21071. break;
  21072. case Texture.PROJECTION_MODE:
  21073. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21074. this._projectionModeMatrix.m[0] = 0.5;
  21075. this._projectionModeMatrix.m[5] = -0.5;
  21076. this._projectionModeMatrix.m[10] = 0.0;
  21077. this._projectionModeMatrix.m[12] = 0.5;
  21078. this._projectionModeMatrix.m[13] = 0.5;
  21079. this._projectionModeMatrix.m[14] = 1.0;
  21080. this._projectionModeMatrix.m[15] = 1.0;
  21081. var projectionMatrix = scene.getProjectionMatrix();
  21082. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  21083. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21084. break;
  21085. default:
  21086. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21087. break;
  21088. }
  21089. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21090. return (mat.getActiveTextures().indexOf(_this) !== -1);
  21091. });
  21092. return this._cachedTextureMatrix;
  21093. };
  21094. Texture.prototype.clone = function () {
  21095. var _this = this;
  21096. return BABYLON.SerializationHelper.Clone(function () {
  21097. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21098. }, this);
  21099. };
  21100. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21101. get: function () {
  21102. if (!this._onLoadObservable) {
  21103. this._onLoadObservable = new BABYLON.Observable();
  21104. }
  21105. return this._onLoadObservable;
  21106. },
  21107. enumerable: true,
  21108. configurable: true
  21109. });
  21110. Texture.prototype.serialize = function () {
  21111. var serializationObject = _super.prototype.serialize.call(this);
  21112. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  21113. serializationObject.base64String = this._buffer;
  21114. serializationObject.name = serializationObject.name.replace("data:", "");
  21115. }
  21116. return serializationObject;
  21117. };
  21118. Texture.prototype.getClassName = function () {
  21119. return "Texture";
  21120. };
  21121. Texture.prototype.dispose = function () {
  21122. _super.prototype.dispose.call(this);
  21123. if (this.onLoadObservable) {
  21124. this.onLoadObservable.clear();
  21125. this._onLoadObservable = null;
  21126. }
  21127. this._delayedOnLoad = null;
  21128. this._delayedOnError = null;
  21129. };
  21130. // Statics
  21131. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21132. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21133. if (onLoad === void 0) { onLoad = null; }
  21134. if (onError === void 0) { onError = null; }
  21135. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21136. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  21137. };
  21138. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21139. if (parsedTexture.customType) {
  21140. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21141. // Update Sampling Mode
  21142. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  21143. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  21144. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  21145. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  21146. }
  21147. }
  21148. return parsedCustomTexture;
  21149. }
  21150. if (parsedTexture.isCube) {
  21151. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21152. }
  21153. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21154. return null;
  21155. }
  21156. var texture = BABYLON.SerializationHelper.Parse(function () {
  21157. if (parsedTexture.mirrorPlane) {
  21158. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21159. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21160. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21161. return mirrorTexture;
  21162. }
  21163. else if (parsedTexture.isRenderTarget) {
  21164. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21165. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21166. return renderTargetTexture;
  21167. }
  21168. else {
  21169. var texture;
  21170. if (parsedTexture.base64String) {
  21171. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21172. }
  21173. else {
  21174. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21175. }
  21176. return texture;
  21177. }
  21178. }, parsedTexture, scene);
  21179. // Update Sampling Mode
  21180. if (parsedTexture.samplingMode) {
  21181. var sampling = parsedTexture.samplingMode;
  21182. if (texture._samplingMode !== sampling) {
  21183. texture.updateSamplingMode(sampling);
  21184. }
  21185. }
  21186. // Animations
  21187. if (parsedTexture.animations) {
  21188. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21189. var parsedAnimation = parsedTexture.animations[animationIndex];
  21190. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21191. }
  21192. }
  21193. return texture;
  21194. };
  21195. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21196. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21197. if (noMipmap === void 0) { noMipmap = false; }
  21198. if (invertY === void 0) { invertY = true; }
  21199. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21200. if (onLoad === void 0) { onLoad = null; }
  21201. if (onError === void 0) { onError = null; }
  21202. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21203. if (name.substr(0, 5) !== "data:") {
  21204. name = "data:" + name;
  21205. }
  21206. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  21207. };
  21208. // Constants
  21209. Texture.NEAREST_SAMPLINGMODE = 1;
  21210. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  21211. Texture.BILINEAR_SAMPLINGMODE = 2;
  21212. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  21213. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21214. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  21215. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  21216. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  21217. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  21218. Texture.NEAREST_LINEAR = 7;
  21219. Texture.NEAREST_NEAREST = 8;
  21220. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  21221. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  21222. Texture.LINEAR_LINEAR = 11;
  21223. Texture.LINEAR_NEAREST = 12;
  21224. Texture.EXPLICIT_MODE = 0;
  21225. Texture.SPHERICAL_MODE = 1;
  21226. Texture.PLANAR_MODE = 2;
  21227. Texture.CUBIC_MODE = 3;
  21228. Texture.PROJECTION_MODE = 4;
  21229. Texture.SKYBOX_MODE = 5;
  21230. Texture.INVCUBIC_MODE = 6;
  21231. Texture.EQUIRECTANGULAR_MODE = 7;
  21232. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21233. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  21234. Texture.CLAMP_ADDRESSMODE = 0;
  21235. Texture.WRAP_ADDRESSMODE = 1;
  21236. Texture.MIRROR_ADDRESSMODE = 2;
  21237. __decorate([
  21238. BABYLON.serialize()
  21239. ], Texture.prototype, "url", void 0);
  21240. __decorate([
  21241. BABYLON.serialize()
  21242. ], Texture.prototype, "uOffset", void 0);
  21243. __decorate([
  21244. BABYLON.serialize()
  21245. ], Texture.prototype, "vOffset", void 0);
  21246. __decorate([
  21247. BABYLON.serialize()
  21248. ], Texture.prototype, "uScale", void 0);
  21249. __decorate([
  21250. BABYLON.serialize()
  21251. ], Texture.prototype, "vScale", void 0);
  21252. __decorate([
  21253. BABYLON.serialize()
  21254. ], Texture.prototype, "uAng", void 0);
  21255. __decorate([
  21256. BABYLON.serialize()
  21257. ], Texture.prototype, "vAng", void 0);
  21258. __decorate([
  21259. BABYLON.serialize()
  21260. ], Texture.prototype, "wAng", void 0);
  21261. __decorate([
  21262. BABYLON.serialize()
  21263. ], Texture.prototype, "isBlocking", null);
  21264. return Texture;
  21265. }(BABYLON.BaseTexture));
  21266. BABYLON.Texture = Texture;
  21267. })(BABYLON || (BABYLON = {}));
  21268. //# sourceMappingURL=babylon.texture.js.map
  21269. var BABYLON;
  21270. (function (BABYLON) {
  21271. var _InstancesBatch = (function () {
  21272. function _InstancesBatch() {
  21273. this.mustReturn = false;
  21274. this.visibleInstances = new Array();
  21275. this.renderSelf = new Array();
  21276. }
  21277. return _InstancesBatch;
  21278. }());
  21279. BABYLON._InstancesBatch = _InstancesBatch;
  21280. var Mesh = (function (_super) {
  21281. __extends(Mesh, _super);
  21282. /**
  21283. * @constructor
  21284. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21285. * @param {Scene} scene The scene to add this mesh to.
  21286. * @param {Node} parent The parent of this mesh, if it has one
  21287. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21288. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21289. * When false, achieved by calling a clone(), also passing False.
  21290. * This will make creation of children, recursive.
  21291. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21292. */
  21293. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21294. if (parent === void 0) { parent = null; }
  21295. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21296. var _this = _super.call(this, name, scene) || this;
  21297. // Events
  21298. /**
  21299. * An event triggered before rendering the mesh
  21300. * @type {BABYLON.Observable}
  21301. */
  21302. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21303. /**
  21304. * An event triggered after rendering the mesh
  21305. * @type {BABYLON.Observable}
  21306. */
  21307. _this.onAfterRenderObservable = new BABYLON.Observable();
  21308. /**
  21309. * An event triggered before drawing the mesh
  21310. * @type {BABYLON.Observable}
  21311. */
  21312. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21313. // Members
  21314. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21315. _this.instances = new Array();
  21316. _this._LODLevels = new Array();
  21317. _this._visibleInstances = {};
  21318. _this._renderIdForInstances = new Array();
  21319. _this._batchCache = new _InstancesBatch();
  21320. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21321. _this._sideOrientation = Mesh._DEFAULTSIDE;
  21322. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21323. // Will be used to save a source mesh reference, If any
  21324. _this._source = null;
  21325. if (source) {
  21326. // Source mesh
  21327. _this._source = source;
  21328. // Geometry
  21329. if (source._geometry) {
  21330. source._geometry.applyToMesh(_this);
  21331. }
  21332. // Deep copy
  21333. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21334. // Parent
  21335. _this.parent = source.parent;
  21336. // Pivot
  21337. _this.setPivotMatrix(source.getPivotMatrix());
  21338. _this.id = name + "." + source.id;
  21339. // Material
  21340. _this.material = source.material;
  21341. var index;
  21342. if (!doNotCloneChildren) {
  21343. // Children
  21344. for (index = 0; index < scene.meshes.length; index++) {
  21345. var mesh = scene.meshes[index];
  21346. if (mesh.parent === source) {
  21347. // doNotCloneChildren is always going to be False
  21348. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21349. }
  21350. }
  21351. }
  21352. // Physics clone
  21353. var physicsEngine = _this.getScene().getPhysicsEngine();
  21354. if (clonePhysicsImpostor && physicsEngine) {
  21355. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21356. if (impostor) {
  21357. _this.physicsImpostor = impostor.clone(_this);
  21358. }
  21359. }
  21360. // Particles
  21361. for (index = 0; index < scene.particleSystems.length; index++) {
  21362. var system = scene.particleSystems[index];
  21363. if (system.emitter === source) {
  21364. system.clone(system.name, _this);
  21365. }
  21366. }
  21367. _this.computeWorldMatrix(true);
  21368. }
  21369. // Parent
  21370. if (parent !== null) {
  21371. _this.parent = parent;
  21372. }
  21373. return _this;
  21374. }
  21375. Object.defineProperty(Mesh, "FRONTSIDE", {
  21376. /**
  21377. * Mesh side orientation : usually the external or front surface
  21378. */
  21379. get: function () {
  21380. return Mesh._FRONTSIDE;
  21381. },
  21382. enumerable: true,
  21383. configurable: true
  21384. });
  21385. Object.defineProperty(Mesh, "BACKSIDE", {
  21386. /**
  21387. * Mesh side orientation : usually the internal or back surface
  21388. */
  21389. get: function () {
  21390. return Mesh._BACKSIDE;
  21391. },
  21392. enumerable: true,
  21393. configurable: true
  21394. });
  21395. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21396. /**
  21397. * Mesh side orientation : both internal and external or front and back surfaces
  21398. */
  21399. get: function () {
  21400. return Mesh._DOUBLESIDE;
  21401. },
  21402. enumerable: true,
  21403. configurable: true
  21404. });
  21405. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21406. /**
  21407. * Mesh side orientation : by default, `FRONTSIDE`
  21408. */
  21409. get: function () {
  21410. return Mesh._DEFAULTSIDE;
  21411. },
  21412. enumerable: true,
  21413. configurable: true
  21414. });
  21415. Object.defineProperty(Mesh, "NO_CAP", {
  21416. /**
  21417. * Mesh cap setting : no cap
  21418. */
  21419. get: function () {
  21420. return Mesh._NO_CAP;
  21421. },
  21422. enumerable: true,
  21423. configurable: true
  21424. });
  21425. Object.defineProperty(Mesh, "CAP_START", {
  21426. /**
  21427. * Mesh cap setting : one cap at the beginning of the mesh
  21428. */
  21429. get: function () {
  21430. return Mesh._CAP_START;
  21431. },
  21432. enumerable: true,
  21433. configurable: true
  21434. });
  21435. Object.defineProperty(Mesh, "CAP_END", {
  21436. /**
  21437. * Mesh cap setting : one cap at the end of the mesh
  21438. */
  21439. get: function () {
  21440. return Mesh._CAP_END;
  21441. },
  21442. enumerable: true,
  21443. configurable: true
  21444. });
  21445. Object.defineProperty(Mesh, "CAP_ALL", {
  21446. /**
  21447. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21448. */
  21449. get: function () {
  21450. return Mesh._CAP_ALL;
  21451. },
  21452. enumerable: true,
  21453. configurable: true
  21454. });
  21455. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21456. set: function (callback) {
  21457. if (this._onBeforeDrawObserver) {
  21458. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21459. }
  21460. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21461. },
  21462. enumerable: true,
  21463. configurable: true
  21464. });
  21465. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21466. get: function () {
  21467. return this._morphTargetManager;
  21468. },
  21469. set: function (value) {
  21470. if (this._morphTargetManager === value) {
  21471. return;
  21472. }
  21473. this._morphTargetManager = value;
  21474. this._syncGeometryWithMorphTargetManager();
  21475. },
  21476. enumerable: true,
  21477. configurable: true
  21478. });
  21479. Object.defineProperty(Mesh.prototype, "source", {
  21480. get: function () {
  21481. return this._source;
  21482. },
  21483. enumerable: true,
  21484. configurable: true
  21485. });
  21486. // Methods
  21487. /**
  21488. * Returns the string "Mesh".
  21489. */
  21490. Mesh.prototype.getClassName = function () {
  21491. return "Mesh";
  21492. };
  21493. /**
  21494. * Returns a string.
  21495. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21496. */
  21497. Mesh.prototype.toString = function (fullDetails) {
  21498. var ret = _super.prototype.toString.call(this, fullDetails);
  21499. ret += ", n vertices: " + this.getTotalVertices();
  21500. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21501. if (this.animations) {
  21502. for (var i = 0; i < this.animations.length; i++) {
  21503. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21504. }
  21505. }
  21506. if (fullDetails) {
  21507. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21508. }
  21509. return ret;
  21510. };
  21511. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21512. /**
  21513. * True if the mesh has some Levels Of Details (LOD).
  21514. * Returns a boolean.
  21515. */
  21516. get: function () {
  21517. return this._LODLevels.length > 0;
  21518. },
  21519. enumerable: true,
  21520. configurable: true
  21521. });
  21522. Mesh.prototype._sortLODLevels = function () {
  21523. this._LODLevels.sort(function (a, b) {
  21524. if (a.distance < b.distance) {
  21525. return 1;
  21526. }
  21527. if (a.distance > b.distance) {
  21528. return -1;
  21529. }
  21530. return 0;
  21531. });
  21532. };
  21533. /**
  21534. * Add a mesh as LOD level triggered at the given distance.
  21535. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21536. * @param {number} distance The distance from the center of the object to show this level
  21537. * @param {Mesh} mesh The mesh to be added as LOD level
  21538. * @return {Mesh} This mesh (for chaining)
  21539. */
  21540. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21541. if (mesh && mesh._masterMesh) {
  21542. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21543. return this;
  21544. }
  21545. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21546. this._LODLevels.push(level);
  21547. if (mesh) {
  21548. mesh._masterMesh = this;
  21549. }
  21550. this._sortLODLevels();
  21551. return this;
  21552. };
  21553. /**
  21554. * Returns the LOD level mesh at the passed distance or null if not found.
  21555. * It is related to the method `addLODLevel(distance, mesh)`.
  21556. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21557. * Returns an object Mesh or `null`.
  21558. */
  21559. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21560. for (var index = 0; index < this._LODLevels.length; index++) {
  21561. var level = this._LODLevels[index];
  21562. if (level.distance === distance) {
  21563. return level.mesh;
  21564. }
  21565. }
  21566. return null;
  21567. };
  21568. /**
  21569. * Remove a mesh from the LOD array
  21570. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21571. * @param {Mesh} mesh The mesh to be removed.
  21572. * @return {Mesh} This mesh (for chaining)
  21573. */
  21574. Mesh.prototype.removeLODLevel = function (mesh) {
  21575. for (var index = 0; index < this._LODLevels.length; index++) {
  21576. if (this._LODLevels[index].mesh === mesh) {
  21577. this._LODLevels.splice(index, 1);
  21578. if (mesh) {
  21579. mesh._masterMesh = null;
  21580. }
  21581. }
  21582. }
  21583. this._sortLODLevels();
  21584. return this;
  21585. };
  21586. /**
  21587. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21588. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21589. */
  21590. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21591. if (!this._LODLevels || this._LODLevels.length === 0) {
  21592. return this;
  21593. }
  21594. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21595. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21596. if (this.onLODLevelSelection) {
  21597. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21598. }
  21599. return this;
  21600. }
  21601. for (var index = 0; index < this._LODLevels.length; index++) {
  21602. var level = this._LODLevels[index];
  21603. if (level.distance < distanceToCamera) {
  21604. if (level.mesh) {
  21605. level.mesh._preActivate();
  21606. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21607. }
  21608. if (this.onLODLevelSelection) {
  21609. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21610. }
  21611. return level.mesh;
  21612. }
  21613. }
  21614. if (this.onLODLevelSelection) {
  21615. this.onLODLevelSelection(distanceToCamera, this, this);
  21616. }
  21617. return this;
  21618. };
  21619. Object.defineProperty(Mesh.prototype, "geometry", {
  21620. /**
  21621. * Returns the mesh internal Geometry object.
  21622. */
  21623. get: function () {
  21624. return this._geometry;
  21625. },
  21626. enumerable: true,
  21627. configurable: true
  21628. });
  21629. /**
  21630. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21631. */
  21632. Mesh.prototype.getTotalVertices = function () {
  21633. if (!this._geometry) {
  21634. return 0;
  21635. }
  21636. return this._geometry.getTotalVertices();
  21637. };
  21638. /**
  21639. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21640. * 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.
  21641. * You can force the copy with forceCopy === true
  21642. * Returns null if the mesh has no geometry or no vertex buffer.
  21643. * Possible `kind` values :
  21644. * - BABYLON.VertexBuffer.PositionKind
  21645. * - BABYLON.VertexBuffer.UVKind
  21646. * - BABYLON.VertexBuffer.UV2Kind
  21647. * - BABYLON.VertexBuffer.UV3Kind
  21648. * - BABYLON.VertexBuffer.UV4Kind
  21649. * - BABYLON.VertexBuffer.UV5Kind
  21650. * - BABYLON.VertexBuffer.UV6Kind
  21651. * - BABYLON.VertexBuffer.ColorKind
  21652. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21653. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21654. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21655. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21656. */
  21657. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21658. if (!this._geometry) {
  21659. return null;
  21660. }
  21661. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21662. };
  21663. /**
  21664. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21665. * Returns `undefined` if the mesh has no geometry.
  21666. * Possible `kind` values :
  21667. * - BABYLON.VertexBuffer.PositionKind
  21668. * - BABYLON.VertexBuffer.UVKind
  21669. * - BABYLON.VertexBuffer.UV2Kind
  21670. * - BABYLON.VertexBuffer.UV3Kind
  21671. * - BABYLON.VertexBuffer.UV4Kind
  21672. * - BABYLON.VertexBuffer.UV5Kind
  21673. * - BABYLON.VertexBuffer.UV6Kind
  21674. * - BABYLON.VertexBuffer.ColorKind
  21675. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21676. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21677. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21678. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21679. */
  21680. Mesh.prototype.getVertexBuffer = function (kind) {
  21681. if (!this._geometry) {
  21682. return undefined;
  21683. }
  21684. return this._geometry.getVertexBuffer(kind);
  21685. };
  21686. /**
  21687. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21688. * Possible `kind` values :
  21689. * - BABYLON.VertexBuffer.PositionKind
  21690. * - BABYLON.VertexBuffer.UVKind
  21691. * - BABYLON.VertexBuffer.UV2Kind
  21692. * - BABYLON.VertexBuffer.UV3Kind
  21693. * - BABYLON.VertexBuffer.UV4Kind
  21694. * - BABYLON.VertexBuffer.UV5Kind
  21695. * - BABYLON.VertexBuffer.UV6Kind
  21696. * - BABYLON.VertexBuffer.ColorKind
  21697. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21698. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21699. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21700. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21701. */
  21702. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21703. if (!this._geometry) {
  21704. if (this._delayInfo) {
  21705. return this._delayInfo.indexOf(kind) !== -1;
  21706. }
  21707. return false;
  21708. }
  21709. return this._geometry.isVerticesDataPresent(kind);
  21710. };
  21711. /**
  21712. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21713. * Possible `kind` values :
  21714. * - BABYLON.VertexBuffer.PositionKind
  21715. * - BABYLON.VertexBuffer.UVKind
  21716. * - BABYLON.VertexBuffer.UV2Kind
  21717. * - BABYLON.VertexBuffer.UV3Kind
  21718. * - BABYLON.VertexBuffer.UV4Kind
  21719. * - BABYLON.VertexBuffer.UV5Kind
  21720. * - BABYLON.VertexBuffer.UV6Kind
  21721. * - BABYLON.VertexBuffer.ColorKind
  21722. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21723. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21724. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21725. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21726. */
  21727. Mesh.prototype.getVerticesDataKinds = function () {
  21728. if (!this._geometry) {
  21729. var result = [];
  21730. if (this._delayInfo) {
  21731. this._delayInfo.forEach(function (kind, index, array) {
  21732. result.push(kind);
  21733. });
  21734. }
  21735. return result;
  21736. }
  21737. return this._geometry.getVerticesDataKinds();
  21738. };
  21739. /**
  21740. * Returns a positive integer : the total number of indices in this mesh geometry.
  21741. * Returns zero if the mesh has no geometry.
  21742. */
  21743. Mesh.prototype.getTotalIndices = function () {
  21744. if (!this._geometry) {
  21745. return 0;
  21746. }
  21747. return this._geometry.getTotalIndices();
  21748. };
  21749. /**
  21750. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21751. * 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.
  21752. * Returns an empty array if the mesh has no geometry.
  21753. */
  21754. Mesh.prototype.getIndices = function (copyWhenShared) {
  21755. if (!this._geometry) {
  21756. return [];
  21757. }
  21758. return this._geometry.getIndices(copyWhenShared);
  21759. };
  21760. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21761. get: function () {
  21762. return this._masterMesh !== null && this._masterMesh !== undefined;
  21763. },
  21764. enumerable: true,
  21765. configurable: true
  21766. });
  21767. /**
  21768. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21769. */
  21770. Mesh.prototype.isReady = function () {
  21771. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21772. return false;
  21773. }
  21774. return _super.prototype.isReady.call(this);
  21775. };
  21776. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21777. get: function () {
  21778. return this._sideOrientation;
  21779. },
  21780. /**
  21781. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21782. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21783. */
  21784. set: function (sideO) {
  21785. this._sideOrientation = sideO;
  21786. },
  21787. enumerable: true,
  21788. configurable: true
  21789. });
  21790. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21791. /**
  21792. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21793. * This property is pertinent only for updatable parametric shapes.
  21794. */
  21795. get: function () {
  21796. return this._areNormalsFrozen;
  21797. },
  21798. enumerable: true,
  21799. configurable: true
  21800. });
  21801. /**
  21802. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21803. * It has no effect at all on other shapes.
  21804. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21805. * Returns the Mesh.
  21806. */
  21807. Mesh.prototype.freezeNormals = function () {
  21808. this._areNormalsFrozen = true;
  21809. return this;
  21810. };
  21811. /**
  21812. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21813. * It has no effect at all on other shapes.
  21814. * It reactivates the mesh normals computation if it was previously frozen.
  21815. * Returns the Mesh.
  21816. */
  21817. Mesh.prototype.unfreezeNormals = function () {
  21818. this._areNormalsFrozen = false;
  21819. return this;
  21820. };
  21821. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21822. /**
  21823. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21824. */
  21825. set: function (count) {
  21826. this._overridenInstanceCount = count;
  21827. },
  21828. enumerable: true,
  21829. configurable: true
  21830. });
  21831. // Methods
  21832. Mesh.prototype._preActivate = function () {
  21833. var sceneRenderId = this.getScene().getRenderId();
  21834. if (this._preActivateId === sceneRenderId) {
  21835. return this;
  21836. }
  21837. this._preActivateId = sceneRenderId;
  21838. this._visibleInstances = null;
  21839. return this;
  21840. };
  21841. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21842. if (this._visibleInstances) {
  21843. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21844. }
  21845. return this;
  21846. };
  21847. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21848. if (!this._visibleInstances) {
  21849. this._visibleInstances = {};
  21850. this._visibleInstances.defaultRenderId = renderId;
  21851. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21852. }
  21853. if (!this._visibleInstances[renderId]) {
  21854. this._visibleInstances[renderId] = new Array();
  21855. }
  21856. this._visibleInstances[renderId].push(instance);
  21857. return this;
  21858. };
  21859. /**
  21860. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21861. * This means the mesh underlying bounding box and sphere are recomputed.
  21862. * Returns the Mesh.
  21863. */
  21864. Mesh.prototype.refreshBoundingInfo = function () {
  21865. if (this._boundingInfo.isLocked) {
  21866. return;
  21867. }
  21868. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21869. if (data) {
  21870. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21871. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21872. }
  21873. if (this.subMeshes) {
  21874. for (var index = 0; index < this.subMeshes.length; index++) {
  21875. this.subMeshes[index].refreshBoundingInfo();
  21876. }
  21877. }
  21878. this._updateBoundingInfo();
  21879. return this;
  21880. };
  21881. Mesh.prototype._createGlobalSubMesh = function (force) {
  21882. var totalVertices = this.getTotalVertices();
  21883. if (!totalVertices || !this.getIndices()) {
  21884. return null;
  21885. }
  21886. // Check if we need to recreate the submeshes
  21887. if (this.subMeshes && this.subMeshes.length > 0) {
  21888. var totalIndices = this.getIndices().length;
  21889. var needToRecreate = false;
  21890. if (force) {
  21891. needToRecreate = true;
  21892. }
  21893. else {
  21894. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21895. var submesh = _a[_i];
  21896. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21897. needToRecreate = true;
  21898. break;
  21899. }
  21900. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21901. needToRecreate = true;
  21902. break;
  21903. }
  21904. }
  21905. }
  21906. if (!needToRecreate) {
  21907. return;
  21908. }
  21909. }
  21910. this.releaseSubMeshes();
  21911. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21912. };
  21913. Mesh.prototype.subdivide = function (count) {
  21914. if (count < 1) {
  21915. return;
  21916. }
  21917. var totalIndices = this.getTotalIndices();
  21918. var subdivisionSize = (totalIndices / count) | 0;
  21919. var offset = 0;
  21920. // Ensure that subdivisionSize is a multiple of 3
  21921. while (subdivisionSize % 3 !== 0) {
  21922. subdivisionSize++;
  21923. }
  21924. this.releaseSubMeshes();
  21925. for (var index = 0; index < count; index++) {
  21926. if (offset >= totalIndices) {
  21927. break;
  21928. }
  21929. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21930. offset += subdivisionSize;
  21931. }
  21932. this.synchronizeInstances();
  21933. };
  21934. /**
  21935. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21936. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21937. * The `data` are either a numeric array either a Float32Array.
  21938. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21939. * 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).
  21940. * Note that a new underlying VertexBuffer object is created each call.
  21941. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21942. *
  21943. * Possible `kind` values :
  21944. * - BABYLON.VertexBuffer.PositionKind
  21945. * - BABYLON.VertexBuffer.UVKind
  21946. * - BABYLON.VertexBuffer.UV2Kind
  21947. * - BABYLON.VertexBuffer.UV3Kind
  21948. * - BABYLON.VertexBuffer.UV4Kind
  21949. * - BABYLON.VertexBuffer.UV5Kind
  21950. * - BABYLON.VertexBuffer.UV6Kind
  21951. * - BABYLON.VertexBuffer.ColorKind
  21952. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21953. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21954. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21955. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21956. *
  21957. * Returns the Mesh.
  21958. */
  21959. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21960. if (!this._geometry) {
  21961. var vertexData = new BABYLON.VertexData();
  21962. vertexData.set(data, kind);
  21963. var scene = this.getScene();
  21964. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21965. }
  21966. else {
  21967. this._geometry.setVerticesData(kind, data, updatable, stride);
  21968. }
  21969. return this;
  21970. };
  21971. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21972. if (updatable === void 0) { updatable = true; }
  21973. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21974. return;
  21975. }
  21976. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21977. };
  21978. /**
  21979. * Sets the mesh VertexBuffer.
  21980. * Returns the Mesh.
  21981. */
  21982. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21983. if (!this._geometry) {
  21984. var scene = this.getScene();
  21985. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21986. }
  21987. this._geometry.setVerticesBuffer(buffer);
  21988. return this;
  21989. };
  21990. /**
  21991. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21992. * If the mesh has no geometry, it is simply returned as it is.
  21993. * The `data` are either a numeric array either a Float32Array.
  21994. * No new underlying VertexBuffer object is created.
  21995. * 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.
  21996. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21997. *
  21998. * Possible `kind` values :
  21999. * - BABYLON.VertexBuffer.PositionKind
  22000. * - BABYLON.VertexBuffer.UVKind
  22001. * - BABYLON.VertexBuffer.UV2Kind
  22002. * - BABYLON.VertexBuffer.UV3Kind
  22003. * - BABYLON.VertexBuffer.UV4Kind
  22004. * - BABYLON.VertexBuffer.UV5Kind
  22005. * - BABYLON.VertexBuffer.UV6Kind
  22006. * - BABYLON.VertexBuffer.ColorKind
  22007. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22008. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22009. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22010. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22011. *
  22012. * Returns the Mesh.
  22013. */
  22014. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  22015. if (!this._geometry) {
  22016. return;
  22017. }
  22018. if (!makeItUnique) {
  22019. this._geometry.updateVerticesData(kind, data, updateExtends);
  22020. }
  22021. else {
  22022. this.makeGeometryUnique();
  22023. this.updateVerticesData(kind, data, updateExtends, false);
  22024. }
  22025. return this;
  22026. };
  22027. /**
  22028. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  22029. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  22030. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  22031. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  22032. * Returns the Mesh.
  22033. */
  22034. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  22035. if (computeNormals === void 0) { computeNormals = true; }
  22036. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22037. positionFunction(positions);
  22038. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22039. if (computeNormals) {
  22040. var indices = this.getIndices();
  22041. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22042. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22043. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22044. }
  22045. return this;
  22046. };
  22047. /**
  22048. * Creates a un-shared specific occurence of the geometry for the mesh.
  22049. * Returns the Mesh.
  22050. */
  22051. Mesh.prototype.makeGeometryUnique = function () {
  22052. if (!this._geometry) {
  22053. return;
  22054. }
  22055. var oldGeometry = this._geometry;
  22056. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  22057. oldGeometry.releaseForMesh(this, true);
  22058. geometry.applyToMesh(this);
  22059. return this;
  22060. };
  22061. /**
  22062. * Sets the mesh indices.
  22063. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  22064. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  22065. * This method creates a new index buffer each call.
  22066. * Returns the Mesh.
  22067. */
  22068. Mesh.prototype.setIndices = function (indices, totalVertices) {
  22069. if (!this._geometry) {
  22070. var vertexData = new BABYLON.VertexData();
  22071. vertexData.indices = indices;
  22072. var scene = this.getScene();
  22073. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  22074. }
  22075. else {
  22076. this._geometry.setIndices(indices, totalVertices);
  22077. }
  22078. return this;
  22079. };
  22080. /**
  22081. * Invert the geometry to move from a right handed system to a left handed one.
  22082. * Returns the Mesh.
  22083. */
  22084. Mesh.prototype.toLeftHanded = function () {
  22085. if (!this._geometry) {
  22086. return;
  22087. }
  22088. this._geometry.toLeftHanded();
  22089. return this;
  22090. };
  22091. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  22092. var engine = this.getScene().getEngine();
  22093. // Wireframe
  22094. var indexToBind;
  22095. if (this._unIndexed) {
  22096. indexToBind = null;
  22097. }
  22098. else {
  22099. switch (fillMode) {
  22100. case BABYLON.Material.PointFillMode:
  22101. indexToBind = null;
  22102. break;
  22103. case BABYLON.Material.WireFrameFillMode:
  22104. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  22105. break;
  22106. default:
  22107. case BABYLON.Material.TriangleFillMode:
  22108. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  22109. break;
  22110. }
  22111. }
  22112. // VBOs
  22113. this._geometry._bind(effect, indexToBind);
  22114. return this;
  22115. };
  22116. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  22117. if (alternate === void 0) { alternate = false; }
  22118. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22119. return this;
  22120. }
  22121. this.onBeforeDrawObservable.notifyObservers(this);
  22122. var scene = this.getScene();
  22123. var engine = scene.getEngine();
  22124. // Draw order
  22125. switch (fillMode) {
  22126. case BABYLON.Material.PointFillMode:
  22127. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22128. break;
  22129. case BABYLON.Material.WireFrameFillMode:
  22130. if (this._unIndexed) {
  22131. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22132. }
  22133. else {
  22134. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  22135. }
  22136. break;
  22137. default:
  22138. if (this._unIndexed) {
  22139. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22140. }
  22141. else {
  22142. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  22143. }
  22144. }
  22145. if (scene._isAlternateRenderingEnabled && !alternate) {
  22146. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  22147. scene._switchToAlternateCameraConfiguration(true);
  22148. this._effectiveMaterial.bindView(effect);
  22149. this._effectiveMaterial.bindViewProjection(effect);
  22150. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  22151. this._draw(subMesh, fillMode, instancesCount, true);
  22152. engine.setViewport(scene.activeCamera.viewport);
  22153. scene._switchToAlternateCameraConfiguration(false);
  22154. this._effectiveMaterial.bindView(effect);
  22155. this._effectiveMaterial.bindViewProjection(effect);
  22156. }
  22157. return this;
  22158. };
  22159. /**
  22160. * Registers for this mesh a javascript function called just before the rendering process.
  22161. * This function is passed the current mesh.
  22162. * Return the Mesh.
  22163. */
  22164. Mesh.prototype.registerBeforeRender = function (func) {
  22165. this.onBeforeRenderObservable.add(func);
  22166. return this;
  22167. };
  22168. /**
  22169. * Disposes a previously registered javascript function called before the rendering.
  22170. * This function is passed the current mesh.
  22171. * Returns the Mesh.
  22172. */
  22173. Mesh.prototype.unregisterBeforeRender = function (func) {
  22174. this.onBeforeRenderObservable.removeCallback(func);
  22175. return this;
  22176. };
  22177. /**
  22178. * Registers for this mesh a javascript function called just after the rendering is complete.
  22179. * This function is passed the current mesh.
  22180. * Returns the Mesh.
  22181. */
  22182. Mesh.prototype.registerAfterRender = function (func) {
  22183. this.onAfterRenderObservable.add(func);
  22184. return this;
  22185. };
  22186. /**
  22187. * Disposes a previously registered javascript function called after the rendering.
  22188. * This function is passed the current mesh.
  22189. * Return the Mesh.
  22190. */
  22191. Mesh.prototype.unregisterAfterRender = function (func) {
  22192. this.onAfterRenderObservable.removeCallback(func);
  22193. return this;
  22194. };
  22195. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  22196. var scene = this.getScene();
  22197. this._batchCache.mustReturn = false;
  22198. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  22199. this._batchCache.visibleInstances[subMeshId] = null;
  22200. if (this._visibleInstances) {
  22201. var currentRenderId = scene.getRenderId();
  22202. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  22203. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  22204. var selfRenderId = this._renderId;
  22205. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  22206. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  22207. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  22208. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  22209. }
  22210. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  22211. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  22212. this._batchCache.mustReturn = true;
  22213. return this._batchCache;
  22214. }
  22215. if (currentRenderId !== selfRenderId) {
  22216. this._batchCache.renderSelf[subMeshId] = false;
  22217. }
  22218. }
  22219. this._renderIdForInstances[subMeshId] = currentRenderId;
  22220. }
  22221. return this._batchCache;
  22222. };
  22223. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  22224. var visibleInstances = batch.visibleInstances[subMesh._id];
  22225. var matricesCount = visibleInstances.length + 1;
  22226. var bufferSize = matricesCount * 16 * 4;
  22227. var currentInstancesBufferSize = this._instancesBufferSize;
  22228. var instancesBuffer = this._instancesBuffer;
  22229. while (this._instancesBufferSize < bufferSize) {
  22230. this._instancesBufferSize *= 2;
  22231. }
  22232. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  22233. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  22234. }
  22235. var offset = 0;
  22236. var instancesCount = 0;
  22237. var world = this.getWorldMatrix();
  22238. if (batch.renderSelf[subMesh._id]) {
  22239. world.copyToArray(this._instancesData, offset);
  22240. offset += 16;
  22241. instancesCount++;
  22242. }
  22243. if (visibleInstances) {
  22244. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  22245. var instance = visibleInstances[instanceIndex];
  22246. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  22247. offset += 16;
  22248. instancesCount++;
  22249. }
  22250. }
  22251. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  22252. if (instancesBuffer) {
  22253. instancesBuffer.dispose();
  22254. }
  22255. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  22256. this._instancesBuffer = instancesBuffer;
  22257. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  22258. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  22259. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  22260. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  22261. }
  22262. else {
  22263. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  22264. }
  22265. this._bind(subMesh, effect, fillMode);
  22266. this._draw(subMesh, fillMode, instancesCount);
  22267. engine.unbindInstanceAttributes();
  22268. return this;
  22269. };
  22270. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  22271. var scene = this.getScene();
  22272. var engine = scene.getEngine();
  22273. if (hardwareInstancedRendering) {
  22274. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  22275. }
  22276. else {
  22277. if (batch.renderSelf[subMesh._id]) {
  22278. // Draw
  22279. if (onBeforeDraw) {
  22280. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22281. }
  22282. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22283. }
  22284. if (batch.visibleInstances[subMesh._id]) {
  22285. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22286. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22287. // World
  22288. var world = instance.getWorldMatrix();
  22289. if (onBeforeDraw) {
  22290. onBeforeDraw(true, world, effectiveMaterial);
  22291. }
  22292. // Draw
  22293. this._draw(subMesh, fillMode);
  22294. }
  22295. }
  22296. }
  22297. return this;
  22298. };
  22299. /**
  22300. * Triggers the draw call for the mesh.
  22301. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22302. * Returns the Mesh.
  22303. */
  22304. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22305. this.checkOcclusionQuery();
  22306. if (this._isOccluded) {
  22307. return;
  22308. }
  22309. var scene = this.getScene();
  22310. // Managing instances
  22311. var batch = this._getInstancesRenderList(subMesh._id);
  22312. if (batch.mustReturn) {
  22313. return this;
  22314. }
  22315. // Checking geometry state
  22316. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22317. return this;
  22318. }
  22319. var callbackIndex;
  22320. this.onBeforeRenderObservable.notifyObservers(this);
  22321. var engine = scene.getEngine();
  22322. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22323. // Material
  22324. this._effectiveMaterial = subMesh.getMaterial();
  22325. if (!this._effectiveMaterial) {
  22326. return this;
  22327. }
  22328. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22329. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22330. return this;
  22331. }
  22332. }
  22333. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22334. return this;
  22335. }
  22336. // Alpha mode
  22337. if (enableAlphaMode) {
  22338. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  22339. }
  22340. // Outline - step 1
  22341. var savedDepthWrite = engine.getDepthWrite();
  22342. if (this.renderOutline) {
  22343. engine.setDepthWrite(false);
  22344. scene.getOutlineRenderer().render(subMesh, batch);
  22345. engine.setDepthWrite(savedDepthWrite);
  22346. }
  22347. var effect;
  22348. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22349. effect = subMesh.effect;
  22350. }
  22351. else {
  22352. effect = this._effectiveMaterial.getEffect();
  22353. }
  22354. this._effectiveMaterial._preBind(effect);
  22355. // Bind
  22356. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  22357. if (!hardwareInstancedRendering) {
  22358. this._bind(subMesh, effect, fillMode);
  22359. }
  22360. var world = this.getWorldMatrix();
  22361. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22362. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22363. }
  22364. else {
  22365. this._effectiveMaterial.bind(world, this);
  22366. }
  22367. // Draw
  22368. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22369. // Unbind
  22370. this._effectiveMaterial.unbind();
  22371. // Outline - step 2
  22372. if (this.renderOutline && savedDepthWrite) {
  22373. engine.setDepthWrite(true);
  22374. engine.setColorWrite(false);
  22375. scene.getOutlineRenderer().render(subMesh, batch);
  22376. engine.setColorWrite(true);
  22377. }
  22378. // Overlay
  22379. if (this.renderOverlay) {
  22380. var currentMode = engine.getAlphaMode();
  22381. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22382. scene.getOutlineRenderer().render(subMesh, batch, true);
  22383. engine.setAlphaMode(currentMode);
  22384. }
  22385. this.onAfterRenderObservable.notifyObservers(this);
  22386. return this;
  22387. };
  22388. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22389. if (isInstance) {
  22390. effectiveMaterial.bindOnlyWorldMatrix(world);
  22391. }
  22392. return this;
  22393. };
  22394. /**
  22395. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22396. */
  22397. Mesh.prototype.getEmittedParticleSystems = function () {
  22398. var results = new Array();
  22399. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22400. var particleSystem = this.getScene().particleSystems[index];
  22401. if (particleSystem.emitter === this) {
  22402. results.push(particleSystem);
  22403. }
  22404. }
  22405. return results;
  22406. };
  22407. /**
  22408. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22409. */
  22410. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22411. var results = new Array();
  22412. var descendants = this.getDescendants();
  22413. descendants.push(this);
  22414. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22415. var particleSystem = this.getScene().particleSystems[index];
  22416. var emitter = particleSystem.emitter;
  22417. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22418. results.push(particleSystem);
  22419. }
  22420. }
  22421. return results;
  22422. };
  22423. Mesh.prototype._checkDelayState = function () {
  22424. var scene = this.getScene();
  22425. if (this._geometry) {
  22426. this._geometry.load(scene);
  22427. }
  22428. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22429. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22430. this._queueLoad(this, scene);
  22431. }
  22432. return this;
  22433. };
  22434. Mesh.prototype._queueLoad = function (mesh, scene) {
  22435. var _this = this;
  22436. scene._addPendingData(mesh);
  22437. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22438. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22439. if (data instanceof ArrayBuffer) {
  22440. _this._delayLoadingFunction(data, _this);
  22441. }
  22442. else {
  22443. _this._delayLoadingFunction(JSON.parse(data), _this);
  22444. }
  22445. _this.instances.forEach(function (instance) {
  22446. instance._syncSubMeshes();
  22447. });
  22448. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22449. scene._removePendingData(_this);
  22450. }, function () { }, scene.database, getBinaryData);
  22451. return this;
  22452. };
  22453. /**
  22454. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22455. */
  22456. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22457. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22458. return false;
  22459. }
  22460. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22461. return false;
  22462. }
  22463. this._checkDelayState();
  22464. return true;
  22465. };
  22466. /**
  22467. * Sets the mesh material by the material or multiMaterial `id` property.
  22468. * The material `id` is a string identifying the material or the multiMaterial.
  22469. * This method returns the Mesh.
  22470. */
  22471. Mesh.prototype.setMaterialByID = function (id) {
  22472. var materials = this.getScene().materials;
  22473. var index;
  22474. for (index = materials.length - 1; index > -1; index--) {
  22475. if (materials[index].id === id) {
  22476. this.material = materials[index];
  22477. return this;
  22478. }
  22479. }
  22480. // Multi
  22481. var multiMaterials = this.getScene().multiMaterials;
  22482. for (index = multiMaterials.length - 1; index > -1; index--) {
  22483. if (multiMaterials[index].id === id) {
  22484. this.material = multiMaterials[index];
  22485. return this;
  22486. }
  22487. }
  22488. return this;
  22489. };
  22490. /**
  22491. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22492. */
  22493. Mesh.prototype.getAnimatables = function () {
  22494. var results = [];
  22495. if (this.material) {
  22496. results.push(this.material);
  22497. }
  22498. if (this.skeleton) {
  22499. results.push(this.skeleton);
  22500. }
  22501. return results;
  22502. };
  22503. /**
  22504. * Modifies the mesh geometry according to the passed transformation matrix.
  22505. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22506. * The mesh normals are modified accordingly the same transformation.
  22507. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22508. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22509. * Returns the Mesh.
  22510. */
  22511. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22512. // Position
  22513. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22514. return this;
  22515. }
  22516. var submeshes = this.subMeshes.splice(0);
  22517. this._resetPointsArrayCache();
  22518. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22519. var temp = [];
  22520. var index;
  22521. for (index = 0; index < data.length; index += 3) {
  22522. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22523. }
  22524. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22525. // Normals
  22526. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22527. return this;
  22528. }
  22529. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22530. temp = [];
  22531. for (index = 0; index < data.length; index += 3) {
  22532. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22533. }
  22534. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22535. // flip faces?
  22536. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22537. this.flipFaces();
  22538. }
  22539. // Restore submeshes
  22540. this.releaseSubMeshes();
  22541. this.subMeshes = submeshes;
  22542. return this;
  22543. };
  22544. /**
  22545. * Modifies the mesh geometry according to its own current World Matrix.
  22546. * The mesh World Matrix is then reset.
  22547. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22548. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22549. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22550. * Returns the Mesh.
  22551. */
  22552. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22553. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22554. this.scaling.copyFromFloats(1, 1, 1);
  22555. this.position.copyFromFloats(0, 0, 0);
  22556. this.rotation.copyFromFloats(0, 0, 0);
  22557. //only if quaternion is already set
  22558. if (this.rotationQuaternion) {
  22559. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22560. }
  22561. this._worldMatrix = BABYLON.Matrix.Identity();
  22562. return this;
  22563. };
  22564. Object.defineProperty(Mesh.prototype, "_positions", {
  22565. // Cache
  22566. get: function () {
  22567. if (this._geometry) {
  22568. return this._geometry._positions;
  22569. }
  22570. return null;
  22571. },
  22572. enumerable: true,
  22573. configurable: true
  22574. });
  22575. Mesh.prototype._resetPointsArrayCache = function () {
  22576. if (this._geometry) {
  22577. this._geometry._resetPointsArrayCache();
  22578. }
  22579. return this;
  22580. };
  22581. Mesh.prototype._generatePointsArray = function () {
  22582. if (this._geometry) {
  22583. return this._geometry._generatePointsArray();
  22584. }
  22585. return false;
  22586. };
  22587. /**
  22588. * Returns a new Mesh object generated from the current mesh properties.
  22589. * This method must not get confused with createInstance().
  22590. * The parameter `name` is a string, the name given to the new mesh.
  22591. * The optional parameter `newParent` can be any Node object (default `null`).
  22592. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22593. * 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.
  22594. */
  22595. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22596. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22597. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22598. };
  22599. /**
  22600. * Disposes the mesh.
  22601. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22602. */
  22603. Mesh.prototype.dispose = function (doNotRecurse) {
  22604. var _this = this;
  22605. this.morphTargetManager = undefined;
  22606. if (this._geometry) {
  22607. this._geometry.releaseForMesh(this, true);
  22608. }
  22609. // Sources
  22610. var meshes = this.getScene().meshes;
  22611. meshes.forEach(function (mesh) {
  22612. if (mesh._source && mesh._source === _this) {
  22613. mesh._source = null;
  22614. }
  22615. });
  22616. this._source = null;
  22617. // Instances
  22618. if (this._instancesBuffer) {
  22619. this._instancesBuffer.dispose();
  22620. this._instancesBuffer = null;
  22621. }
  22622. while (this.instances.length) {
  22623. this.instances[0].dispose();
  22624. }
  22625. // Highlight layers.
  22626. var highlightLayers = this.getScene().highlightLayers;
  22627. for (var i = 0; i < highlightLayers.length; i++) {
  22628. var highlightLayer = highlightLayers[i];
  22629. if (highlightLayer) {
  22630. highlightLayer.removeMesh(this);
  22631. highlightLayer.removeExcludedMesh(this);
  22632. }
  22633. }
  22634. _super.prototype.dispose.call(this, doNotRecurse);
  22635. };
  22636. /**
  22637. * Modifies the mesh geometry according to a displacement map.
  22638. * 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.
  22639. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22640. * This method returns nothing.
  22641. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22642. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22643. * 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.
  22644. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22645. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22646. *
  22647. * Returns the Mesh.
  22648. */
  22649. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22650. var _this = this;
  22651. var scene = this.getScene();
  22652. var onload = function (img) {
  22653. // Getting height map data
  22654. var canvas = document.createElement("canvas");
  22655. var context = canvas.getContext("2d");
  22656. var heightMapWidth = img.width;
  22657. var heightMapHeight = img.height;
  22658. canvas.width = heightMapWidth;
  22659. canvas.height = heightMapHeight;
  22660. context.drawImage(img, 0, 0);
  22661. // Create VertexData from map data
  22662. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22663. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22664. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22665. //execute success callback, if set
  22666. if (onSuccess) {
  22667. onSuccess(_this);
  22668. }
  22669. };
  22670. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22671. return this;
  22672. };
  22673. /**
  22674. * Modifies the mesh geometry according to a displacementMap buffer.
  22675. * 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.
  22676. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22677. * This method returns nothing.
  22678. * 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.
  22679. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22680. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22681. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22682. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22683. *
  22684. * Returns the Mesh.
  22685. */
  22686. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22687. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22688. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22689. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22690. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22691. return this;
  22692. }
  22693. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22694. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22695. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22696. var position = BABYLON.Vector3.Zero();
  22697. var normal = BABYLON.Vector3.Zero();
  22698. var uv = BABYLON.Vector2.Zero();
  22699. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22700. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22701. for (var index = 0; index < positions.length; index += 3) {
  22702. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22703. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22704. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22705. // Compute height
  22706. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22707. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22708. var pos = (u + v * heightMapWidth) * 4;
  22709. var r = buffer[pos] / 255.0;
  22710. var g = buffer[pos + 1] / 255.0;
  22711. var b = buffer[pos + 2] / 255.0;
  22712. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22713. normal.normalize();
  22714. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22715. position = position.add(normal);
  22716. position.toArray(positions, index);
  22717. }
  22718. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22719. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22720. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22721. return this;
  22722. };
  22723. /**
  22724. * Modify the mesh to get a flat shading rendering.
  22725. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22726. * This method returns the Mesh.
  22727. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22728. */
  22729. Mesh.prototype.convertToFlatShadedMesh = function () {
  22730. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22731. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22732. var kinds = this.getVerticesDataKinds();
  22733. var vbs = [];
  22734. var data = [];
  22735. var newdata = [];
  22736. var updatableNormals = false;
  22737. var kindIndex;
  22738. var kind;
  22739. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22740. kind = kinds[kindIndex];
  22741. var vertexBuffer = this.getVertexBuffer(kind);
  22742. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22743. updatableNormals = vertexBuffer.isUpdatable();
  22744. kinds.splice(kindIndex, 1);
  22745. kindIndex--;
  22746. continue;
  22747. }
  22748. vbs[kind] = vertexBuffer;
  22749. data[kind] = vbs[kind].getData();
  22750. newdata[kind] = [];
  22751. }
  22752. // Save previous submeshes
  22753. var previousSubmeshes = this.subMeshes.slice(0);
  22754. var indices = this.getIndices();
  22755. var totalIndices = this.getTotalIndices();
  22756. // Generating unique vertices per face
  22757. var index;
  22758. for (index = 0; index < totalIndices; index++) {
  22759. var vertexIndex = indices[index];
  22760. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22761. kind = kinds[kindIndex];
  22762. var stride = vbs[kind].getStrideSize();
  22763. for (var offset = 0; offset < stride; offset++) {
  22764. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22765. }
  22766. }
  22767. }
  22768. // Updating faces & normal
  22769. var normals = [];
  22770. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22771. for (index = 0; index < totalIndices; index += 3) {
  22772. indices[index] = index;
  22773. indices[index + 1] = index + 1;
  22774. indices[index + 2] = index + 2;
  22775. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22776. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22777. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22778. var p1p2 = p1.subtract(p2);
  22779. var p3p2 = p3.subtract(p2);
  22780. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22781. // Store same normals for every vertex
  22782. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22783. normals.push(normal.x);
  22784. normals.push(normal.y);
  22785. normals.push(normal.z);
  22786. }
  22787. }
  22788. this.setIndices(indices);
  22789. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22790. // Updating vertex buffers
  22791. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22792. kind = kinds[kindIndex];
  22793. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22794. }
  22795. // Updating submeshes
  22796. this.releaseSubMeshes();
  22797. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22798. var previousOne = previousSubmeshes[submeshIndex];
  22799. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22800. }
  22801. this.synchronizeInstances();
  22802. return this;
  22803. };
  22804. /**
  22805. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22806. * In other words, more vertices, no more indices and a single bigger VBO.
  22807. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22808. * Returns the Mesh.
  22809. */
  22810. Mesh.prototype.convertToUnIndexedMesh = function () {
  22811. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22812. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22813. var kinds = this.getVerticesDataKinds();
  22814. var vbs = [];
  22815. var data = [];
  22816. var newdata = [];
  22817. var updatableNormals = false;
  22818. var kindIndex;
  22819. var kind;
  22820. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22821. kind = kinds[kindIndex];
  22822. var vertexBuffer = this.getVertexBuffer(kind);
  22823. vbs[kind] = vertexBuffer;
  22824. data[kind] = vbs[kind].getData();
  22825. newdata[kind] = [];
  22826. }
  22827. // Save previous submeshes
  22828. var previousSubmeshes = this.subMeshes.slice(0);
  22829. var indices = this.getIndices();
  22830. var totalIndices = this.getTotalIndices();
  22831. // Generating unique vertices per face
  22832. var index;
  22833. for (index = 0; index < totalIndices; index++) {
  22834. var vertexIndex = indices[index];
  22835. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22836. kind = kinds[kindIndex];
  22837. var stride = vbs[kind].getStrideSize();
  22838. for (var offset = 0; offset < stride; offset++) {
  22839. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22840. }
  22841. }
  22842. }
  22843. // Updating indices
  22844. for (index = 0; index < totalIndices; index += 3) {
  22845. indices[index] = index;
  22846. indices[index + 1] = index + 1;
  22847. indices[index + 2] = index + 2;
  22848. }
  22849. this.setIndices(indices);
  22850. // Updating vertex buffers
  22851. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22852. kind = kinds[kindIndex];
  22853. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22854. }
  22855. // Updating submeshes
  22856. this.releaseSubMeshes();
  22857. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22858. var previousOne = previousSubmeshes[submeshIndex];
  22859. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22860. }
  22861. this._unIndexed = true;
  22862. this.synchronizeInstances();
  22863. return this;
  22864. };
  22865. /**
  22866. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22867. * This method returns the Mesh.
  22868. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22869. */
  22870. Mesh.prototype.flipFaces = function (flipNormals) {
  22871. if (flipNormals === void 0) { flipNormals = false; }
  22872. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22873. var i;
  22874. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22875. for (i = 0; i < vertex_data.normals.length; i++) {
  22876. vertex_data.normals[i] *= -1;
  22877. }
  22878. }
  22879. var temp;
  22880. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22881. // reassign indices
  22882. temp = vertex_data.indices[i + 1];
  22883. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22884. vertex_data.indices[i + 2] = temp;
  22885. }
  22886. vertex_data.applyToMesh(this);
  22887. return this;
  22888. };
  22889. // Instances
  22890. /**
  22891. * Creates a new InstancedMesh object from the mesh model.
  22892. * An instance shares the same properties and the same material than its model.
  22893. * Only these properties of each instance can then be set individually :
  22894. * - position
  22895. * - rotation
  22896. * - rotationQuaternion
  22897. * - setPivotMatrix
  22898. * - scaling
  22899. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22900. * Warning : this method is not supported for Line mesh and LineSystem
  22901. */
  22902. Mesh.prototype.createInstance = function (name) {
  22903. return new BABYLON.InstancedMesh(name, this);
  22904. };
  22905. /**
  22906. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22907. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22908. * This method returns the Mesh.
  22909. */
  22910. Mesh.prototype.synchronizeInstances = function () {
  22911. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22912. var instance = this.instances[instanceIndex];
  22913. instance._syncSubMeshes();
  22914. }
  22915. return this;
  22916. };
  22917. /**
  22918. * Simplify the mesh according to the given array of settings.
  22919. * Function will return immediately and will simplify async. It returns the Mesh.
  22920. * @param settings a collection of simplification settings.
  22921. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22922. * @param type the type of simplification to run.
  22923. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22924. */
  22925. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22926. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22927. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22928. this.getScene().simplificationQueue.addTask({
  22929. settings: settings,
  22930. parallelProcessing: parallelProcessing,
  22931. mesh: this,
  22932. simplificationType: simplificationType,
  22933. successCallback: successCallback
  22934. });
  22935. return this;
  22936. };
  22937. /**
  22938. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22939. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22940. * This should be used together with the simplification to avoid disappearing triangles.
  22941. * Returns the Mesh.
  22942. * @param successCallback an optional success callback to be called after the optimization finished.
  22943. */
  22944. Mesh.prototype.optimizeIndices = function (successCallback) {
  22945. var _this = this;
  22946. var indices = this.getIndices();
  22947. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22948. var vectorPositions = [];
  22949. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22950. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22951. }
  22952. var dupes = [];
  22953. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22954. var realPos = vectorPositions.length - 1 - iteration;
  22955. var testedPosition = vectorPositions[realPos];
  22956. for (var j = 0; j < realPos; ++j) {
  22957. var againstPosition = vectorPositions[j];
  22958. if (testedPosition.equals(againstPosition)) {
  22959. dupes[realPos] = j;
  22960. break;
  22961. }
  22962. }
  22963. }, function () {
  22964. for (var i = 0; i < indices.length; ++i) {
  22965. indices[i] = dupes[indices[i]] || indices[i];
  22966. }
  22967. //indices are now reordered
  22968. var originalSubMeshes = _this.subMeshes.slice(0);
  22969. _this.setIndices(indices);
  22970. _this.subMeshes = originalSubMeshes;
  22971. if (successCallback) {
  22972. successCallback(_this);
  22973. }
  22974. });
  22975. return this;
  22976. };
  22977. Mesh.prototype.serialize = function (serializationObject) {
  22978. serializationObject.name = this.name;
  22979. serializationObject.id = this.id;
  22980. serializationObject.type = this.getClassName();
  22981. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22982. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22983. }
  22984. serializationObject.position = this.position.asArray();
  22985. if (this.rotationQuaternion) {
  22986. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22987. }
  22988. else if (this.rotation) {
  22989. serializationObject.rotation = this.rotation.asArray();
  22990. }
  22991. serializationObject.scaling = this.scaling.asArray();
  22992. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22993. serializationObject.isEnabled = this.isEnabled();
  22994. serializationObject.isVisible = this.isVisible;
  22995. serializationObject.infiniteDistance = this.infiniteDistance;
  22996. serializationObject.pickable = this.isPickable;
  22997. serializationObject.receiveShadows = this.receiveShadows;
  22998. serializationObject.billboardMode = this.billboardMode;
  22999. serializationObject.visibility = this.visibility;
  23000. serializationObject.checkCollisions = this.checkCollisions;
  23001. serializationObject.isBlocker = this.isBlocker;
  23002. // Parent
  23003. if (this.parent) {
  23004. serializationObject.parentId = this.parent.id;
  23005. }
  23006. // Geometry
  23007. var geometry = this._geometry;
  23008. if (geometry) {
  23009. var geometryId = geometry.id;
  23010. serializationObject.geometryId = geometryId;
  23011. // SubMeshes
  23012. serializationObject.subMeshes = [];
  23013. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  23014. var subMesh = this.subMeshes[subIndex];
  23015. serializationObject.subMeshes.push({
  23016. materialIndex: subMesh.materialIndex,
  23017. verticesStart: subMesh.verticesStart,
  23018. verticesCount: subMesh.verticesCount,
  23019. indexStart: subMesh.indexStart,
  23020. indexCount: subMesh.indexCount
  23021. });
  23022. }
  23023. }
  23024. // Material
  23025. if (this.material) {
  23026. serializationObject.materialId = this.material.id;
  23027. }
  23028. else {
  23029. this.material = null;
  23030. }
  23031. // Morph targets
  23032. if (this.morphTargetManager) {
  23033. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  23034. }
  23035. // Skeleton
  23036. if (this.skeleton) {
  23037. serializationObject.skeletonId = this.skeleton.id;
  23038. }
  23039. // Physics
  23040. //TODO implement correct serialization for physics impostors.
  23041. if (this.getPhysicsImpostor()) {
  23042. var impostor = this.getPhysicsImpostor();
  23043. serializationObject.physicsMass = impostor.getParam("mass");
  23044. serializationObject.physicsFriction = impostor.getParam("friction");
  23045. serializationObject.physicsRestitution = impostor.getParam("mass");
  23046. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  23047. }
  23048. // Metadata
  23049. if (this.metadata) {
  23050. serializationObject.metadata = this.metadata;
  23051. }
  23052. // Instances
  23053. serializationObject.instances = [];
  23054. for (var index = 0; index < this.instances.length; index++) {
  23055. var instance = this.instances[index];
  23056. var serializationInstance = {
  23057. name: instance.name,
  23058. position: instance.position.asArray(),
  23059. scaling: instance.scaling.asArray()
  23060. };
  23061. if (instance.rotationQuaternion) {
  23062. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  23063. }
  23064. else if (instance.rotation) {
  23065. serializationInstance.rotation = instance.rotation.asArray();
  23066. }
  23067. serializationObject.instances.push(serializationInstance);
  23068. // Animations
  23069. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  23070. serializationInstance.ranges = instance.serializeAnimationRanges();
  23071. }
  23072. //
  23073. // Animations
  23074. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23075. serializationObject.ranges = this.serializeAnimationRanges();
  23076. // Layer mask
  23077. serializationObject.layerMask = this.layerMask;
  23078. // Alpha
  23079. serializationObject.alphaIndex = this.alphaIndex;
  23080. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  23081. // Overlay
  23082. serializationObject.overlayAlpha = this.overlayAlpha;
  23083. serializationObject.overlayColor = this.overlayColor.asArray();
  23084. serializationObject.renderOverlay = this.renderOverlay;
  23085. // Fog
  23086. serializationObject.applyFog = this.applyFog;
  23087. // Action Manager
  23088. if (this.actionManager) {
  23089. serializationObject.actions = this.actionManager.serialize(this.name);
  23090. }
  23091. };
  23092. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  23093. if (!this.geometry) {
  23094. return;
  23095. }
  23096. this._markSubMeshesAsAttributesDirty();
  23097. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  23098. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  23099. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  23100. this.morphTargetManager = undefined;
  23101. return;
  23102. }
  23103. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  23104. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  23105. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  23106. if (morphTarget.hasNormals) {
  23107. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  23108. }
  23109. if (morphTarget.hasTangents) {
  23110. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  23111. }
  23112. }
  23113. }
  23114. else {
  23115. var index = 0;
  23116. // Positions
  23117. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  23118. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  23119. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  23120. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  23121. }
  23122. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  23123. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  23124. }
  23125. index++;
  23126. }
  23127. }
  23128. };
  23129. // Statics
  23130. /**
  23131. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23132. * The parameter `parsedMesh` is the mesh to be copied.
  23133. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23134. */
  23135. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  23136. var mesh;
  23137. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  23138. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  23139. }
  23140. else {
  23141. mesh = new Mesh(parsedMesh.name, scene);
  23142. }
  23143. mesh.id = parsedMesh.id;
  23144. if (BABYLON.Tags) {
  23145. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23146. }
  23147. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23148. if (parsedMesh.metadata !== undefined) {
  23149. mesh.metadata = parsedMesh.metadata;
  23150. }
  23151. if (parsedMesh.rotationQuaternion) {
  23152. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23153. }
  23154. else if (parsedMesh.rotation) {
  23155. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23156. }
  23157. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23158. if (parsedMesh.localMatrix) {
  23159. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23160. }
  23161. else if (parsedMesh.pivotMatrix) {
  23162. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23163. }
  23164. mesh.setEnabled(parsedMesh.isEnabled);
  23165. mesh.isVisible = parsedMesh.isVisible;
  23166. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23167. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23168. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23169. if (parsedMesh.applyFog !== undefined) {
  23170. mesh.applyFog = parsedMesh.applyFog;
  23171. }
  23172. if (parsedMesh.pickable !== undefined) {
  23173. mesh.isPickable = parsedMesh.pickable;
  23174. }
  23175. if (parsedMesh.alphaIndex !== undefined) {
  23176. mesh.alphaIndex = parsedMesh.alphaIndex;
  23177. }
  23178. mesh.receiveShadows = parsedMesh.receiveShadows;
  23179. mesh.billboardMode = parsedMesh.billboardMode;
  23180. if (parsedMesh.visibility !== undefined) {
  23181. mesh.visibility = parsedMesh.visibility;
  23182. }
  23183. mesh.checkCollisions = parsedMesh.checkCollisions;
  23184. if (parsedMesh.isBlocker !== undefined) {
  23185. mesh.isBlocker = parsedMesh.isBlocker;
  23186. }
  23187. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23188. // freezeWorldMatrix
  23189. if (parsedMesh.freezeWorldMatrix) {
  23190. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23191. }
  23192. // Parent
  23193. if (parsedMesh.parentId) {
  23194. mesh._waitingParentId = parsedMesh.parentId;
  23195. }
  23196. // Actions
  23197. if (parsedMesh.actions !== undefined) {
  23198. mesh._waitingActions = parsedMesh.actions;
  23199. }
  23200. // Overlay
  23201. if (parsedMesh.overlayAlpha !== undefined) {
  23202. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23203. }
  23204. if (parsedMesh.overlayColor !== undefined) {
  23205. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23206. }
  23207. if (parsedMesh.renderOverlay !== undefined) {
  23208. mesh.renderOverlay = parsedMesh.renderOverlay;
  23209. }
  23210. // Geometry
  23211. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23212. if (parsedMesh.delayLoadingFile) {
  23213. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23214. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23215. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23216. if (parsedMesh._binaryInfo) {
  23217. mesh._binaryInfo = parsedMesh._binaryInfo;
  23218. }
  23219. mesh._delayInfo = [];
  23220. if (parsedMesh.hasUVs) {
  23221. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23222. }
  23223. if (parsedMesh.hasUVs2) {
  23224. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23225. }
  23226. if (parsedMesh.hasUVs3) {
  23227. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23228. }
  23229. if (parsedMesh.hasUVs4) {
  23230. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23231. }
  23232. if (parsedMesh.hasUVs5) {
  23233. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23234. }
  23235. if (parsedMesh.hasUVs6) {
  23236. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23237. }
  23238. if (parsedMesh.hasColors) {
  23239. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23240. }
  23241. if (parsedMesh.hasMatricesIndices) {
  23242. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23243. }
  23244. if (parsedMesh.hasMatricesWeights) {
  23245. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23246. }
  23247. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23248. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23249. mesh._checkDelayState();
  23250. }
  23251. }
  23252. else {
  23253. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23254. }
  23255. // Material
  23256. if (parsedMesh.materialId) {
  23257. mesh.setMaterialByID(parsedMesh.materialId);
  23258. }
  23259. else {
  23260. mesh.material = null;
  23261. }
  23262. // Morph targets
  23263. if (parsedMesh.morphTargetManagerId > -1) {
  23264. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  23265. }
  23266. // Skeleton
  23267. if (parsedMesh.skeletonId > -1) {
  23268. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23269. if (parsedMesh.numBoneInfluencers) {
  23270. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23271. }
  23272. }
  23273. // Animations
  23274. if (parsedMesh.animations) {
  23275. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23276. var parsedAnimation = parsedMesh.animations[animationIndex];
  23277. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23278. }
  23279. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23280. }
  23281. if (parsedMesh.autoAnimate) {
  23282. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23283. }
  23284. // Layer Mask
  23285. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23286. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23287. }
  23288. else {
  23289. mesh.layerMask = 0x0FFFFFFF;
  23290. }
  23291. // Physics
  23292. if (parsedMesh.physicsImpostor) {
  23293. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23294. mass: parsedMesh.physicsMass,
  23295. friction: parsedMesh.physicsFriction,
  23296. restitution: parsedMesh.physicsRestitution
  23297. }, scene);
  23298. }
  23299. // Instances
  23300. if (parsedMesh.instances) {
  23301. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23302. var parsedInstance = parsedMesh.instances[index];
  23303. var instance = mesh.createInstance(parsedInstance.name);
  23304. if (BABYLON.Tags) {
  23305. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23306. }
  23307. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23308. if (parsedInstance.parentId) {
  23309. instance._waitingParentId = parsedInstance.parentId;
  23310. }
  23311. if (parsedInstance.rotationQuaternion) {
  23312. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23313. }
  23314. else if (parsedInstance.rotation) {
  23315. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23316. }
  23317. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23318. instance.checkCollisions = mesh.checkCollisions;
  23319. if (parsedMesh.animations) {
  23320. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23321. parsedAnimation = parsedMesh.animations[animationIndex];
  23322. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23323. }
  23324. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23325. }
  23326. }
  23327. }
  23328. return mesh;
  23329. };
  23330. /**
  23331. * Creates a ribbon mesh.
  23332. * Please consider using the same method from the MeshBuilder class instead.
  23333. * 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.
  23334. *
  23335. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23336. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23337. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23338. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23339. * 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.
  23340. * 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.
  23341. * 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
  23342. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23343. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23344. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23345. */
  23346. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23347. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23348. pathArray: pathArray,
  23349. closeArray: closeArray,
  23350. closePath: closePath,
  23351. offset: offset,
  23352. updatable: updatable,
  23353. sideOrientation: sideOrientation,
  23354. instance: instance
  23355. }, scene);
  23356. };
  23357. /**
  23358. * Creates a plane polygonal mesh. By default, this is a disc.
  23359. * Please consider using the same method from the MeshBuilder class instead.
  23360. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23361. * 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.
  23362. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23363. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23365. */
  23366. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23367. var options = {
  23368. radius: radius,
  23369. tessellation: tessellation,
  23370. sideOrientation: sideOrientation,
  23371. updatable: updatable
  23372. };
  23373. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23374. };
  23375. /**
  23376. * Creates a box mesh.
  23377. * Please consider using the same method from the MeshBuilder class instead.
  23378. * The parameter `size` sets the size (float) of each box side (default 1).
  23379. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23380. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23381. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23382. */
  23383. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23384. var options = {
  23385. size: size,
  23386. sideOrientation: sideOrientation,
  23387. updatable: updatable
  23388. };
  23389. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23390. };
  23391. /**
  23392. * Creates a sphere mesh.
  23393. * Please consider using the same method from the MeshBuilder class instead.
  23394. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23395. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23396. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23397. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23398. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23399. */
  23400. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23401. var options = {
  23402. segments: segments,
  23403. diameterX: diameter,
  23404. diameterY: diameter,
  23405. diameterZ: diameter,
  23406. sideOrientation: sideOrientation,
  23407. updatable: updatable
  23408. };
  23409. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23410. };
  23411. /**
  23412. * Creates a cylinder or a cone mesh.
  23413. * Please consider using the same method from the MeshBuilder class instead.
  23414. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23415. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23416. * 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.
  23417. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23418. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23419. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23420. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23421. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23422. */
  23423. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23424. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23425. if (scene !== undefined) {
  23426. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23427. updatable = scene;
  23428. }
  23429. scene = subdivisions;
  23430. subdivisions = 1;
  23431. }
  23432. var options = {
  23433. height: height,
  23434. diameterTop: diameterTop,
  23435. diameterBottom: diameterBottom,
  23436. tessellation: tessellation,
  23437. subdivisions: subdivisions,
  23438. sideOrientation: sideOrientation,
  23439. updatable: updatable
  23440. };
  23441. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23442. };
  23443. // Torus (Code from SharpDX.org)
  23444. /**
  23445. * Creates a torus mesh.
  23446. * Please consider using the same method from the MeshBuilder class instead.
  23447. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23448. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23449. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23450. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23451. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23453. */
  23454. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23455. var options = {
  23456. diameter: diameter,
  23457. thickness: thickness,
  23458. tessellation: tessellation,
  23459. sideOrientation: sideOrientation,
  23460. updatable: updatable
  23461. };
  23462. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23463. };
  23464. /**
  23465. * Creates a torus knot mesh.
  23466. * Please consider using the same method from the MeshBuilder class instead.
  23467. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23468. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23469. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23470. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23472. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23474. */
  23475. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23476. var options = {
  23477. radius: radius,
  23478. tube: tube,
  23479. radialSegments: radialSegments,
  23480. tubularSegments: tubularSegments,
  23481. p: p,
  23482. q: q,
  23483. sideOrientation: sideOrientation,
  23484. updatable: updatable
  23485. };
  23486. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23487. };
  23488. /**
  23489. * Creates a line mesh.
  23490. * Please consider using the same method from the MeshBuilder class instead.
  23491. * 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.
  23492. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23493. * The parameter `points` is an array successive Vector3.
  23494. * 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
  23495. * When updating an instance, remember that only point positions can change, not the number of points.
  23496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23497. */
  23498. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23499. var options = {
  23500. points: points,
  23501. updatable: updatable,
  23502. instance: instance
  23503. };
  23504. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23505. };
  23506. /**
  23507. * Creates a dashed line mesh.
  23508. * Please consider using the same method from the MeshBuilder class instead.
  23509. * 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.
  23510. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23511. * The parameter `points` is an array successive Vector3.
  23512. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23513. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23514. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23515. * 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
  23516. * When updating an instance, remember that only point positions can change, not the number of points.
  23517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23518. */
  23519. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23520. var options = {
  23521. points: points,
  23522. dashSize: dashSize,
  23523. gapSize: gapSize,
  23524. dashNb: dashNb,
  23525. updatable: updatable,
  23526. instance: instance
  23527. };
  23528. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23529. };
  23530. /**
  23531. * Creates a polygon mesh.
  23532. * Please consider using the same method from the MeshBuilder class instead.
  23533. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23534. * 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.
  23535. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23537. * Remember you can only change the shape positions, not their number when updating a polygon.
  23538. */
  23539. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23540. var options = {
  23541. shape: shape,
  23542. holes: holes,
  23543. updatable: updatable,
  23544. sideOrientation: sideOrientation
  23545. };
  23546. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23547. };
  23548. /**
  23549. * Creates an extruded polygon mesh, with depth in the Y direction.
  23550. * Please consider using the same method from the MeshBuilder class instead.
  23551. */
  23552. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23553. var options = {
  23554. shape: shape,
  23555. holes: holes,
  23556. depth: depth,
  23557. updatable: updatable,
  23558. sideOrientation: sideOrientation
  23559. };
  23560. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23561. };
  23562. /**
  23563. * Creates an extruded shape mesh.
  23564. * 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.
  23565. * Please consider using the same method from the MeshBuilder class instead.
  23566. *
  23567. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23568. * 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
  23569. * extruded along the Z axis.
  23570. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23571. * 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.
  23572. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23573. * 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
  23574. * 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
  23575. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23579. */
  23580. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23581. var options = {
  23582. shape: shape,
  23583. path: path,
  23584. scale: scale,
  23585. rotation: rotation,
  23586. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23587. sideOrientation: sideOrientation,
  23588. instance: instance,
  23589. updatable: updatable
  23590. };
  23591. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23592. };
  23593. /**
  23594. * Creates an custom extruded shape mesh.
  23595. * 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.
  23596. * Please consider using the same method from the MeshBuilder class instead.
  23597. *
  23598. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23599. * 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
  23600. * extruded along the Z axis.
  23601. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23602. * 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
  23603. * and the distance of this point from the begining of the path :
  23604. * ```javascript
  23605. * var rotationFunction = function(i, distance) {
  23606. * // do things
  23607. * return rotationValue; }
  23608. * ```
  23609. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23610. * 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
  23611. * and the distance of this point from the begining of the path :
  23612. * ```javascript
  23613. * var scaleFunction = function(i, distance) {
  23614. * // do things
  23615. * return scaleValue;}
  23616. * ```
  23617. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23618. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23619. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23620. * 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
  23621. * 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
  23622. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23624. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23625. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23626. */
  23627. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23628. var options = {
  23629. shape: shape,
  23630. path: path,
  23631. scaleFunction: scaleFunction,
  23632. rotationFunction: rotationFunction,
  23633. ribbonCloseArray: ribbonCloseArray,
  23634. ribbonClosePath: ribbonClosePath,
  23635. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23636. sideOrientation: sideOrientation,
  23637. instance: instance,
  23638. updatable: updatable
  23639. };
  23640. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23641. };
  23642. /**
  23643. * Creates lathe mesh.
  23644. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23645. * Please consider using the same method from the MeshBuilder class instead.
  23646. * 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
  23647. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23648. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23649. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23650. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23651. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23652. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23653. */
  23654. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23655. var options = {
  23656. shape: shape,
  23657. radius: radius,
  23658. tessellation: tessellation,
  23659. sideOrientation: sideOrientation,
  23660. updatable: updatable
  23661. };
  23662. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23663. };
  23664. /**
  23665. * Creates a plane mesh.
  23666. * Please consider using the same method from the MeshBuilder class instead.
  23667. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23668. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23669. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23671. */
  23672. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23673. var options = {
  23674. size: size,
  23675. width: size,
  23676. height: size,
  23677. sideOrientation: sideOrientation,
  23678. updatable: updatable
  23679. };
  23680. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23681. };
  23682. /**
  23683. * Creates a ground mesh.
  23684. * Please consider using the same method from the MeshBuilder class instead.
  23685. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23686. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23687. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23688. */
  23689. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23690. var options = {
  23691. width: width,
  23692. height: height,
  23693. subdivisions: subdivisions,
  23694. updatable: updatable
  23695. };
  23696. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23697. };
  23698. /**
  23699. * Creates a tiled ground mesh.
  23700. * Please consider using the same method from the MeshBuilder class instead.
  23701. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23702. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23703. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23704. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23705. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23706. * numbers of subdivisions on the ground width and height of each tile.
  23707. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23708. */
  23709. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23710. var options = {
  23711. xmin: xmin,
  23712. zmin: zmin,
  23713. xmax: xmax,
  23714. zmax: zmax,
  23715. subdivisions: subdivisions,
  23716. precision: precision,
  23717. updatable: updatable
  23718. };
  23719. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23720. };
  23721. /**
  23722. * Creates a ground mesh from a height map.
  23723. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23724. * Please consider using the same method from the MeshBuilder class instead.
  23725. * The parameter `url` sets the URL of the height map image resource.
  23726. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23727. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23728. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23729. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23730. * 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).
  23731. * This function is passed the newly built mesh :
  23732. * ```javascript
  23733. * function(mesh) { // do things
  23734. * return; }
  23735. * ```
  23736. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23737. */
  23738. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23739. var options = {
  23740. width: width,
  23741. height: height,
  23742. subdivisions: subdivisions,
  23743. minHeight: minHeight,
  23744. maxHeight: maxHeight,
  23745. updatable: updatable,
  23746. onReady: onReady
  23747. };
  23748. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23749. };
  23750. /**
  23751. * Creates a tube mesh.
  23752. * 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.
  23753. * Please consider using the same method from the MeshBuilder class instead.
  23754. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23755. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23756. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23757. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23758. * 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.
  23759. * It must return a radius value (positive float) :
  23760. * ```javascript
  23761. * var radiusFunction = function(i, distance) {
  23762. * // do things
  23763. * return radius; }
  23764. * ```
  23765. * 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
  23766. * 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
  23767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23768. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23770. */
  23771. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23772. var options = {
  23773. path: path,
  23774. radius: radius,
  23775. tessellation: tessellation,
  23776. radiusFunction: radiusFunction,
  23777. arc: 1,
  23778. cap: cap,
  23779. updatable: updatable,
  23780. sideOrientation: sideOrientation,
  23781. instance: instance
  23782. };
  23783. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23784. };
  23785. /**
  23786. * Creates a polyhedron mesh.
  23787. * Please consider using the same method from the MeshBuilder class instead.
  23788. * 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
  23789. * to choose the wanted type.
  23790. * The parameter `size` (positive float, default 1) sets the polygon size.
  23791. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23792. * 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`.
  23793. * 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
  23794. * 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)`).
  23795. * 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
  23796. * 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.
  23797. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23798. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23799. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23800. */
  23801. Mesh.CreatePolyhedron = function (name, options, scene) {
  23802. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23803. };
  23804. /**
  23805. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23806. * Please consider using the same method from the MeshBuilder class instead.
  23807. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23808. * 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`).
  23809. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23810. * 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.
  23811. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23812. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23813. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23814. */
  23815. Mesh.CreateIcoSphere = function (name, options, scene) {
  23816. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23817. };
  23818. /**
  23819. * Creates a decal mesh.
  23820. * Please consider using the same method from the MeshBuilder class instead.
  23821. * 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.
  23822. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23823. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23824. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23825. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23826. */
  23827. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23828. var options = {
  23829. position: position,
  23830. normal: normal,
  23831. size: size,
  23832. angle: angle
  23833. };
  23834. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23835. };
  23836. // Skeletons
  23837. /**
  23838. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23839. */
  23840. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23841. var source;
  23842. if (!this._sourcePositions) {
  23843. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23844. this._sourcePositions = new Float32Array(source);
  23845. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23846. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23847. }
  23848. }
  23849. return this._sourcePositions;
  23850. };
  23851. /**
  23852. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23853. */
  23854. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23855. var source;
  23856. if (!this._sourceNormals) {
  23857. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23858. this._sourceNormals = new Float32Array(source);
  23859. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23860. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23861. }
  23862. }
  23863. return this._sourceNormals;
  23864. };
  23865. /**
  23866. * Updates the vertex buffer by applying transformation from the bones.
  23867. * Returns the Mesh.
  23868. *
  23869. * @param {skeleton} skeleton to apply
  23870. */
  23871. Mesh.prototype.applySkeleton = function (skeleton) {
  23872. if (!this.geometry) {
  23873. return this;
  23874. }
  23875. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23876. return this;
  23877. }
  23878. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23879. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23880. return this;
  23881. }
  23882. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23883. return this;
  23884. }
  23885. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23886. return this;
  23887. }
  23888. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23889. return this;
  23890. }
  23891. if (!this._sourcePositions) {
  23892. var submeshes = this.subMeshes.slice();
  23893. this.setPositionsForCPUSkinning();
  23894. this.subMeshes = submeshes;
  23895. }
  23896. if (!this._sourceNormals) {
  23897. this.setNormalsForCPUSkinning();
  23898. }
  23899. // positionsData checks for not being Float32Array will only pass at most once
  23900. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23901. if (!(positionsData instanceof Float32Array)) {
  23902. positionsData = new Float32Array(positionsData);
  23903. }
  23904. // normalsData checks for not being Float32Array will only pass at most once
  23905. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23906. if (!(normalsData instanceof Float32Array)) {
  23907. normalsData = new Float32Array(normalsData);
  23908. }
  23909. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23910. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23911. var needExtras = this.numBoneInfluencers > 4;
  23912. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23913. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23914. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23915. var tempVector3 = BABYLON.Vector3.Zero();
  23916. var finalMatrix = new BABYLON.Matrix();
  23917. var tempMatrix = new BABYLON.Matrix();
  23918. var matWeightIdx = 0;
  23919. var inf;
  23920. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23921. var weight;
  23922. for (inf = 0; inf < 4; inf++) {
  23923. weight = matricesWeightsData[matWeightIdx + inf];
  23924. if (weight > 0) {
  23925. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23926. finalMatrix.addToSelf(tempMatrix);
  23927. }
  23928. else
  23929. break;
  23930. }
  23931. if (needExtras) {
  23932. for (inf = 0; inf < 4; inf++) {
  23933. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23934. if (weight > 0) {
  23935. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23936. finalMatrix.addToSelf(tempMatrix);
  23937. }
  23938. else
  23939. break;
  23940. }
  23941. }
  23942. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23943. tempVector3.toArray(positionsData, index);
  23944. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23945. tempVector3.toArray(normalsData, index);
  23946. finalMatrix.reset();
  23947. }
  23948. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23949. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23950. return this;
  23951. };
  23952. // Tools
  23953. /**
  23954. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23955. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23956. */
  23957. Mesh.MinMax = function (meshes) {
  23958. var minVector = null;
  23959. var maxVector = null;
  23960. meshes.forEach(function (mesh, index, array) {
  23961. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23962. if (!minVector) {
  23963. minVector = boundingBox.minimumWorld;
  23964. maxVector = boundingBox.maximumWorld;
  23965. }
  23966. else {
  23967. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23968. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23969. }
  23970. });
  23971. return {
  23972. min: minVector,
  23973. max: maxVector
  23974. };
  23975. };
  23976. /**
  23977. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23978. */
  23979. Mesh.Center = function (meshesOrMinMaxVector) {
  23980. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23981. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23982. };
  23983. /**
  23984. * Merge the array of meshes into a single mesh for performance reasons.
  23985. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23986. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23987. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23988. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23989. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23990. */
  23991. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23992. if (disposeSource === void 0) { disposeSource = true; }
  23993. var index;
  23994. if (!allow32BitsIndices) {
  23995. var totalVertices = 0;
  23996. // Counting vertices
  23997. for (index = 0; index < meshes.length; index++) {
  23998. if (meshes[index]) {
  23999. totalVertices += meshes[index].getTotalVertices();
  24000. if (totalVertices > 65536) {
  24001. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  24002. return null;
  24003. }
  24004. }
  24005. }
  24006. }
  24007. // Merge
  24008. var vertexData;
  24009. var otherVertexData;
  24010. var indiceArray = new Array();
  24011. var source;
  24012. for (index = 0; index < meshes.length; index++) {
  24013. if (meshes[index]) {
  24014. meshes[index].computeWorldMatrix(true);
  24015. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  24016. otherVertexData.transform(meshes[index].getWorldMatrix());
  24017. if (vertexData) {
  24018. vertexData.merge(otherVertexData);
  24019. }
  24020. else {
  24021. vertexData = otherVertexData;
  24022. source = meshes[index];
  24023. }
  24024. if (subdivideWithSubMeshes) {
  24025. indiceArray.push(meshes[index].getTotalIndices());
  24026. }
  24027. }
  24028. }
  24029. if (!meshSubclass) {
  24030. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  24031. }
  24032. vertexData.applyToMesh(meshSubclass);
  24033. // Setting properties
  24034. meshSubclass.material = source.material;
  24035. meshSubclass.checkCollisions = source.checkCollisions;
  24036. // Cleaning
  24037. if (disposeSource) {
  24038. for (index = 0; index < meshes.length; index++) {
  24039. if (meshes[index]) {
  24040. meshes[index].dispose();
  24041. }
  24042. }
  24043. }
  24044. // Subdivide
  24045. if (subdivideWithSubMeshes) {
  24046. //-- Suppresions du submesh global
  24047. meshSubclass.releaseSubMeshes();
  24048. index = 0;
  24049. var offset = 0;
  24050. //-- aplique la subdivision en fonction du tableau d'indices
  24051. while (index < indiceArray.length) {
  24052. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24053. offset += indiceArray[index];
  24054. index++;
  24055. }
  24056. }
  24057. return meshSubclass;
  24058. };
  24059. // Consts
  24060. Mesh._FRONTSIDE = 0;
  24061. Mesh._BACKSIDE = 1;
  24062. Mesh._DOUBLESIDE = 2;
  24063. Mesh._DEFAULTSIDE = 0;
  24064. Mesh._NO_CAP = 0;
  24065. Mesh._CAP_START = 1;
  24066. Mesh._CAP_END = 2;
  24067. Mesh._CAP_ALL = 3;
  24068. return Mesh;
  24069. }(BABYLON.AbstractMesh));
  24070. BABYLON.Mesh = Mesh;
  24071. })(BABYLON || (BABYLON = {}));
  24072. //# sourceMappingURL=babylon.mesh.js.map
  24073. var BABYLON;
  24074. (function (BABYLON) {
  24075. var BaseSubMesh = (function () {
  24076. function BaseSubMesh() {
  24077. }
  24078. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  24079. get: function () {
  24080. return this._materialEffect;
  24081. },
  24082. enumerable: true,
  24083. configurable: true
  24084. });
  24085. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  24086. if (this._materialEffect === effect) {
  24087. if (!effect) {
  24088. this._materialDefines = undefined;
  24089. }
  24090. return;
  24091. }
  24092. this._materialDefines = defines;
  24093. this._materialEffect = effect;
  24094. };
  24095. return BaseSubMesh;
  24096. }());
  24097. BABYLON.BaseSubMesh = BaseSubMesh;
  24098. var SubMesh = (function (_super) {
  24099. __extends(SubMesh, _super);
  24100. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24101. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24102. var _this = _super.call(this) || this;
  24103. _this.materialIndex = materialIndex;
  24104. _this.verticesStart = verticesStart;
  24105. _this.verticesCount = verticesCount;
  24106. _this.indexStart = indexStart;
  24107. _this.indexCount = indexCount;
  24108. _this._renderId = 0;
  24109. _this._mesh = mesh;
  24110. _this._renderingMesh = renderingMesh || mesh;
  24111. mesh.subMeshes.push(_this);
  24112. _this._trianglePlanes = [];
  24113. _this._id = mesh.subMeshes.length - 1;
  24114. if (createBoundingBox) {
  24115. _this.refreshBoundingInfo();
  24116. mesh.computeWorldMatrix(true);
  24117. }
  24118. return _this;
  24119. }
  24120. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24121. get: function () {
  24122. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24123. },
  24124. enumerable: true,
  24125. configurable: true
  24126. });
  24127. /**
  24128. * Returns the submesh BoudingInfo object.
  24129. */
  24130. SubMesh.prototype.getBoundingInfo = function () {
  24131. if (this.IsGlobal) {
  24132. return this._mesh.getBoundingInfo();
  24133. }
  24134. return this._boundingInfo;
  24135. };
  24136. /**
  24137. * Sets the submesh BoundingInfo.
  24138. * Return the SubMesh.
  24139. */
  24140. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24141. this._boundingInfo = boundingInfo;
  24142. return this;
  24143. };
  24144. /**
  24145. * Returns the mesh of the current submesh.
  24146. */
  24147. SubMesh.prototype.getMesh = function () {
  24148. return this._mesh;
  24149. };
  24150. /**
  24151. * Returns the rendering mesh of the submesh.
  24152. */
  24153. SubMesh.prototype.getRenderingMesh = function () {
  24154. return this._renderingMesh;
  24155. };
  24156. /**
  24157. * Returns the submesh material.
  24158. */
  24159. SubMesh.prototype.getMaterial = function () {
  24160. var rootMaterial = this._renderingMesh.material;
  24161. if (rootMaterial && rootMaterial.getSubMaterial) {
  24162. var multiMaterial = rootMaterial;
  24163. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  24164. if (this._currentMaterial !== effectiveMaterial) {
  24165. this._currentMaterial = effectiveMaterial;
  24166. this._materialDefines = undefined;
  24167. }
  24168. return effectiveMaterial;
  24169. }
  24170. if (!rootMaterial) {
  24171. return this._mesh.getScene().defaultMaterial;
  24172. }
  24173. return rootMaterial;
  24174. };
  24175. // Methods
  24176. /**
  24177. * Sets a new updated BoundingInfo object to the submesh.
  24178. * Returns the SubMesh.
  24179. */
  24180. SubMesh.prototype.refreshBoundingInfo = function () {
  24181. this._lastColliderWorldVertices = null;
  24182. if (this.IsGlobal) {
  24183. return;
  24184. }
  24185. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24186. if (!data) {
  24187. this._boundingInfo = this._mesh._boundingInfo;
  24188. return;
  24189. }
  24190. var indices = this._renderingMesh.getIndices();
  24191. var extend;
  24192. //is this the only submesh?
  24193. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24194. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24195. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24196. }
  24197. else {
  24198. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24199. }
  24200. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24201. return this;
  24202. };
  24203. SubMesh.prototype._checkCollision = function (collider) {
  24204. return this.getBoundingInfo()._checkCollision(collider);
  24205. };
  24206. /**
  24207. * Updates the submesh BoundingInfo.
  24208. * Returns the Submesh.
  24209. */
  24210. SubMesh.prototype.updateBoundingInfo = function (world) {
  24211. if (!this.getBoundingInfo()) {
  24212. this.refreshBoundingInfo();
  24213. }
  24214. this.getBoundingInfo().update(world);
  24215. return this;
  24216. };
  24217. /**
  24218. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24219. * Boolean returned.
  24220. */
  24221. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24222. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24223. };
  24224. /**
  24225. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24226. * Boolean returned.
  24227. */
  24228. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24229. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24230. };
  24231. /**
  24232. * Renders the submesh.
  24233. * Returns it.
  24234. */
  24235. SubMesh.prototype.render = function (enableAlphaMode) {
  24236. this._renderingMesh.render(this, enableAlphaMode);
  24237. return this;
  24238. };
  24239. /**
  24240. * Returns a new Index Buffer.
  24241. * Type returned : WebGLBuffer.
  24242. */
  24243. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24244. if (!this._linesIndexBuffer) {
  24245. var linesIndices = [];
  24246. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24247. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24248. }
  24249. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24250. this.linesIndexCount = linesIndices.length;
  24251. }
  24252. return this._linesIndexBuffer;
  24253. };
  24254. /**
  24255. * True is the passed Ray intersects the submesh bounding box.
  24256. * Boolean returned.
  24257. */
  24258. SubMesh.prototype.canIntersects = function (ray) {
  24259. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24260. };
  24261. /**
  24262. * Returns an object IntersectionInfo.
  24263. */
  24264. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24265. var intersectInfo = null;
  24266. // LineMesh first as it's also a Mesh...
  24267. if (this._mesh instanceof BABYLON.LinesMesh) {
  24268. var lineMesh = this._mesh;
  24269. // Line test
  24270. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24271. var p0 = positions[indices[index]];
  24272. var p1 = positions[indices[index + 1]];
  24273. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24274. if (length < 0) {
  24275. continue;
  24276. }
  24277. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24278. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24279. if (fastCheck) {
  24280. break;
  24281. }
  24282. }
  24283. }
  24284. }
  24285. else {
  24286. // Triangles test
  24287. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24288. var p0 = positions[indices[index]];
  24289. var p1 = positions[indices[index + 1]];
  24290. var p2 = positions[indices[index + 2]];
  24291. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24292. if (currentIntersectInfo) {
  24293. if (currentIntersectInfo.distance < 0) {
  24294. continue;
  24295. }
  24296. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24297. intersectInfo = currentIntersectInfo;
  24298. intersectInfo.faceId = index / 3;
  24299. if (fastCheck) {
  24300. break;
  24301. }
  24302. }
  24303. }
  24304. }
  24305. }
  24306. return intersectInfo;
  24307. };
  24308. SubMesh.prototype._rebuild = function () {
  24309. if (this._linesIndexBuffer) {
  24310. this._linesIndexBuffer = null;
  24311. }
  24312. };
  24313. // Clone
  24314. /**
  24315. * Creates a new Submesh from the passed Mesh.
  24316. */
  24317. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24318. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24319. if (!this.IsGlobal) {
  24320. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24321. }
  24322. return result;
  24323. };
  24324. // Dispose
  24325. /**
  24326. * Disposes the Submesh.
  24327. * Returns nothing.
  24328. */
  24329. SubMesh.prototype.dispose = function () {
  24330. if (this._linesIndexBuffer) {
  24331. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24332. this._linesIndexBuffer = null;
  24333. }
  24334. // Remove from mesh
  24335. var index = this._mesh.subMeshes.indexOf(this);
  24336. this._mesh.subMeshes.splice(index, 1);
  24337. };
  24338. // Statics
  24339. /**
  24340. * Creates a new Submesh from the passed parameters :
  24341. * - materialIndex (integer) : the index of the main mesh material.
  24342. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24343. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24344. * - mesh (Mesh) : the main mesh to create the submesh from.
  24345. * - renderingMesh (optional Mesh) : rendering mesh.
  24346. */
  24347. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24348. var minVertexIndex = Number.MAX_VALUE;
  24349. var maxVertexIndex = -Number.MAX_VALUE;
  24350. renderingMesh = renderingMesh || mesh;
  24351. var indices = renderingMesh.getIndices();
  24352. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24353. var vertexIndex = indices[index];
  24354. if (vertexIndex < minVertexIndex)
  24355. minVertexIndex = vertexIndex;
  24356. if (vertexIndex > maxVertexIndex)
  24357. maxVertexIndex = vertexIndex;
  24358. }
  24359. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24360. };
  24361. return SubMesh;
  24362. }(BaseSubMesh));
  24363. BABYLON.SubMesh = SubMesh;
  24364. })(BABYLON || (BABYLON = {}));
  24365. //# sourceMappingURL=babylon.subMesh.js.map
  24366. var BABYLON;
  24367. (function (BABYLON) {
  24368. var EffectFallbacks = (function () {
  24369. function EffectFallbacks() {
  24370. this._defines = {};
  24371. this._currentRank = 32;
  24372. this._maxRank = -1;
  24373. }
  24374. EffectFallbacks.prototype.unBindMesh = function () {
  24375. this._mesh = null;
  24376. };
  24377. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24378. if (!this._defines[rank]) {
  24379. if (rank < this._currentRank) {
  24380. this._currentRank = rank;
  24381. }
  24382. if (rank > this._maxRank) {
  24383. this._maxRank = rank;
  24384. }
  24385. this._defines[rank] = new Array();
  24386. }
  24387. this._defines[rank].push(define);
  24388. };
  24389. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24390. this._meshRank = rank;
  24391. this._mesh = mesh;
  24392. if (rank < this._currentRank) {
  24393. this._currentRank = rank;
  24394. }
  24395. if (rank > this._maxRank) {
  24396. this._maxRank = rank;
  24397. }
  24398. };
  24399. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24400. get: function () {
  24401. return this._currentRank <= this._maxRank;
  24402. },
  24403. enumerable: true,
  24404. configurable: true
  24405. });
  24406. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24407. // First we try to switch to CPU skinning
  24408. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24409. this._mesh.computeBonesUsingShaders = false;
  24410. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24411. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24412. var scene = this._mesh.getScene();
  24413. for (var index = 0; index < scene.meshes.length; index++) {
  24414. var otherMesh = scene.meshes[index];
  24415. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24416. otherMesh.computeBonesUsingShaders = false;
  24417. }
  24418. }
  24419. }
  24420. else {
  24421. var currentFallbacks = this._defines[this._currentRank];
  24422. if (currentFallbacks) {
  24423. for (var index = 0; index < currentFallbacks.length; index++) {
  24424. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24425. }
  24426. }
  24427. this._currentRank++;
  24428. }
  24429. return currentDefines;
  24430. };
  24431. return EffectFallbacks;
  24432. }());
  24433. BABYLON.EffectFallbacks = EffectFallbacks;
  24434. var EffectCreationOptions = (function () {
  24435. function EffectCreationOptions() {
  24436. }
  24437. return EffectCreationOptions;
  24438. }());
  24439. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24440. var Effect = (function () {
  24441. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24442. var _this = this;
  24443. this.uniqueId = 0;
  24444. this.onCompileObservable = new BABYLON.Observable();
  24445. this.onErrorObservable = new BABYLON.Observable();
  24446. this.onBindObservable = new BABYLON.Observable();
  24447. this._uniformBuffersNames = {};
  24448. this._isReady = false;
  24449. this._compilationError = "";
  24450. this.name = baseName;
  24451. if (attributesNamesOrOptions.attributes) {
  24452. var options = attributesNamesOrOptions;
  24453. this._engine = uniformsNamesOrEngine;
  24454. this._attributesNames = options.attributes;
  24455. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24456. this._samplers = options.samplers;
  24457. this.defines = options.defines;
  24458. this.onError = options.onError;
  24459. this.onCompiled = options.onCompiled;
  24460. this._fallbacks = options.fallbacks;
  24461. this._indexParameters = options.indexParameters;
  24462. if (options.uniformBuffersNames) {
  24463. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24464. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24465. }
  24466. }
  24467. }
  24468. else {
  24469. this._engine = engine;
  24470. this.defines = defines;
  24471. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24472. this._samplers = samplers;
  24473. this._attributesNames = attributesNamesOrOptions;
  24474. this.onError = onError;
  24475. this.onCompiled = onCompiled;
  24476. this._indexParameters = indexParameters;
  24477. this._fallbacks = fallbacks;
  24478. }
  24479. this.uniqueId = Effect._uniqueIdSeed++;
  24480. var vertexSource;
  24481. var fragmentSource;
  24482. if (baseName.vertexElement) {
  24483. vertexSource = document.getElementById(baseName.vertexElement);
  24484. if (!vertexSource) {
  24485. vertexSource = baseName.vertexElement;
  24486. }
  24487. }
  24488. else {
  24489. vertexSource = baseName.vertex || baseName;
  24490. }
  24491. if (baseName.fragmentElement) {
  24492. fragmentSource = document.getElementById(baseName.fragmentElement);
  24493. if (!fragmentSource) {
  24494. fragmentSource = baseName.fragmentElement;
  24495. }
  24496. }
  24497. else {
  24498. fragmentSource = baseName.fragment || baseName;
  24499. }
  24500. this._loadVertexShader(vertexSource, function (vertexCode) {
  24501. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24502. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24503. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24504. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24505. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24506. if (baseName) {
  24507. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24508. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24509. }
  24510. else {
  24511. _this._vertexSourceCode = migratedVertexCode;
  24512. _this._fragmentSourceCode = migratedFragmentCode;
  24513. }
  24514. _this._prepareEffect();
  24515. });
  24516. });
  24517. });
  24518. });
  24519. });
  24520. });
  24521. }
  24522. Object.defineProperty(Effect.prototype, "key", {
  24523. get: function () {
  24524. return this._key;
  24525. },
  24526. enumerable: true,
  24527. configurable: true
  24528. });
  24529. // Properties
  24530. Effect.prototype.isReady = function () {
  24531. return this._isReady;
  24532. };
  24533. Effect.prototype.getEngine = function () {
  24534. return this._engine;
  24535. };
  24536. Effect.prototype.getProgram = function () {
  24537. return this._program;
  24538. };
  24539. Effect.prototype.getAttributesNames = function () {
  24540. return this._attributesNames;
  24541. };
  24542. Effect.prototype.getAttributeLocation = function (index) {
  24543. return this._attributes[index];
  24544. };
  24545. Effect.prototype.getAttributeLocationByName = function (name) {
  24546. var index = this._attributesNames.indexOf(name);
  24547. return this._attributes[index];
  24548. };
  24549. Effect.prototype.getAttributesCount = function () {
  24550. return this._attributes.length;
  24551. };
  24552. Effect.prototype.getUniformIndex = function (uniformName) {
  24553. return this._uniformsNames.indexOf(uniformName);
  24554. };
  24555. Effect.prototype.getUniform = function (uniformName) {
  24556. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24557. };
  24558. Effect.prototype.getSamplers = function () {
  24559. return this._samplers;
  24560. };
  24561. Effect.prototype.getCompilationError = function () {
  24562. return this._compilationError;
  24563. };
  24564. // Methods
  24565. Effect.prototype.executeWhenCompiled = function (func) {
  24566. if (this.isReady()) {
  24567. func(this);
  24568. return;
  24569. }
  24570. this.onCompileObservable.add(function (effect) {
  24571. func(effect);
  24572. });
  24573. };
  24574. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24575. // DOM element ?
  24576. if (vertex instanceof HTMLElement) {
  24577. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24578. callback(vertexCode);
  24579. return;
  24580. }
  24581. // Base64 encoded ?
  24582. if (vertex.substr(0, 7) === "base64:") {
  24583. var vertexBinary = window.atob(vertex.substr(7));
  24584. callback(vertexBinary);
  24585. return;
  24586. }
  24587. // Is in local store ?
  24588. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24589. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24590. return;
  24591. }
  24592. var vertexShaderUrl;
  24593. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24594. vertexShaderUrl = vertex;
  24595. }
  24596. else {
  24597. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24598. }
  24599. // Vertex shader
  24600. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24601. };
  24602. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24603. // DOM element ?
  24604. if (fragment instanceof HTMLElement) {
  24605. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24606. callback(fragmentCode);
  24607. return;
  24608. }
  24609. // Base64 encoded ?
  24610. if (fragment.substr(0, 7) === "base64:") {
  24611. var fragmentBinary = window.atob(fragment.substr(7));
  24612. callback(fragmentBinary);
  24613. return;
  24614. }
  24615. // Is in local store ?
  24616. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24617. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24618. return;
  24619. }
  24620. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24621. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24622. return;
  24623. }
  24624. var fragmentShaderUrl;
  24625. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24626. fragmentShaderUrl = fragment;
  24627. }
  24628. else {
  24629. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24630. }
  24631. // Fragment shader
  24632. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24633. };
  24634. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24635. // Rebuild shaders source code
  24636. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24637. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24638. vertexCode = prefix + vertexCode;
  24639. fragmentCode = prefix + fragmentCode;
  24640. // Number lines of shaders source code
  24641. var i = 2;
  24642. var regex = /\n/gm;
  24643. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24644. i = 2;
  24645. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24646. // Dump shaders name and formatted source code
  24647. if (this.name.vertexElement) {
  24648. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24649. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24650. }
  24651. else if (this.name.vertex) {
  24652. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24653. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24654. }
  24655. else {
  24656. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24657. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24658. }
  24659. };
  24660. ;
  24661. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24662. var preparedSourceCode = this._processPrecision(sourceCode);
  24663. if (this._engine.webGLVersion == 1) {
  24664. callback(preparedSourceCode);
  24665. return;
  24666. }
  24667. // Already converted
  24668. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24669. callback(preparedSourceCode.replace("#version 300 es", ""));
  24670. return;
  24671. }
  24672. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  24673. // Remove extensions
  24674. // #extension GL_OES_standard_derivatives : enable
  24675. // #extension GL_EXT_shader_texture_lod : enable
  24676. // #extension GL_EXT_frag_depth : enable
  24677. // #extension GL_EXT_draw_buffers : require
  24678. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  24679. var result = preparedSourceCode.replace(regex, "");
  24680. // Migrate to GLSL v300
  24681. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24682. result = result.replace(/attribute[ \t]/g, "in ");
  24683. result = result.replace(/[ \t]attribute/g, " in");
  24684. if (isFragment) {
  24685. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24686. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24687. result = result.replace(/texture2D\(/g, "texture(");
  24688. result = result.replace(/textureCube\(/g, "texture(");
  24689. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24690. result = result.replace(/gl_FragColor/g, "glFragColor");
  24691. result = result.replace(/gl_FragData/g, "glFragData");
  24692. result = result.replace(/void\s+?main\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  24693. }
  24694. callback(result);
  24695. };
  24696. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24697. var _this = this;
  24698. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24699. var match = regex.exec(sourceCode);
  24700. var returnValue = new String(sourceCode);
  24701. while (match != null) {
  24702. var includeFile = match[1];
  24703. // Uniform declaration
  24704. if (includeFile.indexOf("__decl__") !== -1) {
  24705. includeFile = includeFile.replace(/__decl__/, "");
  24706. if (this._engine.supportsUniformBuffers) {
  24707. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24708. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24709. }
  24710. includeFile = includeFile + "Declaration";
  24711. }
  24712. if (Effect.IncludesShadersStore[includeFile]) {
  24713. // Substitution
  24714. var includeContent = Effect.IncludesShadersStore[includeFile];
  24715. if (match[2]) {
  24716. var splits = match[3].split(",");
  24717. for (var index = 0; index < splits.length; index += 2) {
  24718. var source = new RegExp(splits[index], "g");
  24719. var dest = splits[index + 1];
  24720. includeContent = includeContent.replace(source, dest);
  24721. }
  24722. }
  24723. if (match[4]) {
  24724. var indexString = match[5];
  24725. if (indexString.indexOf("..") !== -1) {
  24726. var indexSplits = indexString.split("..");
  24727. var minIndex = parseInt(indexSplits[0]);
  24728. var maxIndex = parseInt(indexSplits[1]);
  24729. var sourceIncludeContent = includeContent.slice(0);
  24730. includeContent = "";
  24731. if (isNaN(maxIndex)) {
  24732. maxIndex = this._indexParameters[indexSplits[1]];
  24733. }
  24734. for (var i = minIndex; i < maxIndex; i++) {
  24735. if (!this._engine.supportsUniformBuffers) {
  24736. // Ubo replacement
  24737. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24738. return p1 + "{X}";
  24739. });
  24740. }
  24741. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24742. }
  24743. }
  24744. else {
  24745. if (!this._engine.supportsUniformBuffers) {
  24746. // Ubo replacement
  24747. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24748. return p1 + "{X}";
  24749. });
  24750. }
  24751. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24752. }
  24753. }
  24754. // Replace
  24755. returnValue = returnValue.replace(match[0], includeContent);
  24756. }
  24757. else {
  24758. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24759. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24760. Effect.IncludesShadersStore[includeFile] = fileContent;
  24761. _this._processIncludes(returnValue, callback);
  24762. });
  24763. return;
  24764. }
  24765. match = regex.exec(sourceCode);
  24766. }
  24767. callback(returnValue);
  24768. };
  24769. Effect.prototype._processPrecision = function (source) {
  24770. if (source.indexOf("precision highp float") === -1) {
  24771. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24772. source = "precision mediump float;\n" + source;
  24773. }
  24774. else {
  24775. source = "precision highp float;\n" + source;
  24776. }
  24777. }
  24778. else {
  24779. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24780. source = source.replace("precision highp float", "precision mediump float");
  24781. }
  24782. }
  24783. return source;
  24784. };
  24785. Effect.prototype._prepareEffect = function () {
  24786. var attributesNames = this._attributesNames;
  24787. var defines = this.defines;
  24788. var fallbacks = this._fallbacks;
  24789. this._valueCache = {};
  24790. try {
  24791. var engine = this._engine;
  24792. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24793. if (engine.webGLVersion > 1) {
  24794. for (var name in this._uniformBuffersNames) {
  24795. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24796. }
  24797. }
  24798. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24799. this._attributes = engine.getAttributes(this._program, attributesNames);
  24800. var index;
  24801. for (index = 0; index < this._samplers.length; index++) {
  24802. var sampler = this.getUniform(this._samplers[index]);
  24803. if (sampler == null) {
  24804. this._samplers.splice(index, 1);
  24805. index--;
  24806. }
  24807. }
  24808. engine.bindSamplers(this);
  24809. this._compilationError = "";
  24810. this._isReady = true;
  24811. if (this.onCompiled) {
  24812. this.onCompiled(this);
  24813. }
  24814. this.onCompileObservable.notifyObservers(this);
  24815. this.onCompileObservable.clear();
  24816. // Unbind mesh reference in fallbacks
  24817. if (this._fallbacks) {
  24818. this._fallbacks.unBindMesh();
  24819. }
  24820. }
  24821. catch (e) {
  24822. this._compilationError = e.message;
  24823. // Let's go through fallbacks then
  24824. BABYLON.Tools.Error("Unable to compile effect:");
  24825. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24826. return " " + uniform;
  24827. }));
  24828. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24829. return " " + attribute;
  24830. }));
  24831. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24832. BABYLON.Tools.Error("Error: " + this._compilationError);
  24833. if (fallbacks && fallbacks.isMoreFallbacks) {
  24834. BABYLON.Tools.Error("Trying next fallback.");
  24835. this.defines = fallbacks.reduce(this.defines);
  24836. this._prepareEffect();
  24837. }
  24838. else {
  24839. if (this.onError) {
  24840. this.onError(this, this._compilationError);
  24841. }
  24842. this.onErrorObservable.notifyObservers(this);
  24843. this.onErrorObservable.clear();
  24844. // Unbind mesh reference in fallbacks
  24845. if (this._fallbacks) {
  24846. this._fallbacks.unBindMesh();
  24847. }
  24848. }
  24849. }
  24850. };
  24851. Object.defineProperty(Effect.prototype, "isSupported", {
  24852. get: function () {
  24853. return this._compilationError === "";
  24854. },
  24855. enumerable: true,
  24856. configurable: true
  24857. });
  24858. Effect.prototype._bindTexture = function (channel, texture) {
  24859. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24860. };
  24861. Effect.prototype.setTexture = function (channel, texture) {
  24862. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24863. };
  24864. Effect.prototype.setTextureArray = function (channel, textures) {
  24865. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24866. var initialPos = this._samplers.indexOf(channel);
  24867. for (var index = 1; index < textures.length; index++) {
  24868. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24869. }
  24870. }
  24871. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24872. };
  24873. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24874. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24875. };
  24876. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24877. var cache = this._valueCache[uniformName];
  24878. var flag = matrix.updateFlag;
  24879. if (cache !== undefined && cache === flag) {
  24880. return false;
  24881. }
  24882. this._valueCache[uniformName] = flag;
  24883. return true;
  24884. };
  24885. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24886. var cache = this._valueCache[uniformName];
  24887. if (!cache) {
  24888. cache = [x, y];
  24889. this._valueCache[uniformName] = cache;
  24890. return true;
  24891. }
  24892. var changed = false;
  24893. if (cache[0] !== x) {
  24894. cache[0] = x;
  24895. changed = true;
  24896. }
  24897. if (cache[1] !== y) {
  24898. cache[1] = y;
  24899. changed = true;
  24900. }
  24901. return changed;
  24902. };
  24903. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24904. var cache = this._valueCache[uniformName];
  24905. if (!cache) {
  24906. cache = [x, y, z];
  24907. this._valueCache[uniformName] = cache;
  24908. return true;
  24909. }
  24910. var changed = false;
  24911. if (cache[0] !== x) {
  24912. cache[0] = x;
  24913. changed = true;
  24914. }
  24915. if (cache[1] !== y) {
  24916. cache[1] = y;
  24917. changed = true;
  24918. }
  24919. if (cache[2] !== z) {
  24920. cache[2] = z;
  24921. changed = true;
  24922. }
  24923. return changed;
  24924. };
  24925. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24926. var cache = this._valueCache[uniformName];
  24927. if (!cache) {
  24928. cache = [x, y, z, w];
  24929. this._valueCache[uniformName] = cache;
  24930. return true;
  24931. }
  24932. var changed = false;
  24933. if (cache[0] !== x) {
  24934. cache[0] = x;
  24935. changed = true;
  24936. }
  24937. if (cache[1] !== y) {
  24938. cache[1] = y;
  24939. changed = true;
  24940. }
  24941. if (cache[2] !== z) {
  24942. cache[2] = z;
  24943. changed = true;
  24944. }
  24945. if (cache[3] !== w) {
  24946. cache[3] = w;
  24947. changed = true;
  24948. }
  24949. return changed;
  24950. };
  24951. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24952. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24953. return;
  24954. }
  24955. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24956. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24957. };
  24958. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24959. this._engine.bindUniformBlock(this._program, blockName, index);
  24960. };
  24961. Effect.prototype.setIntArray = function (uniformName, array) {
  24962. this._valueCache[uniformName] = null;
  24963. this._engine.setIntArray(this.getUniform(uniformName), array);
  24964. return this;
  24965. };
  24966. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24967. this._valueCache[uniformName] = null;
  24968. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24969. return this;
  24970. };
  24971. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24972. this._valueCache[uniformName] = null;
  24973. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24974. return this;
  24975. };
  24976. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24977. this._valueCache[uniformName] = null;
  24978. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24979. return this;
  24980. };
  24981. Effect.prototype.setFloatArray = function (uniformName, array) {
  24982. this._valueCache[uniformName] = null;
  24983. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24984. return this;
  24985. };
  24986. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24987. this._valueCache[uniformName] = null;
  24988. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24989. return this;
  24990. };
  24991. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24992. this._valueCache[uniformName] = null;
  24993. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24994. return this;
  24995. };
  24996. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24997. this._valueCache[uniformName] = null;
  24998. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24999. return this;
  25000. };
  25001. Effect.prototype.setArray = function (uniformName, array) {
  25002. this._valueCache[uniformName] = null;
  25003. this._engine.setArray(this.getUniform(uniformName), array);
  25004. return this;
  25005. };
  25006. Effect.prototype.setArray2 = function (uniformName, array) {
  25007. this._valueCache[uniformName] = null;
  25008. this._engine.setArray2(this.getUniform(uniformName), array);
  25009. return this;
  25010. };
  25011. Effect.prototype.setArray3 = function (uniformName, array) {
  25012. this._valueCache[uniformName] = null;
  25013. this._engine.setArray3(this.getUniform(uniformName), array);
  25014. return this;
  25015. };
  25016. Effect.prototype.setArray4 = function (uniformName, array) {
  25017. this._valueCache[uniformName] = null;
  25018. this._engine.setArray4(this.getUniform(uniformName), array);
  25019. return this;
  25020. };
  25021. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25022. if (!matrices) {
  25023. return;
  25024. }
  25025. this._valueCache[uniformName] = null;
  25026. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25027. return this;
  25028. };
  25029. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25030. if (this._cacheMatrix(uniformName, matrix)) {
  25031. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25032. }
  25033. return this;
  25034. };
  25035. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25036. this._valueCache[uniformName] = null;
  25037. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25038. return this;
  25039. };
  25040. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25041. this._valueCache[uniformName] = null;
  25042. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25043. return this;
  25044. };
  25045. Effect.prototype.setFloat = function (uniformName, value) {
  25046. var cache = this._valueCache[uniformName];
  25047. if (cache !== undefined && cache === value)
  25048. return this;
  25049. this._valueCache[uniformName] = value;
  25050. this._engine.setFloat(this.getUniform(uniformName), value);
  25051. return this;
  25052. };
  25053. Effect.prototype.setBool = function (uniformName, bool) {
  25054. var cache = this._valueCache[uniformName];
  25055. if (cache !== undefined && cache === bool)
  25056. return this;
  25057. this._valueCache[uniformName] = bool;
  25058. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25059. return this;
  25060. };
  25061. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25062. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25063. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25064. }
  25065. return this;
  25066. };
  25067. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25068. if (this._cacheFloat2(uniformName, x, y)) {
  25069. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25070. }
  25071. return this;
  25072. };
  25073. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25074. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25075. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25076. }
  25077. return this;
  25078. };
  25079. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25080. if (this._cacheFloat3(uniformName, x, y, z)) {
  25081. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25082. }
  25083. return this;
  25084. };
  25085. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25086. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25087. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25088. }
  25089. return this;
  25090. };
  25091. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25092. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25093. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25094. }
  25095. return this;
  25096. };
  25097. Effect.prototype.setColor3 = function (uniformName, color3) {
  25098. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25099. this._engine.setColor3(this.getUniform(uniformName), color3);
  25100. }
  25101. return this;
  25102. };
  25103. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25104. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25105. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25106. }
  25107. return this;
  25108. };
  25109. Effect.ResetCache = function () {
  25110. Effect._baseCache = {};
  25111. };
  25112. Effect._uniqueIdSeed = 0;
  25113. Effect._baseCache = {};
  25114. // Statics
  25115. Effect.ShadersStore = {};
  25116. Effect.IncludesShadersStore = {};
  25117. return Effect;
  25118. }());
  25119. BABYLON.Effect = Effect;
  25120. })(BABYLON || (BABYLON = {}));
  25121. //# sourceMappingURL=babylon.effect.js.map
  25122. var BABYLON;
  25123. (function (BABYLON) {
  25124. var MaterialHelper = (function () {
  25125. function MaterialHelper() {
  25126. }
  25127. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  25128. defines._needUVs = true;
  25129. defines[key] = true;
  25130. if (texture.getTextureMatrix().isIdentity(true)) {
  25131. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  25132. if (texture.coordinatesIndex === 0) {
  25133. defines["MAINUV1"] = true;
  25134. }
  25135. else {
  25136. defines["MAINUV2"] = true;
  25137. }
  25138. }
  25139. else {
  25140. defines[key + "DIRECTUV"] = 0;
  25141. }
  25142. };
  25143. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  25144. var matrix = texture.getTextureMatrix();
  25145. if (!matrix.isIdentity(true)) {
  25146. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  25147. }
  25148. };
  25149. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  25150. if (defines._areMiscDirty) {
  25151. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  25152. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  25153. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  25154. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  25155. }
  25156. };
  25157. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  25158. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  25159. var changed = false;
  25160. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  25161. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  25162. changed = true;
  25163. }
  25164. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  25165. defines["ALPHATEST"] = !defines["ALPHATEST"];
  25166. changed = true;
  25167. }
  25168. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  25169. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  25170. changed = true;
  25171. }
  25172. if (defines["INSTANCES"] !== useInstances) {
  25173. defines["INSTANCES"] = useInstances;
  25174. changed = true;
  25175. }
  25176. if (changed) {
  25177. defines.markAsUnprocessed();
  25178. }
  25179. };
  25180. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  25181. if (useMorphTargets === void 0) { useMorphTargets = false; }
  25182. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  25183. return false;
  25184. }
  25185. defines._normals = defines._needNormals;
  25186. defines._uvs = defines._needUVs;
  25187. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  25188. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25189. defines["TANGENT"] = true;
  25190. }
  25191. if (defines._needUVs) {
  25192. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  25193. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  25194. }
  25195. else {
  25196. defines["UV1"] = false;
  25197. defines["UV2"] = false;
  25198. }
  25199. if (useVertexColor) {
  25200. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  25201. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  25202. }
  25203. if (useBones) {
  25204. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25205. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  25206. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  25207. }
  25208. else {
  25209. defines["NUM_BONE_INFLUENCERS"] = 0;
  25210. defines["BonesPerMesh"] = 0;
  25211. }
  25212. }
  25213. if (useMorphTargets) {
  25214. if (mesh.morphTargetManager) {
  25215. var manager = mesh.morphTargetManager;
  25216. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  25217. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  25218. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  25219. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  25220. }
  25221. else {
  25222. defines["MORPHTARGETS_TANGENT"] = false;
  25223. defines["MORPHTARGETS_NORMAL"] = false;
  25224. defines["MORPHTARGETS"] = false;
  25225. defines["NUM_MORPH_INFLUENCERS"] = 0;
  25226. }
  25227. }
  25228. return true;
  25229. };
  25230. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  25231. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25232. if (disableLighting === void 0) { disableLighting = false; }
  25233. if (!defines._areLightsDirty) {
  25234. return defines._needNormals;
  25235. }
  25236. var lightIndex = 0;
  25237. var needNormals = false;
  25238. var needRebuild = false;
  25239. var lightmapMode = false;
  25240. var shadowEnabled = false;
  25241. var specularEnabled = false;
  25242. if (scene.lightsEnabled && !disableLighting) {
  25243. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25244. var light = _a[_i];
  25245. needNormals = true;
  25246. if (defines["LIGHT" + lightIndex] === undefined) {
  25247. needRebuild = true;
  25248. }
  25249. defines["LIGHT" + lightIndex] = true;
  25250. defines["SPOTLIGHT" + lightIndex] = false;
  25251. defines["HEMILIGHT" + lightIndex] = false;
  25252. defines["POINTLIGHT" + lightIndex] = false;
  25253. defines["DIRLIGHT" + lightIndex] = false;
  25254. var type;
  25255. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  25256. type = "SPOTLIGHT" + lightIndex;
  25257. }
  25258. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  25259. type = "HEMILIGHT" + lightIndex;
  25260. }
  25261. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  25262. type = "POINTLIGHT" + lightIndex;
  25263. }
  25264. else {
  25265. type = "DIRLIGHT" + lightIndex;
  25266. }
  25267. defines[type] = true;
  25268. // Specular
  25269. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  25270. specularEnabled = true;
  25271. }
  25272. // Shadows
  25273. defines["SHADOW" + lightIndex] = false;
  25274. defines["SHADOWPCF" + lightIndex] = false;
  25275. defines["SHADOWESM" + lightIndex] = false;
  25276. defines["SHADOWCUBE" + lightIndex] = false;
  25277. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  25278. var shadowGenerator = light.getShadowGenerator();
  25279. if (shadowGenerator) {
  25280. shadowEnabled = true;
  25281. shadowGenerator.prepareDefines(defines, lightIndex);
  25282. }
  25283. }
  25284. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25285. lightmapMode = true;
  25286. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25287. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25288. }
  25289. else {
  25290. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25291. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25292. }
  25293. lightIndex++;
  25294. if (lightIndex === maxSimultaneousLights)
  25295. break;
  25296. }
  25297. }
  25298. defines["SPECULARTERM"] = specularEnabled;
  25299. defines["SHADOWS"] = shadowEnabled;
  25300. // Resetting all other lights if any
  25301. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25302. if (defines["LIGHT" + index] !== undefined) {
  25303. defines["LIGHT" + index] = false;
  25304. defines["HEMILIGHT" + lightIndex] = false;
  25305. defines["POINTLIGHT" + lightIndex] = false;
  25306. defines["DIRLIGHT" + lightIndex] = false;
  25307. defines["SPOTLIGHT" + lightIndex] = false;
  25308. defines["SHADOW" + lightIndex] = false;
  25309. }
  25310. }
  25311. var caps = scene.getEngine().getCaps();
  25312. if (defines["SHADOWFLOAT"] === undefined) {
  25313. needRebuild = true;
  25314. }
  25315. defines["SHADOWFLOAT"] = shadowEnabled &&
  25316. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25317. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25318. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25319. if (needRebuild) {
  25320. defines.rebuild();
  25321. }
  25322. return needNormals;
  25323. };
  25324. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25325. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25326. var uniformsList, uniformBuffersList, samplersList, defines;
  25327. if (uniformsListOrOptions.uniformsNames) {
  25328. var options = uniformsListOrOptions;
  25329. uniformsList = options.uniformsNames;
  25330. uniformBuffersList = options.uniformBuffersNames;
  25331. samplersList = options.samplers;
  25332. defines = options.defines;
  25333. maxSimultaneousLights = options.maxSimultaneousLights;
  25334. }
  25335. else {
  25336. uniformsList = uniformsListOrOptions;
  25337. }
  25338. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25339. if (!defines["LIGHT" + lightIndex]) {
  25340. break;
  25341. }
  25342. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25343. if (uniformBuffersList) {
  25344. uniformBuffersList.push("Light" + lightIndex);
  25345. }
  25346. samplersList.push("shadowSampler" + lightIndex);
  25347. }
  25348. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25349. uniformsList.push("morphTargetInfluences");
  25350. }
  25351. };
  25352. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25353. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25354. if (!defines["SHADOWS"]) {
  25355. return;
  25356. }
  25357. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25358. if (!defines["LIGHT" + lightIndex]) {
  25359. break;
  25360. }
  25361. if (lightIndex > 0) {
  25362. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25363. }
  25364. if (defines["SHADOW" + lightIndex]) {
  25365. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25366. }
  25367. if (defines["SHADOWPCF" + lightIndex]) {
  25368. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25369. }
  25370. if (defines["SHADOWESM" + lightIndex]) {
  25371. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25372. }
  25373. }
  25374. };
  25375. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25376. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25377. if (influencers > 0) {
  25378. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25379. var manager = mesh.morphTargetManager;
  25380. var normal = manager.supportsNormals && defines["NORMAL"];
  25381. var tangent = manager.supportsTangents && defines["TANGENT"];
  25382. for (var index = 0; index < influencers; index++) {
  25383. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25384. if (normal) {
  25385. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25386. }
  25387. if (tangent) {
  25388. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25389. }
  25390. if (attribs.length > maxAttributesCount) {
  25391. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25392. }
  25393. }
  25394. }
  25395. };
  25396. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25397. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25398. fallbacks.addCPUSkinningFallback(0, mesh);
  25399. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25400. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25401. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25402. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25403. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25404. }
  25405. }
  25406. };
  25407. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25408. if (defines["INSTANCES"]) {
  25409. attribs.push("world0");
  25410. attribs.push("world1");
  25411. attribs.push("world2");
  25412. attribs.push("world3");
  25413. }
  25414. };
  25415. // Bindings
  25416. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25417. if (light.shadowEnabled && mesh.receiveShadows) {
  25418. var shadowGenerator = light.getShadowGenerator();
  25419. if (shadowGenerator) {
  25420. shadowGenerator.bindShadowLight(lightIndex, effect);
  25421. }
  25422. }
  25423. };
  25424. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25425. light.transferToEffect(effect, lightIndex + "");
  25426. };
  25427. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25428. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25429. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25430. var lightIndex = 0;
  25431. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25432. var light = _a[_i];
  25433. var scaledIntensity = light.getScaledIntensity();
  25434. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25435. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25436. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25437. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25438. if (defines["SPECULARTERM"]) {
  25439. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25440. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25441. }
  25442. // Shadows
  25443. if (scene.shadowsEnabled) {
  25444. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25445. }
  25446. light._uniformBuffer.update();
  25447. lightIndex++;
  25448. if (lightIndex === maxSimultaneousLights)
  25449. break;
  25450. }
  25451. };
  25452. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25453. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25454. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25455. effect.setColor3("vFogColor", scene.fogColor);
  25456. }
  25457. };
  25458. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25459. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25460. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25461. if (matrices) {
  25462. effect.setMatrices("mBones", matrices);
  25463. }
  25464. }
  25465. };
  25466. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25467. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25468. return;
  25469. }
  25470. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25471. };
  25472. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25473. if (defines["LOGARITHMICDEPTH"]) {
  25474. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25475. }
  25476. };
  25477. MaterialHelper.BindClipPlane = function (effect, scene) {
  25478. if (scene.clipPlane) {
  25479. var clipPlane = scene.clipPlane;
  25480. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25481. }
  25482. };
  25483. return MaterialHelper;
  25484. }());
  25485. BABYLON.MaterialHelper = MaterialHelper;
  25486. })(BABYLON || (BABYLON = {}));
  25487. //# sourceMappingURL=babylon.materialHelper.js.map
  25488. var BABYLON;
  25489. (function (BABYLON) {
  25490. var MaterialDefines = (function () {
  25491. function MaterialDefines() {
  25492. this._isDirty = true;
  25493. this._areLightsDirty = true;
  25494. this._areAttributesDirty = true;
  25495. this._areTexturesDirty = true;
  25496. this._areFresnelDirty = true;
  25497. this._areMiscDirty = true;
  25498. this._areImageProcessingDirty = true;
  25499. this._normals = false;
  25500. this._uvs = false;
  25501. this._needNormals = false;
  25502. this._needUVs = false;
  25503. }
  25504. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25505. get: function () {
  25506. return this._isDirty;
  25507. },
  25508. enumerable: true,
  25509. configurable: true
  25510. });
  25511. MaterialDefines.prototype.markAsProcessed = function () {
  25512. this._isDirty = false;
  25513. this._areAttributesDirty = false;
  25514. this._areTexturesDirty = false;
  25515. this._areFresnelDirty = false;
  25516. this._areLightsDirty = false;
  25517. this._areMiscDirty = false;
  25518. this._areImageProcessingDirty = false;
  25519. };
  25520. MaterialDefines.prototype.markAsUnprocessed = function () {
  25521. this._isDirty = true;
  25522. };
  25523. MaterialDefines.prototype.markAllAsDirty = function () {
  25524. this._areTexturesDirty = true;
  25525. this._areAttributesDirty = true;
  25526. this._areLightsDirty = true;
  25527. this._areFresnelDirty = true;
  25528. this._areMiscDirty = true;
  25529. this._areImageProcessingDirty = true;
  25530. this._isDirty = true;
  25531. };
  25532. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25533. this._areImageProcessingDirty = true;
  25534. this._isDirty = true;
  25535. };
  25536. MaterialDefines.prototype.markAsLightDirty = function () {
  25537. this._areLightsDirty = true;
  25538. this._isDirty = true;
  25539. };
  25540. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25541. this._areAttributesDirty = true;
  25542. this._isDirty = true;
  25543. };
  25544. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25545. this._areTexturesDirty = true;
  25546. this._isDirty = true;
  25547. };
  25548. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25549. this._areFresnelDirty = true;
  25550. this._isDirty = true;
  25551. };
  25552. MaterialDefines.prototype.markAsMiscDirty = function () {
  25553. this._areMiscDirty = true;
  25554. this._isDirty = true;
  25555. };
  25556. MaterialDefines.prototype.rebuild = function () {
  25557. if (this._keys) {
  25558. delete this._keys;
  25559. }
  25560. this._keys = [];
  25561. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25562. var key = _a[_i];
  25563. if (key[0] === "_") {
  25564. continue;
  25565. }
  25566. this._keys.push(key);
  25567. }
  25568. };
  25569. MaterialDefines.prototype.isEqual = function (other) {
  25570. if (this._keys.length !== other._keys.length) {
  25571. return false;
  25572. }
  25573. for (var index = 0; index < this._keys.length; index++) {
  25574. var prop = this._keys[index];
  25575. if (this[prop] !== other[prop]) {
  25576. return false;
  25577. }
  25578. }
  25579. return true;
  25580. };
  25581. MaterialDefines.prototype.cloneTo = function (other) {
  25582. if (this._keys.length !== other._keys.length) {
  25583. other._keys = this._keys.slice(0);
  25584. }
  25585. for (var index = 0; index < this._keys.length; index++) {
  25586. var prop = this._keys[index];
  25587. other[prop] = this[prop];
  25588. }
  25589. };
  25590. MaterialDefines.prototype.reset = function () {
  25591. for (var index = 0; index < this._keys.length; index++) {
  25592. var prop = this._keys[index];
  25593. if (typeof (this[prop]) === "number") {
  25594. this[prop] = 0;
  25595. }
  25596. else {
  25597. this[prop] = false;
  25598. }
  25599. }
  25600. };
  25601. MaterialDefines.prototype.toString = function () {
  25602. var result = "";
  25603. for (var index = 0; index < this._keys.length; index++) {
  25604. var prop = this._keys[index];
  25605. var value = this[prop];
  25606. if (typeof (value) === "number") {
  25607. result += "#define " + prop + " " + this[prop] + "\n";
  25608. }
  25609. else if (value) {
  25610. result += "#define " + prop + "\n";
  25611. }
  25612. }
  25613. return result;
  25614. };
  25615. return MaterialDefines;
  25616. }());
  25617. BABYLON.MaterialDefines = MaterialDefines;
  25618. var Material = (function () {
  25619. function Material(name, scene, doNotAdd) {
  25620. this.checkReadyOnEveryCall = false;
  25621. this.checkReadyOnlyOnce = false;
  25622. this.state = "";
  25623. this.alpha = 1.0;
  25624. this._backFaceCulling = true;
  25625. this.doNotSerialize = false;
  25626. this.storeEffectOnSubMeshes = false;
  25627. /**
  25628. * An event triggered when the material is disposed.
  25629. * @type {BABYLON.Observable}
  25630. */
  25631. this.onDisposeObservable = new BABYLON.Observable();
  25632. /**
  25633. * An event triggered when the material is bound.
  25634. * @type {BABYLON.Observable}
  25635. */
  25636. this.onBindObservable = new BABYLON.Observable();
  25637. /**
  25638. * An event triggered when the material is unbound.
  25639. * @type {BABYLON.Observable}
  25640. */
  25641. this.onUnBindObservable = new BABYLON.Observable();
  25642. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25643. this.needDepthPrePass = false;
  25644. this.disableDepthWrite = false;
  25645. this._fogEnabled = true;
  25646. this.pointSize = 1.0;
  25647. this.zOffset = 0;
  25648. this._wasPreviouslyReady = false;
  25649. this._fillMode = Material.TriangleFillMode;
  25650. this.name = name;
  25651. this.id = name || BABYLON.Tools.RandomId();
  25652. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25653. if (this._scene.useRightHandedSystem) {
  25654. this.sideOrientation = Material.ClockWiseSideOrientation;
  25655. }
  25656. else {
  25657. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25658. }
  25659. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25660. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25661. if (!doNotAdd) {
  25662. this._scene.materials.push(this);
  25663. }
  25664. }
  25665. Object.defineProperty(Material, "TriangleFillMode", {
  25666. get: function () {
  25667. return Material._TriangleFillMode;
  25668. },
  25669. enumerable: true,
  25670. configurable: true
  25671. });
  25672. Object.defineProperty(Material, "WireFrameFillMode", {
  25673. get: function () {
  25674. return Material._WireFrameFillMode;
  25675. },
  25676. enumerable: true,
  25677. configurable: true
  25678. });
  25679. Object.defineProperty(Material, "PointFillMode", {
  25680. get: function () {
  25681. return Material._PointFillMode;
  25682. },
  25683. enumerable: true,
  25684. configurable: true
  25685. });
  25686. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25687. get: function () {
  25688. return Material._ClockWiseSideOrientation;
  25689. },
  25690. enumerable: true,
  25691. configurable: true
  25692. });
  25693. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25694. get: function () {
  25695. return Material._CounterClockWiseSideOrientation;
  25696. },
  25697. enumerable: true,
  25698. configurable: true
  25699. });
  25700. Object.defineProperty(Material, "TextureDirtyFlag", {
  25701. get: function () {
  25702. return Material._TextureDirtyFlag;
  25703. },
  25704. enumerable: true,
  25705. configurable: true
  25706. });
  25707. Object.defineProperty(Material, "LightDirtyFlag", {
  25708. get: function () {
  25709. return Material._LightDirtyFlag;
  25710. },
  25711. enumerable: true,
  25712. configurable: true
  25713. });
  25714. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25715. get: function () {
  25716. return Material._FresnelDirtyFlag;
  25717. },
  25718. enumerable: true,
  25719. configurable: true
  25720. });
  25721. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25722. get: function () {
  25723. return Material._AttributesDirtyFlag;
  25724. },
  25725. enumerable: true,
  25726. configurable: true
  25727. });
  25728. Object.defineProperty(Material, "MiscDirtyFlag", {
  25729. get: function () {
  25730. return Material._MiscDirtyFlag;
  25731. },
  25732. enumerable: true,
  25733. configurable: true
  25734. });
  25735. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25736. get: function () {
  25737. return this._backFaceCulling;
  25738. },
  25739. set: function (value) {
  25740. if (this._backFaceCulling === value) {
  25741. return;
  25742. }
  25743. this._backFaceCulling = value;
  25744. this.markAsDirty(Material.TextureDirtyFlag);
  25745. },
  25746. enumerable: true,
  25747. configurable: true
  25748. });
  25749. Object.defineProperty(Material.prototype, "onDispose", {
  25750. set: function (callback) {
  25751. if (this._onDisposeObserver) {
  25752. this.onDisposeObservable.remove(this._onDisposeObserver);
  25753. }
  25754. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25755. },
  25756. enumerable: true,
  25757. configurable: true
  25758. });
  25759. Object.defineProperty(Material.prototype, "onBind", {
  25760. set: function (callback) {
  25761. if (this._onBindObserver) {
  25762. this.onBindObservable.remove(this._onBindObserver);
  25763. }
  25764. this._onBindObserver = this.onBindObservable.add(callback);
  25765. },
  25766. enumerable: true,
  25767. configurable: true
  25768. });
  25769. Object.defineProperty(Material.prototype, "fogEnabled", {
  25770. get: function () {
  25771. return this._fogEnabled;
  25772. },
  25773. set: function (value) {
  25774. if (this._fogEnabled === value) {
  25775. return;
  25776. }
  25777. this._fogEnabled = value;
  25778. this.markAsDirty(Material.MiscDirtyFlag);
  25779. },
  25780. enumerable: true,
  25781. configurable: true
  25782. });
  25783. Object.defineProperty(Material.prototype, "wireframe", {
  25784. get: function () {
  25785. return this._fillMode === Material.WireFrameFillMode;
  25786. },
  25787. set: function (value) {
  25788. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25789. },
  25790. enumerable: true,
  25791. configurable: true
  25792. });
  25793. Object.defineProperty(Material.prototype, "pointsCloud", {
  25794. get: function () {
  25795. return this._fillMode === Material.PointFillMode;
  25796. },
  25797. set: function (value) {
  25798. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25799. },
  25800. enumerable: true,
  25801. configurable: true
  25802. });
  25803. Object.defineProperty(Material.prototype, "fillMode", {
  25804. get: function () {
  25805. return this._fillMode;
  25806. },
  25807. set: function (value) {
  25808. if (this._fillMode === value) {
  25809. return;
  25810. }
  25811. this._fillMode = value;
  25812. this.markAsDirty(Material.MiscDirtyFlag);
  25813. },
  25814. enumerable: true,
  25815. configurable: true
  25816. });
  25817. /**
  25818. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25819. * subclasses should override adding information pertainent to themselves
  25820. */
  25821. Material.prototype.toString = function (fullDetails) {
  25822. var ret = "Name: " + this.name;
  25823. if (fullDetails) {
  25824. }
  25825. return ret;
  25826. };
  25827. /**
  25828. * Child classes can use it to update shaders
  25829. */
  25830. Material.prototype.getClassName = function () {
  25831. return "Material";
  25832. };
  25833. Object.defineProperty(Material.prototype, "isFrozen", {
  25834. get: function () {
  25835. return this.checkReadyOnlyOnce;
  25836. },
  25837. enumerable: true,
  25838. configurable: true
  25839. });
  25840. Material.prototype.freeze = function () {
  25841. this.checkReadyOnlyOnce = true;
  25842. };
  25843. Material.prototype.unfreeze = function () {
  25844. this.checkReadyOnlyOnce = false;
  25845. };
  25846. Material.prototype.isReady = function (mesh, useInstances) {
  25847. return true;
  25848. };
  25849. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25850. return false;
  25851. };
  25852. Material.prototype.getEffect = function () {
  25853. return this._effect;
  25854. };
  25855. Material.prototype.getScene = function () {
  25856. return this._scene;
  25857. };
  25858. Material.prototype.needAlphaBlending = function () {
  25859. return (this.alpha < 1.0);
  25860. };
  25861. Material.prototype.needAlphaTesting = function () {
  25862. return false;
  25863. };
  25864. Material.prototype.getAlphaTestTexture = function () {
  25865. return null;
  25866. };
  25867. Material.prototype.markDirty = function () {
  25868. this._wasPreviouslyReady = false;
  25869. };
  25870. Material.prototype._preBind = function (effect) {
  25871. var engine = this._scene.getEngine();
  25872. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25873. engine.enableEffect(effect ? effect : this._effect);
  25874. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25875. };
  25876. Material.prototype.bind = function (world, mesh) {
  25877. };
  25878. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25879. };
  25880. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25881. };
  25882. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25883. sceneUbo.bindToEffect(effect, "Scene");
  25884. };
  25885. Material.prototype.bindView = function (effect) {
  25886. if (!this._useUBO) {
  25887. effect.setMatrix("view", this.getScene().getViewMatrix());
  25888. }
  25889. else {
  25890. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25891. }
  25892. };
  25893. Material.prototype.bindViewProjection = function (effect) {
  25894. if (!this._useUBO) {
  25895. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25896. }
  25897. else {
  25898. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25899. }
  25900. };
  25901. Material.prototype._afterBind = function (mesh) {
  25902. this._scene._cachedMaterial = this;
  25903. if (mesh) {
  25904. this._scene._cachedVisibility = mesh.visibility;
  25905. }
  25906. else {
  25907. this._scene._cachedVisibility = 1;
  25908. }
  25909. this.onBindObservable.notifyObservers(mesh);
  25910. if (this.disableDepthWrite) {
  25911. var engine = this._scene.getEngine();
  25912. this._cachedDepthWriteState = engine.getDepthWrite();
  25913. engine.setDepthWrite(false);
  25914. }
  25915. };
  25916. Material.prototype.unbind = function () {
  25917. this.onUnBindObservable.notifyObservers(this);
  25918. if (this.disableDepthWrite) {
  25919. var engine = this._scene.getEngine();
  25920. engine.setDepthWrite(this._cachedDepthWriteState);
  25921. }
  25922. };
  25923. Material.prototype.getActiveTextures = function () {
  25924. return [];
  25925. };
  25926. Material.prototype.hasTexture = function (texture) {
  25927. return false;
  25928. };
  25929. Material.prototype.clone = function (name) {
  25930. return null;
  25931. };
  25932. Material.prototype.getBindedMeshes = function () {
  25933. var result = new Array();
  25934. for (var index = 0; index < this._scene.meshes.length; index++) {
  25935. var mesh = this._scene.meshes[index];
  25936. if (mesh.material === this) {
  25937. result.push(mesh);
  25938. }
  25939. }
  25940. return result;
  25941. };
  25942. /**
  25943. * Force shader compilation including textures ready check
  25944. */
  25945. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25946. var _this = this;
  25947. var subMesh = new BABYLON.BaseSubMesh();
  25948. var scene = this.getScene();
  25949. var engine = scene.getEngine();
  25950. var checkReady = function () {
  25951. if (!_this._scene || !_this._scene.getEngine()) {
  25952. return;
  25953. }
  25954. if (subMesh._materialDefines) {
  25955. subMesh._materialDefines._renderId = -1;
  25956. }
  25957. var alphaTestState = engine.getAlphaTesting();
  25958. var clipPlaneState = scene.clipPlane;
  25959. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25960. if (options && options.clipPlane) {
  25961. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25962. }
  25963. if (_this.storeEffectOnSubMeshes) {
  25964. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25965. if (onCompiled) {
  25966. onCompiled(_this);
  25967. }
  25968. }
  25969. else {
  25970. setTimeout(checkReady, 16);
  25971. }
  25972. }
  25973. else {
  25974. if (_this.isReady(mesh)) {
  25975. if (onCompiled) {
  25976. onCompiled(_this);
  25977. }
  25978. }
  25979. else {
  25980. setTimeout(checkReady, 16);
  25981. }
  25982. }
  25983. engine.setAlphaTesting(alphaTestState);
  25984. if (options && options.clipPlane) {
  25985. scene.clipPlane = clipPlaneState;
  25986. }
  25987. };
  25988. checkReady();
  25989. };
  25990. Material.prototype.markAsDirty = function (flag) {
  25991. if (flag & Material.TextureDirtyFlag) {
  25992. this._markAllSubMeshesAsTexturesDirty();
  25993. }
  25994. if (flag & Material.LightDirtyFlag) {
  25995. this._markAllSubMeshesAsLightsDirty();
  25996. }
  25997. if (flag & Material.FresnelDirtyFlag) {
  25998. this._markAllSubMeshesAsFresnelDirty();
  25999. }
  26000. if (flag & Material.AttributesDirtyFlag) {
  26001. this._markAllSubMeshesAsAttributesDirty();
  26002. }
  26003. if (flag & Material.MiscDirtyFlag) {
  26004. this._markAllSubMeshesAsMiscDirty();
  26005. }
  26006. this.getScene().resetCachedMaterial();
  26007. };
  26008. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  26009. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  26010. var mesh = _a[_i];
  26011. if (!mesh.subMeshes) {
  26012. continue;
  26013. }
  26014. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26015. var subMesh = _c[_b];
  26016. if (subMesh.getMaterial() !== this) {
  26017. continue;
  26018. }
  26019. if (!subMesh._materialDefines) {
  26020. continue;
  26021. }
  26022. func(subMesh._materialDefines);
  26023. }
  26024. }
  26025. };
  26026. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  26027. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  26028. };
  26029. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  26030. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  26031. };
  26032. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  26033. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  26034. };
  26035. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  26036. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  26037. };
  26038. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  26039. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  26040. };
  26041. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  26042. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  26043. };
  26044. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26045. // Animations
  26046. this.getScene().stopAnimation(this);
  26047. // Remove from scene
  26048. var index = this._scene.materials.indexOf(this);
  26049. if (index >= 0) {
  26050. this._scene.materials.splice(index, 1);
  26051. }
  26052. // Remove from meshes
  26053. for (index = 0; index < this._scene.meshes.length; index++) {
  26054. var mesh = this._scene.meshes[index];
  26055. if (mesh.material === this) {
  26056. mesh.material = null;
  26057. if (mesh.geometry) {
  26058. var geometry = mesh.geometry;
  26059. if (this.storeEffectOnSubMeshes) {
  26060. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  26061. var subMesh = _a[_i];
  26062. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  26063. }
  26064. }
  26065. else {
  26066. geometry._releaseVertexArrayObject(this._effect);
  26067. }
  26068. }
  26069. }
  26070. }
  26071. this._uniformBuffer.dispose();
  26072. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26073. if (forceDisposeEffect && this._effect) {
  26074. if (this.storeEffectOnSubMeshes) {
  26075. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26076. var subMesh = _c[_b];
  26077. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  26078. }
  26079. }
  26080. else {
  26081. this._scene.getEngine()._releaseEffect(this._effect);
  26082. }
  26083. this._effect = null;
  26084. }
  26085. // Callback
  26086. this.onDisposeObservable.notifyObservers(this);
  26087. this.onDisposeObservable.clear();
  26088. this.onBindObservable.clear();
  26089. this.onUnBindObservable.clear();
  26090. };
  26091. Material.prototype.serialize = function () {
  26092. return BABYLON.SerializationHelper.Serialize(this);
  26093. };
  26094. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26095. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26096. multiMaterial.id = parsedMultiMaterial.id;
  26097. if (BABYLON.Tags) {
  26098. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26099. }
  26100. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26101. var subMatId = parsedMultiMaterial.materials[matIndex];
  26102. if (subMatId) {
  26103. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26104. }
  26105. else {
  26106. multiMaterial.subMaterials.push(null);
  26107. }
  26108. }
  26109. return multiMaterial;
  26110. };
  26111. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26112. if (!parsedMaterial.customType) {
  26113. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26114. }
  26115. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  26116. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  26117. if (!BABYLON.LegacyPBRMaterial) {
  26118. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  26119. return;
  26120. }
  26121. }
  26122. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26123. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26124. ;
  26125. };
  26126. Material._TriangleFillMode = 0;
  26127. Material._WireFrameFillMode = 1;
  26128. Material._PointFillMode = 2;
  26129. Material._ClockWiseSideOrientation = 0;
  26130. Material._CounterClockWiseSideOrientation = 1;
  26131. Material._TextureDirtyFlag = 1;
  26132. Material._LightDirtyFlag = 2;
  26133. Material._FresnelDirtyFlag = 4;
  26134. Material._AttributesDirtyFlag = 8;
  26135. Material._MiscDirtyFlag = 16;
  26136. __decorate([
  26137. BABYLON.serialize()
  26138. ], Material.prototype, "id", void 0);
  26139. __decorate([
  26140. BABYLON.serialize()
  26141. ], Material.prototype, "name", void 0);
  26142. __decorate([
  26143. BABYLON.serialize()
  26144. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26145. __decorate([
  26146. BABYLON.serialize()
  26147. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26148. __decorate([
  26149. BABYLON.serialize()
  26150. ], Material.prototype, "state", void 0);
  26151. __decorate([
  26152. BABYLON.serialize()
  26153. ], Material.prototype, "alpha", void 0);
  26154. __decorate([
  26155. BABYLON.serialize("backFaceCulling")
  26156. ], Material.prototype, "_backFaceCulling", void 0);
  26157. __decorate([
  26158. BABYLON.serialize()
  26159. ], Material.prototype, "sideOrientation", void 0);
  26160. __decorate([
  26161. BABYLON.serialize()
  26162. ], Material.prototype, "alphaMode", void 0);
  26163. __decorate([
  26164. BABYLON.serialize()
  26165. ], Material.prototype, "needDepthPrePass", void 0);
  26166. __decorate([
  26167. BABYLON.serialize()
  26168. ], Material.prototype, "disableDepthWrite", void 0);
  26169. __decorate([
  26170. BABYLON.serialize("fogEnabled")
  26171. ], Material.prototype, "_fogEnabled", void 0);
  26172. __decorate([
  26173. BABYLON.serialize()
  26174. ], Material.prototype, "pointSize", void 0);
  26175. __decorate([
  26176. BABYLON.serialize()
  26177. ], Material.prototype, "zOffset", void 0);
  26178. __decorate([
  26179. BABYLON.serialize()
  26180. ], Material.prototype, "wireframe", null);
  26181. __decorate([
  26182. BABYLON.serialize()
  26183. ], Material.prototype, "pointsCloud", null);
  26184. __decorate([
  26185. BABYLON.serialize()
  26186. ], Material.prototype, "fillMode", null);
  26187. return Material;
  26188. }());
  26189. BABYLON.Material = Material;
  26190. })(BABYLON || (BABYLON = {}));
  26191. //# sourceMappingURL=babylon.material.js.map
  26192. var BABYLON;
  26193. (function (BABYLON) {
  26194. var UniformBuffer = (function () {
  26195. /**
  26196. * Uniform buffer objects.
  26197. *
  26198. * Handles blocks of uniform on the GPU.
  26199. *
  26200. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  26201. *
  26202. * For more information, please refer to :
  26203. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  26204. */
  26205. function UniformBuffer(engine, data, dynamic) {
  26206. this._engine = engine;
  26207. this._noUBO = !engine.supportsUniformBuffers;
  26208. this._dynamic = dynamic;
  26209. this._data = data || [];
  26210. this._uniformLocations = {};
  26211. this._uniformSizes = {};
  26212. this._uniformLocationPointer = 0;
  26213. this._needSync = false;
  26214. if (this._noUBO) {
  26215. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  26216. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  26217. this.updateFloat = this._updateFloatForEffect;
  26218. this.updateFloat2 = this._updateFloat2ForEffect;
  26219. this.updateFloat3 = this._updateFloat3ForEffect;
  26220. this.updateFloat4 = this._updateFloat4ForEffect;
  26221. this.updateMatrix = this._updateMatrixForEffect;
  26222. this.updateVector3 = this._updateVector3ForEffect;
  26223. this.updateVector4 = this._updateVector4ForEffect;
  26224. this.updateColor3 = this._updateColor3ForEffect;
  26225. this.updateColor4 = this._updateColor4ForEffect;
  26226. }
  26227. else {
  26228. this._engine._uniformBuffers.push(this);
  26229. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  26230. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  26231. this.updateFloat = this._updateFloatForUniform;
  26232. this.updateFloat2 = this._updateFloat2ForUniform;
  26233. this.updateFloat3 = this._updateFloat3ForUniform;
  26234. this.updateFloat4 = this._updateFloat4ForUniform;
  26235. this.updateMatrix = this._updateMatrixForUniform;
  26236. this.updateVector3 = this._updateVector3ForUniform;
  26237. this.updateVector4 = this._updateVector4ForUniform;
  26238. this.updateColor3 = this._updateColor3ForUniform;
  26239. this.updateColor4 = this._updateColor4ForUniform;
  26240. }
  26241. }
  26242. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  26243. // Properties
  26244. /**
  26245. * Indicates if the buffer is using the WebGL2 UBO implementation,
  26246. * or just falling back on setUniformXXX calls.
  26247. */
  26248. get: function () {
  26249. return !this._noUBO;
  26250. },
  26251. enumerable: true,
  26252. configurable: true
  26253. });
  26254. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  26255. /**
  26256. * Indicates if the WebGL underlying uniform buffer is in sync
  26257. * with the javascript cache data.
  26258. */
  26259. get: function () {
  26260. return !this._needSync;
  26261. },
  26262. enumerable: true,
  26263. configurable: true
  26264. });
  26265. /**
  26266. * Indicates if the WebGL underlying uniform buffer is dynamic.
  26267. * Also, a dynamic UniformBuffer will disable cache verification and always
  26268. * update the underlying WebGL uniform buffer to the GPU.
  26269. */
  26270. UniformBuffer.prototype.isDynamic = function () {
  26271. return this._dynamic;
  26272. };
  26273. /**
  26274. * The data cache on JS side.
  26275. */
  26276. UniformBuffer.prototype.getData = function () {
  26277. return this._bufferData;
  26278. };
  26279. /**
  26280. * The underlying WebGL Uniform buffer.
  26281. */
  26282. UniformBuffer.prototype.getBuffer = function () {
  26283. return this._buffer;
  26284. };
  26285. /**
  26286. * std140 layout specifies how to align data within an UBO structure.
  26287. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  26288. * for specs.
  26289. */
  26290. UniformBuffer.prototype._fillAlignment = function (size) {
  26291. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  26292. // and 4x4 matrices
  26293. // TODO : change if other types are used
  26294. var alignment;
  26295. if (size <= 2) {
  26296. alignment = size;
  26297. }
  26298. else {
  26299. alignment = 4;
  26300. }
  26301. if ((this._uniformLocationPointer % alignment) !== 0) {
  26302. var oldPointer = this._uniformLocationPointer;
  26303. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26304. var diff = this._uniformLocationPointer - oldPointer;
  26305. for (var i = 0; i < diff; i++) {
  26306. this._data.push(0);
  26307. }
  26308. }
  26309. };
  26310. /**
  26311. * Adds an uniform in the buffer.
  26312. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26313. * for the layout to be correct !
  26314. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26315. * @param {number|number[]} size Data size, or data directly.
  26316. */
  26317. UniformBuffer.prototype.addUniform = function (name, size) {
  26318. if (this._noUBO) {
  26319. return;
  26320. }
  26321. if (this._uniformLocations[name] !== undefined) {
  26322. // Already existing uniform
  26323. return;
  26324. }
  26325. // This function must be called in the order of the shader layout !
  26326. // size can be the size of the uniform, or data directly
  26327. var data;
  26328. if (size instanceof Array) {
  26329. data = size;
  26330. size = data.length;
  26331. }
  26332. else {
  26333. size = size;
  26334. data = [];
  26335. // Fill with zeros
  26336. for (var i = 0; i < size; i++) {
  26337. data.push(0);
  26338. }
  26339. }
  26340. this._fillAlignment(size);
  26341. this._uniformSizes[name] = size;
  26342. this._uniformLocations[name] = this._uniformLocationPointer;
  26343. this._uniformLocationPointer += size;
  26344. for (var i = 0; i < size; i++) {
  26345. this._data.push(data[i]);
  26346. }
  26347. this._needSync = true;
  26348. };
  26349. /**
  26350. * Wrapper for addUniform.
  26351. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26352. * @param {Matrix} mat A 4x4 matrix.
  26353. */
  26354. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26355. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26356. };
  26357. /**
  26358. * Wrapper for addUniform.
  26359. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26360. * @param {number} x
  26361. * @param {number} y
  26362. */
  26363. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26364. var temp = [x, y];
  26365. this.addUniform(name, temp);
  26366. };
  26367. /**
  26368. * Wrapper for addUniform.
  26369. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26370. * @param {number} x
  26371. * @param {number} y
  26372. * @param {number} z
  26373. */
  26374. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26375. var temp = [x, y, z];
  26376. this.addUniform(name, temp);
  26377. };
  26378. /**
  26379. * Wrapper for addUniform.
  26380. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26381. * @param {Color3} color
  26382. */
  26383. UniformBuffer.prototype.addColor3 = function (name, color) {
  26384. var temp = [];
  26385. color.toArray(temp);
  26386. this.addUniform(name, temp);
  26387. };
  26388. /**
  26389. * Wrapper for addUniform.
  26390. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26391. * @param {Color3} color
  26392. * @param {number} alpha
  26393. */
  26394. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26395. var temp = [];
  26396. color.toArray(temp);
  26397. temp.push(alpha);
  26398. this.addUniform(name, temp);
  26399. };
  26400. /**
  26401. * Wrapper for addUniform.
  26402. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26403. * @param {Vector3} vector
  26404. */
  26405. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26406. var temp = [];
  26407. vector.toArray(temp);
  26408. this.addUniform(name, temp);
  26409. };
  26410. /**
  26411. * Wrapper for addUniform.
  26412. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26413. */
  26414. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26415. this.addUniform(name, 12);
  26416. };
  26417. /**
  26418. * Wrapper for addUniform.
  26419. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26420. */
  26421. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26422. this.addUniform(name, 8);
  26423. };
  26424. /**
  26425. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26426. */
  26427. UniformBuffer.prototype.create = function () {
  26428. if (this._noUBO) {
  26429. return;
  26430. }
  26431. if (this._buffer) {
  26432. return; // nothing to do
  26433. }
  26434. // See spec, alignment must be filled as a vec4
  26435. this._fillAlignment(4);
  26436. this._bufferData = new Float32Array(this._data);
  26437. this._rebuild();
  26438. this._needSync = true;
  26439. };
  26440. UniformBuffer.prototype._rebuild = function () {
  26441. if (this._noUBO) {
  26442. return;
  26443. }
  26444. if (this._dynamic) {
  26445. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26446. }
  26447. else {
  26448. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26449. }
  26450. };
  26451. /**
  26452. * Updates the WebGL Uniform Buffer on the GPU.
  26453. * If the `dynamic` flag is set to true, no cache comparison is done.
  26454. * Otherwise, the buffer will be updated only if the cache differs.
  26455. */
  26456. UniformBuffer.prototype.update = function () {
  26457. if (!this._buffer) {
  26458. this.create();
  26459. return;
  26460. }
  26461. if (!this._dynamic && !this._needSync) {
  26462. return;
  26463. }
  26464. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26465. this._needSync = false;
  26466. };
  26467. /**
  26468. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26469. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26470. * @param {number[]|Float32Array} data Flattened data
  26471. * @param {number} size Size of the data.
  26472. */
  26473. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26474. var location = this._uniformLocations[uniformName];
  26475. if (location === undefined) {
  26476. if (this._buffer) {
  26477. // Cannot add an uniform if the buffer is already created
  26478. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26479. return;
  26480. }
  26481. this.addUniform(uniformName, size);
  26482. location = this._uniformLocations[uniformName];
  26483. }
  26484. if (!this._buffer) {
  26485. this.create();
  26486. }
  26487. if (!this._dynamic) {
  26488. // Cache for static uniform buffers
  26489. var changed = false;
  26490. for (var i = 0; i < size; i++) {
  26491. if (this._bufferData[location + i] !== data[i]) {
  26492. changed = true;
  26493. this._bufferData[location + i] = data[i];
  26494. }
  26495. }
  26496. this._needSync = this._needSync || changed;
  26497. }
  26498. else {
  26499. // No cache for dynamic
  26500. for (var i = 0; i < size; i++) {
  26501. this._bufferData[location + i] = data[i];
  26502. }
  26503. }
  26504. };
  26505. // Update methods
  26506. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26507. // To match std140, matrix must be realigned
  26508. for (var i = 0; i < 3; i++) {
  26509. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26510. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26511. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26512. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26513. }
  26514. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26515. };
  26516. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26517. this._currentEffect.setMatrix3x3(name, matrix);
  26518. };
  26519. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26520. this._currentEffect.setMatrix2x2(name, matrix);
  26521. };
  26522. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26523. // To match std140, matrix must be realigned
  26524. for (var i = 0; i < 2; i++) {
  26525. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26526. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26527. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26528. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26529. }
  26530. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26531. };
  26532. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26533. this._currentEffect.setFloat(name, x);
  26534. };
  26535. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26536. UniformBuffer._tempBuffer[0] = x;
  26537. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26538. };
  26539. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26540. if (suffix === void 0) { suffix = ""; }
  26541. this._currentEffect.setFloat2(name + suffix, x, y);
  26542. };
  26543. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26544. if (suffix === void 0) { suffix = ""; }
  26545. UniformBuffer._tempBuffer[0] = x;
  26546. UniformBuffer._tempBuffer[1] = y;
  26547. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26548. };
  26549. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26550. if (suffix === void 0) { suffix = ""; }
  26551. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26552. };
  26553. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26554. if (suffix === void 0) { suffix = ""; }
  26555. UniformBuffer._tempBuffer[0] = x;
  26556. UniformBuffer._tempBuffer[1] = y;
  26557. UniformBuffer._tempBuffer[2] = z;
  26558. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26559. };
  26560. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26561. if (suffix === void 0) { suffix = ""; }
  26562. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26563. };
  26564. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26565. if (suffix === void 0) { suffix = ""; }
  26566. UniformBuffer._tempBuffer[0] = x;
  26567. UniformBuffer._tempBuffer[1] = y;
  26568. UniformBuffer._tempBuffer[2] = z;
  26569. UniformBuffer._tempBuffer[3] = w;
  26570. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26571. };
  26572. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26573. this._currentEffect.setMatrix(name, mat);
  26574. };
  26575. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26576. this.updateUniform(name, mat.toArray(), 16);
  26577. };
  26578. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26579. this._currentEffect.setVector3(name, vector);
  26580. };
  26581. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26582. vector.toArray(UniformBuffer._tempBuffer);
  26583. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26584. };
  26585. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26586. this._currentEffect.setVector4(name, vector);
  26587. };
  26588. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26589. vector.toArray(UniformBuffer._tempBuffer);
  26590. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26591. };
  26592. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26593. if (suffix === void 0) { suffix = ""; }
  26594. this._currentEffect.setColor3(name + suffix, color);
  26595. };
  26596. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26597. if (suffix === void 0) { suffix = ""; }
  26598. color.toArray(UniformBuffer._tempBuffer);
  26599. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26600. };
  26601. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26602. if (suffix === void 0) { suffix = ""; }
  26603. this._currentEffect.setColor4(name + suffix, color, alpha);
  26604. };
  26605. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26606. if (suffix === void 0) { suffix = ""; }
  26607. color.toArray(UniformBuffer._tempBuffer);
  26608. UniformBuffer._tempBuffer[3] = alpha;
  26609. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26610. };
  26611. /**
  26612. * Sets a sampler uniform on the effect.
  26613. * @param {string} name Name of the sampler.
  26614. * @param {Texture} texture
  26615. */
  26616. UniformBuffer.prototype.setTexture = function (name, texture) {
  26617. this._currentEffect.setTexture(name, texture);
  26618. };
  26619. /**
  26620. * Directly updates the value of the uniform in the cache AND on the GPU.
  26621. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26622. * @param {number[]|Float32Array} data Flattened data
  26623. */
  26624. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26625. this.updateUniform(uniformName, data, data.length);
  26626. this.update();
  26627. };
  26628. /**
  26629. * Binds this uniform buffer to an effect.
  26630. * @param {Effect} effect
  26631. * @param {string} name Name of the uniform block in the shader.
  26632. */
  26633. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26634. this._currentEffect = effect;
  26635. if (this._noUBO) {
  26636. return;
  26637. }
  26638. effect.bindUniformBuffer(this._buffer, name);
  26639. };
  26640. /**
  26641. * Disposes the uniform buffer.
  26642. */
  26643. UniformBuffer.prototype.dispose = function () {
  26644. if (this._noUBO) {
  26645. return;
  26646. }
  26647. var index = this._engine._uniformBuffers.indexOf(this);
  26648. if (index !== -1) {
  26649. this._engine._uniformBuffers.splice(index, 1);
  26650. }
  26651. if (!this._buffer) {
  26652. return;
  26653. }
  26654. if (this._engine._releaseBuffer(this._buffer)) {
  26655. this._buffer = null;
  26656. }
  26657. };
  26658. // Pool for avoiding memory leaks
  26659. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26660. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26661. return UniformBuffer;
  26662. }());
  26663. BABYLON.UniformBuffer = UniformBuffer;
  26664. })(BABYLON || (BABYLON = {}));
  26665. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26666. var BABYLON;
  26667. (function (BABYLON) {
  26668. var PushMaterial = (function (_super) {
  26669. __extends(PushMaterial, _super);
  26670. function PushMaterial(name, scene) {
  26671. var _this = _super.call(this, name, scene) || this;
  26672. _this.storeEffectOnSubMeshes = true;
  26673. return _this;
  26674. }
  26675. PushMaterial.prototype.getEffect = function () {
  26676. return this._activeEffect;
  26677. };
  26678. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26679. if (!mesh) {
  26680. return false;
  26681. }
  26682. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26683. return true;
  26684. }
  26685. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26686. };
  26687. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26688. this._activeEffect.setMatrix("world", world);
  26689. };
  26690. PushMaterial.prototype.bind = function (world, mesh) {
  26691. if (!mesh) {
  26692. return;
  26693. }
  26694. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26695. };
  26696. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26697. _super.prototype._afterBind.call(this, mesh);
  26698. this.getScene()._cachedEffect = effect;
  26699. };
  26700. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26701. if (visibility === void 0) { visibility = 1; }
  26702. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26703. };
  26704. return PushMaterial;
  26705. }(BABYLON.Material));
  26706. BABYLON.PushMaterial = PushMaterial;
  26707. })(BABYLON || (BABYLON = {}));
  26708. //# sourceMappingURL=babylon.pushMaterial.js.map
  26709. var BABYLON;
  26710. (function (BABYLON) {
  26711. var VertexData = (function () {
  26712. function VertexData() {
  26713. }
  26714. VertexData.prototype.set = function (data, kind) {
  26715. switch (kind) {
  26716. case BABYLON.VertexBuffer.PositionKind:
  26717. this.positions = data;
  26718. break;
  26719. case BABYLON.VertexBuffer.NormalKind:
  26720. this.normals = data;
  26721. break;
  26722. case BABYLON.VertexBuffer.TangentKind:
  26723. this.tangents = data;
  26724. break;
  26725. case BABYLON.VertexBuffer.UVKind:
  26726. this.uvs = data;
  26727. break;
  26728. case BABYLON.VertexBuffer.UV2Kind:
  26729. this.uvs2 = data;
  26730. break;
  26731. case BABYLON.VertexBuffer.UV3Kind:
  26732. this.uvs3 = data;
  26733. break;
  26734. case BABYLON.VertexBuffer.UV4Kind:
  26735. this.uvs4 = data;
  26736. break;
  26737. case BABYLON.VertexBuffer.UV5Kind:
  26738. this.uvs5 = data;
  26739. break;
  26740. case BABYLON.VertexBuffer.UV6Kind:
  26741. this.uvs6 = data;
  26742. break;
  26743. case BABYLON.VertexBuffer.ColorKind:
  26744. this.colors = data;
  26745. break;
  26746. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26747. this.matricesIndices = data;
  26748. break;
  26749. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26750. this.matricesWeights = data;
  26751. break;
  26752. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26753. this.matricesIndicesExtra = data;
  26754. break;
  26755. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26756. this.matricesWeightsExtra = data;
  26757. break;
  26758. }
  26759. };
  26760. /**
  26761. * Associates the vertexData to the passed Mesh.
  26762. * Sets it as updatable or not (default `false`).
  26763. * Returns the VertexData.
  26764. */
  26765. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26766. this._applyTo(mesh, updatable);
  26767. return this;
  26768. };
  26769. /**
  26770. * Associates the vertexData to the passed Geometry.
  26771. * Sets it as updatable or not (default `false`).
  26772. * Returns the VertexData.
  26773. */
  26774. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26775. this._applyTo(geometry, updatable);
  26776. return this;
  26777. };
  26778. /**
  26779. * Updates the associated mesh.
  26780. * Returns the VertexData.
  26781. */
  26782. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26783. this._update(mesh);
  26784. return this;
  26785. };
  26786. /**
  26787. * Updates the associated geometry.
  26788. * Returns the VertexData.
  26789. */
  26790. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26791. this._update(geometry);
  26792. return this;
  26793. };
  26794. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26795. if (this.positions) {
  26796. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26797. }
  26798. if (this.normals) {
  26799. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26800. }
  26801. if (this.tangents) {
  26802. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26803. }
  26804. if (this.uvs) {
  26805. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26806. }
  26807. if (this.uvs2) {
  26808. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26809. }
  26810. if (this.uvs3) {
  26811. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26812. }
  26813. if (this.uvs4) {
  26814. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26815. }
  26816. if (this.uvs5) {
  26817. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26818. }
  26819. if (this.uvs6) {
  26820. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26821. }
  26822. if (this.colors) {
  26823. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26824. }
  26825. if (this.matricesIndices) {
  26826. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26827. }
  26828. if (this.matricesWeights) {
  26829. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26830. }
  26831. if (this.matricesIndicesExtra) {
  26832. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26833. }
  26834. if (this.matricesWeightsExtra) {
  26835. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26836. }
  26837. if (this.indices) {
  26838. meshOrGeometry.setIndices(this.indices);
  26839. }
  26840. return this;
  26841. };
  26842. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26843. if (this.positions) {
  26844. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26845. }
  26846. if (this.normals) {
  26847. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26848. }
  26849. if (this.tangents) {
  26850. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26851. }
  26852. if (this.uvs) {
  26853. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26854. }
  26855. if (this.uvs2) {
  26856. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26857. }
  26858. if (this.uvs3) {
  26859. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26860. }
  26861. if (this.uvs4) {
  26862. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26863. }
  26864. if (this.uvs5) {
  26865. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26866. }
  26867. if (this.uvs6) {
  26868. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26869. }
  26870. if (this.colors) {
  26871. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26872. }
  26873. if (this.matricesIndices) {
  26874. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26875. }
  26876. if (this.matricesWeights) {
  26877. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26878. }
  26879. if (this.matricesIndicesExtra) {
  26880. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26881. }
  26882. if (this.matricesWeightsExtra) {
  26883. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26884. }
  26885. if (this.indices) {
  26886. meshOrGeometry.setIndices(this.indices);
  26887. }
  26888. return this;
  26889. };
  26890. /**
  26891. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26892. * Returns the VertexData.
  26893. */
  26894. VertexData.prototype.transform = function (matrix) {
  26895. var transformed = BABYLON.Vector3.Zero();
  26896. var index;
  26897. if (this.positions) {
  26898. var position = BABYLON.Vector3.Zero();
  26899. for (index = 0; index < this.positions.length; index += 3) {
  26900. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26901. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26902. this.positions[index] = transformed.x;
  26903. this.positions[index + 1] = transformed.y;
  26904. this.positions[index + 2] = transformed.z;
  26905. }
  26906. }
  26907. if (this.normals) {
  26908. var normal = BABYLON.Vector3.Zero();
  26909. for (index = 0; index < this.normals.length; index += 3) {
  26910. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26911. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26912. this.normals[index] = transformed.x;
  26913. this.normals[index + 1] = transformed.y;
  26914. this.normals[index + 2] = transformed.z;
  26915. }
  26916. }
  26917. if (this.tangents) {
  26918. var tangent = BABYLON.Vector4.Zero();
  26919. var tangentTransformed = BABYLON.Vector4.Zero();
  26920. for (index = 0; index < this.tangents.length; index += 4) {
  26921. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26922. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26923. this.tangents[index] = tangentTransformed.x;
  26924. this.tangents[index + 1] = tangentTransformed.y;
  26925. this.tangents[index + 2] = tangentTransformed.z;
  26926. this.tangents[index + 3] = tangentTransformed.w;
  26927. }
  26928. }
  26929. return this;
  26930. };
  26931. /**
  26932. * Merges the passed VertexData into the current one.
  26933. * Returns the modified VertexData.
  26934. */
  26935. VertexData.prototype.merge = function (other) {
  26936. if (other.indices) {
  26937. if (!this.indices) {
  26938. this.indices = [];
  26939. }
  26940. var offset = this.positions ? this.positions.length / 3 : 0;
  26941. for (var index = 0; index < other.indices.length; index++) {
  26942. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26943. this.indices.push(other.indices[index] + offset);
  26944. }
  26945. }
  26946. this.positions = this._mergeElement(this.positions, other.positions);
  26947. this.normals = this._mergeElement(this.normals, other.normals);
  26948. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26949. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26950. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26951. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26952. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26953. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26954. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26955. this.colors = this._mergeElement(this.colors, other.colors);
  26956. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26957. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26958. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26959. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26960. return this;
  26961. };
  26962. VertexData.prototype._mergeElement = function (source, other) {
  26963. if (!other)
  26964. return source;
  26965. if (!source)
  26966. return other;
  26967. var len = other.length + source.length;
  26968. var isSrcTypedArray = source instanceof Float32Array;
  26969. var isOthTypedArray = other instanceof Float32Array;
  26970. // use non-loop method when the source is Float32Array
  26971. if (isSrcTypedArray) {
  26972. var ret32 = new Float32Array(len);
  26973. ret32.set(source);
  26974. ret32.set(other, source.length);
  26975. return ret32;
  26976. // source is number[], when other is also use concat
  26977. }
  26978. else if (!isOthTypedArray) {
  26979. return source.concat(other);
  26980. // source is a number[], but other is a Float32Array, loop required
  26981. }
  26982. else {
  26983. var ret = source.slice(0); // copy source to a separate array
  26984. for (var i = 0, len = other.length; i < len; i++) {
  26985. ret.push(other[i]);
  26986. }
  26987. return ret;
  26988. }
  26989. };
  26990. /**
  26991. * Serializes the VertexData.
  26992. * Returns a serialized object.
  26993. */
  26994. VertexData.prototype.serialize = function () {
  26995. var serializationObject = this.serialize();
  26996. if (this.positions) {
  26997. serializationObject.positions = this.positions;
  26998. }
  26999. if (this.normals) {
  27000. serializationObject.normals = this.normals;
  27001. }
  27002. if (this.tangents) {
  27003. serializationObject.tangents = this.tangents;
  27004. }
  27005. if (this.uvs) {
  27006. serializationObject.uvs = this.uvs;
  27007. }
  27008. if (this.uvs2) {
  27009. serializationObject.uvs2 = this.uvs2;
  27010. }
  27011. if (this.uvs3) {
  27012. serializationObject.uvs3 = this.uvs3;
  27013. }
  27014. if (this.uvs4) {
  27015. serializationObject.uvs4 = this.uvs4;
  27016. }
  27017. if (this.uvs5) {
  27018. serializationObject.uvs5 = this.uvs5;
  27019. }
  27020. if (this.uvs6) {
  27021. serializationObject.uvs6 = this.uvs6;
  27022. }
  27023. if (this.colors) {
  27024. serializationObject.colors = this.colors;
  27025. }
  27026. if (this.matricesIndices) {
  27027. serializationObject.matricesIndices = this.matricesIndices;
  27028. serializationObject.matricesIndices._isExpanded = true;
  27029. }
  27030. if (this.matricesWeights) {
  27031. serializationObject.matricesWeights = this.matricesWeights;
  27032. }
  27033. if (this.matricesIndicesExtra) {
  27034. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27035. serializationObject.matricesIndicesExtra._isExpanded = true;
  27036. }
  27037. if (this.matricesWeightsExtra) {
  27038. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27039. }
  27040. serializationObject.indices = this.indices;
  27041. return serializationObject;
  27042. };
  27043. // Statics
  27044. /**
  27045. * Returns the object VertexData associated to the passed mesh.
  27046. */
  27047. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  27048. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  27049. };
  27050. /**
  27051. * Returns the object VertexData associated to the passed geometry.
  27052. */
  27053. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  27054. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  27055. };
  27056. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  27057. var result = new VertexData();
  27058. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27059. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  27060. }
  27061. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27062. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  27063. }
  27064. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27065. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  27066. }
  27067. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27068. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  27069. }
  27070. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27071. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  27072. }
  27073. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27074. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  27075. }
  27076. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27077. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  27078. }
  27079. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27080. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  27081. }
  27082. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27083. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  27084. }
  27085. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27086. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  27087. }
  27088. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27089. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  27090. }
  27091. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27092. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  27093. }
  27094. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27095. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  27096. }
  27097. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27098. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  27099. }
  27100. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27101. return result;
  27102. };
  27103. /**
  27104. * Creates the vertexData of the Ribbon.
  27105. */
  27106. VertexData.CreateRibbon = function (options) {
  27107. var pathArray = options.pathArray;
  27108. var closeArray = options.closeArray || false;
  27109. var closePath = options.closePath || false;
  27110. var invertUV = options.invertUV || false;
  27111. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27112. var offset = options.offset || defaultOffset;
  27113. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27114. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27115. var customUV = options.uvs;
  27116. var customColors = options.colors;
  27117. var positions = [];
  27118. var indices = [];
  27119. var normals = [];
  27120. var uvs = [];
  27121. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27122. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27123. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27124. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27125. var minlg; // minimal length among all paths from pathArray
  27126. var lg = []; // array of path lengths : nb of vertex per path
  27127. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27128. var p; // path iterator
  27129. var i; // point iterator
  27130. var j; // point iterator
  27131. // if single path in pathArray
  27132. if (pathArray.length < 2) {
  27133. var ar1 = [];
  27134. var ar2 = [];
  27135. for (i = 0; i < pathArray[0].length - offset; i++) {
  27136. ar1.push(pathArray[0][i]);
  27137. ar2.push(pathArray[0][i + offset]);
  27138. }
  27139. pathArray = [ar1, ar2];
  27140. }
  27141. // positions and horizontal distances (u)
  27142. var idc = 0;
  27143. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  27144. var path;
  27145. var l;
  27146. minlg = pathArray[0].length;
  27147. var vectlg;
  27148. var dist;
  27149. for (p = 0; p < pathArray.length; p++) {
  27150. uTotalDistance[p] = 0;
  27151. us[p] = [0];
  27152. path = pathArray[p];
  27153. l = path.length;
  27154. minlg = (minlg < l) ? minlg : l;
  27155. j = 0;
  27156. while (j < l) {
  27157. positions.push(path[j].x, path[j].y, path[j].z);
  27158. if (j > 0) {
  27159. vectlg = path[j].subtract(path[j - 1]).length();
  27160. dist = vectlg + uTotalDistance[p];
  27161. us[p].push(dist);
  27162. uTotalDistance[p] = dist;
  27163. }
  27164. j++;
  27165. }
  27166. if (closePath) {
  27167. j--;
  27168. positions.push(path[0].x, path[0].y, path[0].z);
  27169. vectlg = path[j].subtract(path[0]).length();
  27170. dist = vectlg + uTotalDistance[p];
  27171. us[p].push(dist);
  27172. uTotalDistance[p] = dist;
  27173. }
  27174. lg[p] = l + closePathCorr;
  27175. idx[p] = idc;
  27176. idc += (l + closePathCorr);
  27177. }
  27178. // vertical distances (v)
  27179. var path1;
  27180. var path2;
  27181. var vertex1;
  27182. var vertex2;
  27183. for (i = 0; i < minlg + closePathCorr; i++) {
  27184. vTotalDistance[i] = 0;
  27185. vs[i] = [0];
  27186. for (p = 0; p < pathArray.length - 1; p++) {
  27187. path1 = pathArray[p];
  27188. path2 = pathArray[p + 1];
  27189. if (i === minlg) {
  27190. vertex1 = path1[0];
  27191. vertex2 = path2[0];
  27192. }
  27193. else {
  27194. vertex1 = path1[i];
  27195. vertex2 = path2[i];
  27196. }
  27197. vectlg = vertex2.subtract(vertex1).length();
  27198. dist = vectlg + vTotalDistance[i];
  27199. vs[i].push(dist);
  27200. vTotalDistance[i] = dist;
  27201. }
  27202. if (closeArray) {
  27203. path1 = pathArray[p];
  27204. path2 = pathArray[0];
  27205. if (i === minlg) {
  27206. vertex2 = path2[0];
  27207. }
  27208. vectlg = vertex2.subtract(vertex1).length();
  27209. dist = vectlg + vTotalDistance[i];
  27210. vTotalDistance[i] = dist;
  27211. }
  27212. }
  27213. // uvs
  27214. var u;
  27215. var v;
  27216. if (customUV) {
  27217. for (p = 0; p < customUV.length; p++) {
  27218. uvs.push(customUV[p].x, customUV[p].y);
  27219. }
  27220. }
  27221. else {
  27222. for (p = 0; p < pathArray.length; p++) {
  27223. for (i = 0; i < minlg + closePathCorr; i++) {
  27224. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  27225. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  27226. if (invertUV) {
  27227. uvs.push(v, u);
  27228. }
  27229. else {
  27230. uvs.push(u, v);
  27231. }
  27232. }
  27233. }
  27234. }
  27235. // indices
  27236. p = 0; // path index
  27237. var pi = 0; // positions array index
  27238. var l1 = lg[p] - 1; // path1 length
  27239. var l2 = lg[p + 1] - 1; // path2 length
  27240. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27241. var shft = idx[1] - idx[0]; // shift
  27242. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27243. while (pi <= min && p < path1nb) {
  27244. // 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
  27245. indices.push(pi, pi + shft, pi + 1);
  27246. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27247. pi += 1;
  27248. if (pi === min) {
  27249. p++;
  27250. if (p === lg.length - 1) {
  27251. shft = idx[0] - idx[p];
  27252. l1 = lg[p] - 1;
  27253. l2 = lg[0] - 1;
  27254. }
  27255. else {
  27256. shft = idx[p + 1] - idx[p];
  27257. l1 = lg[p] - 1;
  27258. l2 = lg[p + 1] - 1;
  27259. }
  27260. pi = idx[p];
  27261. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27262. }
  27263. }
  27264. // normals
  27265. VertexData.ComputeNormals(positions, indices, normals);
  27266. if (closePath) {
  27267. var indexFirst = 0;
  27268. var indexLast = 0;
  27269. for (p = 0; p < pathArray.length; p++) {
  27270. indexFirst = idx[p] * 3;
  27271. if (p + 1 < pathArray.length) {
  27272. indexLast = (idx[p + 1] - 1) * 3;
  27273. }
  27274. else {
  27275. indexLast = normals.length - 3;
  27276. }
  27277. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27278. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27279. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27280. normals[indexLast] = normals[indexFirst];
  27281. normals[indexLast + 1] = normals[indexFirst + 1];
  27282. normals[indexLast + 2] = normals[indexFirst + 2];
  27283. }
  27284. }
  27285. // sides
  27286. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27287. // Colors
  27288. if (customColors) {
  27289. var colors = new Float32Array(customColors.length * 4);
  27290. for (var c = 0; c < customColors.length; c++) {
  27291. colors[c * 4] = customColors[c].r;
  27292. colors[c * 4 + 1] = customColors[c].g;
  27293. colors[c * 4 + 2] = customColors[c].b;
  27294. colors[c * 4 + 3] = customColors[c].a;
  27295. }
  27296. }
  27297. // Result
  27298. var vertexData = new VertexData();
  27299. var positions32 = new Float32Array(positions);
  27300. var normals32 = new Float32Array(normals);
  27301. var uvs32 = new Float32Array(uvs);
  27302. vertexData.indices = indices;
  27303. vertexData.positions = positions32;
  27304. vertexData.normals = normals32;
  27305. vertexData.uvs = uvs32;
  27306. if (customColors) {
  27307. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27308. }
  27309. if (closePath) {
  27310. vertexData._idx = idx;
  27311. }
  27312. return vertexData;
  27313. };
  27314. /**
  27315. * Creates the VertexData of the Box.
  27316. */
  27317. VertexData.CreateBox = function (options) {
  27318. var normalsSource = [
  27319. new BABYLON.Vector3(0, 0, 1),
  27320. new BABYLON.Vector3(0, 0, -1),
  27321. new BABYLON.Vector3(1, 0, 0),
  27322. new BABYLON.Vector3(-1, 0, 0),
  27323. new BABYLON.Vector3(0, 1, 0),
  27324. new BABYLON.Vector3(0, -1, 0)
  27325. ];
  27326. var indices = [];
  27327. var positions = [];
  27328. var normals = [];
  27329. var uvs = [];
  27330. var width = options.width || options.size || 1;
  27331. var height = options.height || options.size || 1;
  27332. var depth = options.depth || options.size || 1;
  27333. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27334. var faceUV = options.faceUV || new Array(6);
  27335. var faceColors = options.faceColors;
  27336. var colors = [];
  27337. // default face colors and UV if undefined
  27338. for (var f = 0; f < 6; f++) {
  27339. if (faceUV[f] === undefined) {
  27340. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27341. }
  27342. if (faceColors && faceColors[f] === undefined) {
  27343. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27344. }
  27345. }
  27346. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27347. // Create each face in turn.
  27348. for (var index = 0; index < normalsSource.length; index++) {
  27349. var normal = normalsSource[index];
  27350. // Get two vectors perpendicular to the face normal and to each other.
  27351. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27352. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27353. // Six indices (two triangles) per face.
  27354. var verticesLength = positions.length / 3;
  27355. indices.push(verticesLength);
  27356. indices.push(verticesLength + 1);
  27357. indices.push(verticesLength + 2);
  27358. indices.push(verticesLength);
  27359. indices.push(verticesLength + 2);
  27360. indices.push(verticesLength + 3);
  27361. // Four vertices per face.
  27362. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27363. positions.push(vertex.x, vertex.y, vertex.z);
  27364. normals.push(normal.x, normal.y, normal.z);
  27365. uvs.push(faceUV[index].z, faceUV[index].w);
  27366. if (faceColors) {
  27367. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27368. }
  27369. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27370. positions.push(vertex.x, vertex.y, vertex.z);
  27371. normals.push(normal.x, normal.y, normal.z);
  27372. uvs.push(faceUV[index].x, faceUV[index].w);
  27373. if (faceColors) {
  27374. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27375. }
  27376. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27377. positions.push(vertex.x, vertex.y, vertex.z);
  27378. normals.push(normal.x, normal.y, normal.z);
  27379. uvs.push(faceUV[index].x, faceUV[index].y);
  27380. if (faceColors) {
  27381. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27382. }
  27383. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27384. positions.push(vertex.x, vertex.y, vertex.z);
  27385. normals.push(normal.x, normal.y, normal.z);
  27386. uvs.push(faceUV[index].z, faceUV[index].y);
  27387. if (faceColors) {
  27388. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27389. }
  27390. }
  27391. // sides
  27392. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27393. // Result
  27394. var vertexData = new VertexData();
  27395. vertexData.indices = indices;
  27396. vertexData.positions = positions;
  27397. vertexData.normals = normals;
  27398. vertexData.uvs = uvs;
  27399. if (faceColors) {
  27400. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27401. vertexData.colors = totalColors;
  27402. }
  27403. return vertexData;
  27404. };
  27405. /**
  27406. * Creates the VertexData of the Sphere.
  27407. */
  27408. VertexData.CreateSphere = function (options) {
  27409. var segments = options.segments || 32;
  27410. var diameterX = options.diameterX || options.diameter || 1;
  27411. var diameterY = options.diameterY || options.diameter || 1;
  27412. var diameterZ = options.diameterZ || options.diameter || 1;
  27413. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27414. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27415. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27416. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27417. var totalZRotationSteps = 2 + segments;
  27418. var totalYRotationSteps = 2 * totalZRotationSteps;
  27419. var indices = [];
  27420. var positions = [];
  27421. var normals = [];
  27422. var uvs = [];
  27423. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27424. var normalizedZ = zRotationStep / totalZRotationSteps;
  27425. var angleZ = normalizedZ * Math.PI * slice;
  27426. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27427. var normalizedY = yRotationStep / totalYRotationSteps;
  27428. var angleY = normalizedY * Math.PI * 2 * arc;
  27429. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27430. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27431. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27432. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27433. var vertex = complete.multiply(radius);
  27434. var normal = complete.divide(radius).normalize();
  27435. positions.push(vertex.x, vertex.y, vertex.z);
  27436. normals.push(normal.x, normal.y, normal.z);
  27437. uvs.push(normalizedY, normalizedZ);
  27438. }
  27439. if (zRotationStep > 0) {
  27440. var verticesCount = positions.length / 3;
  27441. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27442. indices.push((firstIndex));
  27443. indices.push((firstIndex + 1));
  27444. indices.push(firstIndex + totalYRotationSteps + 1);
  27445. indices.push((firstIndex + totalYRotationSteps + 1));
  27446. indices.push((firstIndex + 1));
  27447. indices.push((firstIndex + totalYRotationSteps + 2));
  27448. }
  27449. }
  27450. }
  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 Cylinder or Cone.
  27463. */
  27464. VertexData.CreateCylinder = function (options) {
  27465. var height = options.height || 2;
  27466. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27467. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27468. var tessellation = options.tessellation || 24;
  27469. var subdivisions = options.subdivisions || 1;
  27470. var hasRings = options.hasRings;
  27471. var enclose = options.enclose;
  27472. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27473. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27474. var faceUV = options.faceUV || new Array(3);
  27475. var faceColors = options.faceColors;
  27476. // default face colors and UV if undefined
  27477. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27478. var ringNb = (hasRings) ? subdivisions : 1;
  27479. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27480. var f;
  27481. for (f = 0; f < surfaceNb; f++) {
  27482. if (faceColors && faceColors[f] === undefined) {
  27483. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27484. }
  27485. }
  27486. for (f = 0; f < surfaceNb; f++) {
  27487. if (faceUV && faceUV[f] === undefined) {
  27488. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27489. }
  27490. }
  27491. var indices = [];
  27492. var positions = [];
  27493. var normals = [];
  27494. var uvs = [];
  27495. var colors = [];
  27496. var angle_step = Math.PI * 2 * arc / tessellation;
  27497. var angle;
  27498. var h;
  27499. var radius;
  27500. var tan = (diameterBottom - diameterTop) / 2 / height;
  27501. var ringVertex = BABYLON.Vector3.Zero();
  27502. var ringNormal = BABYLON.Vector3.Zero();
  27503. var ringFirstVertex = BABYLON.Vector3.Zero();
  27504. var ringFirstNormal = BABYLON.Vector3.Zero();
  27505. var quadNormal = BABYLON.Vector3.Zero();
  27506. var Y = BABYLON.Axis.Y;
  27507. // positions, normals, uvs
  27508. var i;
  27509. var j;
  27510. var r;
  27511. var ringIdx = 1;
  27512. var s = 1; // surface index
  27513. var cs = 0;
  27514. var v = 0;
  27515. for (i = 0; i <= subdivisions; i++) {
  27516. h = i / subdivisions;
  27517. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27518. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27519. for (r = 0; r < ringIdx; r++) {
  27520. if (hasRings) {
  27521. s += r;
  27522. }
  27523. if (enclose) {
  27524. s += 2 * r;
  27525. }
  27526. for (j = 0; j <= tessellation; j++) {
  27527. angle = j * angle_step;
  27528. // position
  27529. ringVertex.x = Math.cos(-angle) * radius;
  27530. ringVertex.y = -height / 2 + h * height;
  27531. ringVertex.z = Math.sin(-angle) * radius;
  27532. // normal
  27533. if (diameterTop === 0 && i === subdivisions) {
  27534. // if no top cap, reuse former normals
  27535. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27536. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27537. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27538. }
  27539. else {
  27540. ringNormal.x = ringVertex.x;
  27541. ringNormal.z = ringVertex.z;
  27542. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27543. ringNormal.normalize();
  27544. }
  27545. // keep first ring vertex values for enclose
  27546. if (j === 0) {
  27547. ringFirstVertex.copyFrom(ringVertex);
  27548. ringFirstNormal.copyFrom(ringNormal);
  27549. }
  27550. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27551. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27552. if (hasRings) {
  27553. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27554. }
  27555. else {
  27556. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27557. }
  27558. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27559. if (faceColors) {
  27560. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27561. }
  27562. }
  27563. // if enclose, add four vertices and their dedicated normals
  27564. if (arc !== 1 && enclose) {
  27565. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27566. positions.push(0, ringVertex.y, 0);
  27567. positions.push(0, ringVertex.y, 0);
  27568. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27569. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27570. quadNormal.normalize();
  27571. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27572. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27573. quadNormal.normalize();
  27574. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27575. if (hasRings) {
  27576. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27577. }
  27578. else {
  27579. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27580. }
  27581. uvs.push(faceUV[s + 1].x, v);
  27582. uvs.push(faceUV[s + 1].z, v);
  27583. if (hasRings) {
  27584. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27585. }
  27586. else {
  27587. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27588. }
  27589. uvs.push(faceUV[s + 2].x, v);
  27590. uvs.push(faceUV[s + 2].z, v);
  27591. if (faceColors) {
  27592. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27593. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27594. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27595. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27596. }
  27597. }
  27598. if (cs !== s) {
  27599. cs = s;
  27600. }
  27601. }
  27602. }
  27603. // indices
  27604. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27605. var s;
  27606. i = 0;
  27607. for (s = 0; s < subdivisions; s++) {
  27608. for (j = 0; j < tessellation; j++) {
  27609. var i0 = i * (e + 1) + j;
  27610. var i1 = (i + 1) * (e + 1) + j;
  27611. var i2 = i * (e + 1) + (j + 1);
  27612. var i3 = (i + 1) * (e + 1) + (j + 1);
  27613. indices.push(i0, i1, i2);
  27614. indices.push(i3, i2, i1);
  27615. }
  27616. if (arc !== 1 && enclose) {
  27617. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27618. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27619. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27620. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27621. }
  27622. i = (hasRings) ? (i + 2) : (i + 1);
  27623. }
  27624. // Caps
  27625. var createCylinderCap = function (isTop) {
  27626. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27627. if (radius === 0) {
  27628. return;
  27629. }
  27630. // Cap positions, normals & uvs
  27631. var angle;
  27632. var circleVector;
  27633. var i;
  27634. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27635. var c;
  27636. if (faceColors) {
  27637. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27638. }
  27639. // cap center
  27640. var vbase = positions.length / 3;
  27641. var offset = isTop ? height / 2 : -height / 2;
  27642. var center = new BABYLON.Vector3(0, offset, 0);
  27643. positions.push(center.x, center.y, center.z);
  27644. normals.push(0, isTop ? 1 : -1, 0);
  27645. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27646. if (faceColors) {
  27647. colors.push(c.r, c.g, c.b, c.a);
  27648. }
  27649. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27650. for (i = 0; i <= tessellation; i++) {
  27651. angle = Math.PI * 2 * i * arc / tessellation;
  27652. var cos = Math.cos(-angle);
  27653. var sin = Math.sin(-angle);
  27654. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27655. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27656. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27657. normals.push(0, isTop ? 1 : -1, 0);
  27658. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27659. if (faceColors) {
  27660. colors.push(c.r, c.g, c.b, c.a);
  27661. }
  27662. }
  27663. // Cap indices
  27664. for (i = 0; i < tessellation; i++) {
  27665. if (!isTop) {
  27666. indices.push(vbase);
  27667. indices.push(vbase + (i + 1));
  27668. indices.push(vbase + (i + 2));
  27669. }
  27670. else {
  27671. indices.push(vbase);
  27672. indices.push(vbase + (i + 2));
  27673. indices.push(vbase + (i + 1));
  27674. }
  27675. }
  27676. };
  27677. // add caps to geometry
  27678. createCylinderCap(false);
  27679. createCylinderCap(true);
  27680. // Sides
  27681. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27682. var vertexData = new VertexData();
  27683. vertexData.indices = indices;
  27684. vertexData.positions = positions;
  27685. vertexData.normals = normals;
  27686. vertexData.uvs = uvs;
  27687. if (faceColors) {
  27688. vertexData.colors = colors;
  27689. }
  27690. return vertexData;
  27691. };
  27692. /**
  27693. * Creates the VertexData of the Torus.
  27694. */
  27695. VertexData.CreateTorus = function (options) {
  27696. var indices = [];
  27697. var positions = [];
  27698. var normals = [];
  27699. var uvs = [];
  27700. var diameter = options.diameter || 1;
  27701. var thickness = options.thickness || 0.5;
  27702. var tessellation = options.tessellation || 16;
  27703. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27704. var stride = tessellation + 1;
  27705. for (var i = 0; i <= tessellation; i++) {
  27706. var u = i / tessellation;
  27707. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27708. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27709. for (var j = 0; j <= tessellation; j++) {
  27710. var v = 1 - j / tessellation;
  27711. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27712. var dx = Math.cos(innerAngle);
  27713. var dy = Math.sin(innerAngle);
  27714. // Create a vertex.
  27715. var normal = new BABYLON.Vector3(dx, dy, 0);
  27716. var position = normal.scale(thickness / 2);
  27717. var textureCoordinate = new BABYLON.Vector2(u, v);
  27718. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27719. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27720. positions.push(position.x, position.y, position.z);
  27721. normals.push(normal.x, normal.y, normal.z);
  27722. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27723. // And create indices for two triangles.
  27724. var nextI = (i + 1) % stride;
  27725. var nextJ = (j + 1) % stride;
  27726. indices.push(i * stride + j);
  27727. indices.push(i * stride + nextJ);
  27728. indices.push(nextI * stride + j);
  27729. indices.push(i * stride + nextJ);
  27730. indices.push(nextI * stride + nextJ);
  27731. indices.push(nextI * stride + j);
  27732. }
  27733. }
  27734. // Sides
  27735. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27736. // Result
  27737. var vertexData = new VertexData();
  27738. vertexData.indices = indices;
  27739. vertexData.positions = positions;
  27740. vertexData.normals = normals;
  27741. vertexData.uvs = uvs;
  27742. return vertexData;
  27743. };
  27744. /**
  27745. * Creates the VertexData of the LineSystem.
  27746. */
  27747. VertexData.CreateLineSystem = function (options) {
  27748. var indices = [];
  27749. var positions = [];
  27750. var lines = options.lines;
  27751. var idx = 0;
  27752. for (var l = 0; l < lines.length; l++) {
  27753. var points = lines[l];
  27754. for (var index = 0; index < points.length; index++) {
  27755. positions.push(points[index].x, points[index].y, points[index].z);
  27756. if (index > 0) {
  27757. indices.push(idx - 1);
  27758. indices.push(idx);
  27759. }
  27760. idx++;
  27761. }
  27762. }
  27763. var vertexData = new VertexData();
  27764. vertexData.indices = indices;
  27765. vertexData.positions = positions;
  27766. return vertexData;
  27767. };
  27768. /**
  27769. * Create the VertexData of the DashedLines.
  27770. */
  27771. VertexData.CreateDashedLines = function (options) {
  27772. var dashSize = options.dashSize || 3;
  27773. var gapSize = options.gapSize || 1;
  27774. var dashNb = options.dashNb || 200;
  27775. var points = options.points;
  27776. var positions = new Array();
  27777. var indices = new Array();
  27778. var curvect = BABYLON.Vector3.Zero();
  27779. var lg = 0;
  27780. var nb = 0;
  27781. var shft = 0;
  27782. var dashshft = 0;
  27783. var curshft = 0;
  27784. var idx = 0;
  27785. var i = 0;
  27786. for (i = 0; i < points.length - 1; i++) {
  27787. points[i + 1].subtractToRef(points[i], curvect);
  27788. lg += curvect.length();
  27789. }
  27790. shft = lg / dashNb;
  27791. dashshft = dashSize * shft / (dashSize + gapSize);
  27792. for (i = 0; i < points.length - 1; i++) {
  27793. points[i + 1].subtractToRef(points[i], curvect);
  27794. nb = Math.floor(curvect.length() / shft);
  27795. curvect.normalize();
  27796. for (var j = 0; j < nb; j++) {
  27797. curshft = shft * j;
  27798. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27799. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27800. indices.push(idx, idx + 1);
  27801. idx += 2;
  27802. }
  27803. }
  27804. // Result
  27805. var vertexData = new VertexData();
  27806. vertexData.positions = positions;
  27807. vertexData.indices = indices;
  27808. return vertexData;
  27809. };
  27810. /**
  27811. * Creates the VertexData of the Ground.
  27812. */
  27813. VertexData.CreateGround = function (options) {
  27814. var indices = [];
  27815. var positions = [];
  27816. var normals = [];
  27817. var uvs = [];
  27818. var row, col;
  27819. var width = options.width || 1;
  27820. var height = options.height || 1;
  27821. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27822. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27823. for (row = 0; row <= subdivisionsY; row++) {
  27824. for (col = 0; col <= subdivisionsX; col++) {
  27825. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27826. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27827. positions.push(position.x, position.y, position.z);
  27828. normals.push(normal.x, normal.y, normal.z);
  27829. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27830. }
  27831. }
  27832. for (row = 0; row < subdivisionsY; row++) {
  27833. for (col = 0; col < subdivisionsX; col++) {
  27834. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27835. indices.push(col + 1 + row * (subdivisionsX + 1));
  27836. indices.push(col + row * (subdivisionsX + 1));
  27837. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27838. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27839. indices.push(col + row * (subdivisionsX + 1));
  27840. }
  27841. }
  27842. // Result
  27843. var vertexData = new VertexData();
  27844. vertexData.indices = indices;
  27845. vertexData.positions = positions;
  27846. vertexData.normals = normals;
  27847. vertexData.uvs = uvs;
  27848. return vertexData;
  27849. };
  27850. /**
  27851. * Creates the VertexData of the TiledGround.
  27852. */
  27853. VertexData.CreateTiledGround = function (options) {
  27854. var xmin = options.xmin || -1.0;
  27855. var zmin = options.zmin || -1.0;
  27856. var xmax = options.xmax || 1.0;
  27857. var zmax = options.zmax || 1.0;
  27858. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27859. var precision = options.precision || { w: 1, h: 1 };
  27860. var indices = [];
  27861. var positions = [];
  27862. var normals = [];
  27863. var uvs = [];
  27864. var row, col, tileRow, tileCol;
  27865. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27866. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27867. precision.w = (precision.w < 1) ? 1 : precision.w;
  27868. precision.h = (precision.h < 1) ? 1 : precision.h;
  27869. var tileSize = {
  27870. 'w': (xmax - xmin) / subdivisions.w,
  27871. 'h': (zmax - zmin) / subdivisions.h
  27872. };
  27873. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27874. // Indices
  27875. var base = positions.length / 3;
  27876. var rowLength = precision.w + 1;
  27877. for (row = 0; row < precision.h; row++) {
  27878. for (col = 0; col < precision.w; col++) {
  27879. var square = [
  27880. base + col + row * rowLength,
  27881. base + (col + 1) + row * rowLength,
  27882. base + (col + 1) + (row + 1) * rowLength,
  27883. base + col + (row + 1) * rowLength
  27884. ];
  27885. indices.push(square[1]);
  27886. indices.push(square[2]);
  27887. indices.push(square[3]);
  27888. indices.push(square[0]);
  27889. indices.push(square[1]);
  27890. indices.push(square[3]);
  27891. }
  27892. }
  27893. // Position, normals and uvs
  27894. var position = BABYLON.Vector3.Zero();
  27895. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27896. for (row = 0; row <= precision.h; row++) {
  27897. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27898. for (col = 0; col <= precision.w; col++) {
  27899. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27900. position.y = 0;
  27901. positions.push(position.x, position.y, position.z);
  27902. normals.push(normal.x, normal.y, normal.z);
  27903. uvs.push(col / precision.w, row / precision.h);
  27904. }
  27905. }
  27906. }
  27907. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27908. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27909. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27910. }
  27911. }
  27912. // Result
  27913. var vertexData = new VertexData();
  27914. vertexData.indices = indices;
  27915. vertexData.positions = positions;
  27916. vertexData.normals = normals;
  27917. vertexData.uvs = uvs;
  27918. return vertexData;
  27919. };
  27920. /**
  27921. * Creates the VertexData of the Ground designed from a heightmap.
  27922. */
  27923. VertexData.CreateGroundFromHeightMap = function (options) {
  27924. var indices = [];
  27925. var positions = [];
  27926. var normals = [];
  27927. var uvs = [];
  27928. var row, col;
  27929. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27930. // Vertices
  27931. for (row = 0; row <= options.subdivisions; row++) {
  27932. for (col = 0; col <= options.subdivisions; col++) {
  27933. 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));
  27934. // Compute height
  27935. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27936. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27937. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27938. var r = options.buffer[pos] / 255.0;
  27939. var g = options.buffer[pos + 1] / 255.0;
  27940. var b = options.buffer[pos + 2] / 255.0;
  27941. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27942. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27943. // Add vertex
  27944. positions.push(position.x, position.y, position.z);
  27945. normals.push(0, 0, 0);
  27946. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27947. }
  27948. }
  27949. // Indices
  27950. for (row = 0; row < options.subdivisions; row++) {
  27951. for (col = 0; col < options.subdivisions; col++) {
  27952. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27953. indices.push(col + 1 + row * (options.subdivisions + 1));
  27954. indices.push(col + row * (options.subdivisions + 1));
  27955. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27956. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27957. indices.push(col + row * (options.subdivisions + 1));
  27958. }
  27959. }
  27960. // Normals
  27961. VertexData.ComputeNormals(positions, indices, normals);
  27962. // Result
  27963. var vertexData = new VertexData();
  27964. vertexData.indices = indices;
  27965. vertexData.positions = positions;
  27966. vertexData.normals = normals;
  27967. vertexData.uvs = uvs;
  27968. return vertexData;
  27969. };
  27970. /**
  27971. * Creates the VertexData of the Plane.
  27972. */
  27973. VertexData.CreatePlane = function (options) {
  27974. var indices = [];
  27975. var positions = [];
  27976. var normals = [];
  27977. var uvs = [];
  27978. var width = options.width || options.size || 1;
  27979. var height = options.height || options.size || 1;
  27980. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27981. // Vertices
  27982. var halfWidth = width / 2.0;
  27983. var halfHeight = height / 2.0;
  27984. positions.push(-halfWidth, -halfHeight, 0);
  27985. normals.push(0, 0, -1.0);
  27986. uvs.push(0.0, 0.0);
  27987. positions.push(halfWidth, -halfHeight, 0);
  27988. normals.push(0, 0, -1.0);
  27989. uvs.push(1.0, 0.0);
  27990. positions.push(halfWidth, halfHeight, 0);
  27991. normals.push(0, 0, -1.0);
  27992. uvs.push(1.0, 1.0);
  27993. positions.push(-halfWidth, halfHeight, 0);
  27994. normals.push(0, 0, -1.0);
  27995. uvs.push(0.0, 1.0);
  27996. // Indices
  27997. indices.push(0);
  27998. indices.push(1);
  27999. indices.push(2);
  28000. indices.push(0);
  28001. indices.push(2);
  28002. indices.push(3);
  28003. // Sides
  28004. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28005. // Result
  28006. var vertexData = new VertexData();
  28007. vertexData.indices = indices;
  28008. vertexData.positions = positions;
  28009. vertexData.normals = normals;
  28010. vertexData.uvs = uvs;
  28011. return vertexData;
  28012. };
  28013. /**
  28014. * Creates the VertexData of the Disc or regular Polygon.
  28015. */
  28016. VertexData.CreateDisc = function (options) {
  28017. var positions = [];
  28018. var indices = [];
  28019. var normals = [];
  28020. var uvs = [];
  28021. var radius = options.radius || 0.5;
  28022. var tessellation = options.tessellation || 64;
  28023. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28024. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28025. // positions and uvs
  28026. positions.push(0, 0, 0); // disc center first
  28027. uvs.push(0.5, 0.5);
  28028. var theta = Math.PI * 2 * arc;
  28029. var step = theta / tessellation;
  28030. for (var a = 0; a < theta; a += step) {
  28031. var x = Math.cos(a);
  28032. var y = Math.sin(a);
  28033. var u = (x + 1) / 2;
  28034. var v = (1 - y) / 2;
  28035. positions.push(radius * x, radius * y, 0);
  28036. uvs.push(u, v);
  28037. }
  28038. if (arc === 1) {
  28039. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28040. uvs.push(uvs[2], uvs[3]);
  28041. }
  28042. //indices
  28043. var vertexNb = positions.length / 3;
  28044. for (var i = 1; i < vertexNb - 1; i++) {
  28045. indices.push(i + 1, 0, i);
  28046. }
  28047. // result
  28048. VertexData.ComputeNormals(positions, indices, normals);
  28049. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28050. var vertexData = new VertexData();
  28051. vertexData.indices = indices;
  28052. vertexData.positions = positions;
  28053. vertexData.normals = normals;
  28054. vertexData.uvs = uvs;
  28055. return vertexData;
  28056. };
  28057. /**
  28058. * Re-creates the VertexData of the Polygon for sideOrientation.
  28059. */
  28060. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  28061. var faceUV = fUV || new Array(3);
  28062. var faceColors = fColors;
  28063. var colors = [];
  28064. // default face colors and UV if undefined
  28065. for (var f = 0; f < 3; f++) {
  28066. if (faceUV[f] === undefined) {
  28067. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28068. }
  28069. if (faceColors && faceColors[f] === undefined) {
  28070. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28071. }
  28072. }
  28073. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28074. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28075. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28076. var indices = polygon.getIndices();
  28077. // set face colours and textures
  28078. var idx = 0;
  28079. var face = 0;
  28080. for (var index = 0; index < normals.length; index += 3) {
  28081. //Edge Face no. 1
  28082. if (Math.abs(normals[index + 1]) < 0.001) {
  28083. face = 1;
  28084. }
  28085. //Top Face no. 0
  28086. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  28087. face = 0;
  28088. }
  28089. //Bottom Face no. 2
  28090. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  28091. face = 2;
  28092. }
  28093. idx = index / 3;
  28094. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  28095. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  28096. if (faceColors) {
  28097. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  28098. }
  28099. }
  28100. // sides
  28101. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  28102. // Result
  28103. var vertexData = new VertexData();
  28104. vertexData.indices = indices;
  28105. vertexData.positions = positions;
  28106. vertexData.normals = normals;
  28107. vertexData.uvs = uvs;
  28108. if (faceColors) {
  28109. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28110. vertexData.colors = totalColors;
  28111. }
  28112. return vertexData;
  28113. };
  28114. /**
  28115. * Creates the VertexData of the IcoSphere.
  28116. */
  28117. VertexData.CreateIcoSphere = function (options) {
  28118. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28119. var radius = options.radius || 1;
  28120. var flat = (options.flat === undefined) ? true : options.flat;
  28121. var subdivisions = options.subdivisions || 4;
  28122. var radiusX = options.radiusX || radius;
  28123. var radiusY = options.radiusY || radius;
  28124. var radiusZ = options.radiusZ || radius;
  28125. var t = (1 + Math.sqrt(5)) / 2;
  28126. // 12 vertex x,y,z
  28127. var ico_vertices = [
  28128. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28129. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28130. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28131. ];
  28132. // index of 3 vertex makes a face of icopshere
  28133. var ico_indices = [
  28134. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28135. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28136. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28137. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28138. ];
  28139. // vertex for uv have aliased position, not for UV
  28140. var vertices_unalias_id = [
  28141. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28142. // vertex alias
  28143. 0,
  28144. 2,
  28145. 3,
  28146. 3,
  28147. 3,
  28148. 4,
  28149. 7,
  28150. 8,
  28151. 9,
  28152. 9,
  28153. 10,
  28154. 11 // 23: B + 12
  28155. ];
  28156. // uv as integer step (not pixels !)
  28157. var ico_vertexuv = [
  28158. 5, 1, 3, 1, 6, 4, 0, 0,
  28159. 5, 3, 4, 2, 2, 2, 4, 0,
  28160. 2, 0, 1, 1, 6, 0, 6, 2,
  28161. // vertex alias (for same vertex on different faces)
  28162. 0, 4,
  28163. 3, 3,
  28164. 4, 4,
  28165. 3, 1,
  28166. 4, 2,
  28167. 4, 4,
  28168. 0, 2,
  28169. 1, 1,
  28170. 2, 2,
  28171. 3, 3,
  28172. 1, 3,
  28173. 2, 4 // 23: B + 12
  28174. ];
  28175. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28176. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28177. // First island of uv mapping
  28178. // v = 4h 3+ 2
  28179. // v = 3h 9+ 4
  28180. // v = 2h 9+ 5 B
  28181. // v = 1h 9 1 0
  28182. // v = 0h 3 8 7 A
  28183. // u = 0 1 2 3 4 5 6 *a
  28184. // Second island of uv mapping
  28185. // v = 4h 0+ B+ 4+
  28186. // v = 3h A+ 2+
  28187. // v = 2h 7+ 6 3+
  28188. // v = 1h 8+ 3+
  28189. // v = 0h
  28190. // u = 0 1 2 3 4 5 6 *a
  28191. // Face layout on texture UV mapping
  28192. // ============
  28193. // \ 4 /\ 16 / ======
  28194. // \ / \ / /\ 11 /
  28195. // \/ 7 \/ / \ /
  28196. // ======= / 10 \/
  28197. // /\ 17 /\ =======
  28198. // / \ / \ \ 15 /\
  28199. // / 8 \/ 12 \ \ / \
  28200. // ============ \/ 6 \
  28201. // \ 18 /\ ============
  28202. // \ / \ \ 5 /\ 0 /
  28203. // \/ 13 \ \ / \ /
  28204. // ======= \/ 1 \/
  28205. // =============
  28206. // /\ 19 /\ 2 /\
  28207. // / \ / \ / \
  28208. // / 14 \/ 9 \/ 3 \
  28209. // ===================
  28210. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28211. var ustep = 138 / 1024;
  28212. var vstep = 239 / 1024;
  28213. var uoffset = 60 / 1024;
  28214. var voffset = 26 / 1024;
  28215. // Second island should have margin, not to touch the first island
  28216. // avoid any borderline artefact in pixel rounding
  28217. var island_u_offset = -40 / 1024;
  28218. var island_v_offset = +20 / 1024;
  28219. // face is either island 0 or 1 :
  28220. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28221. var island = [
  28222. 0, 0, 0, 0, 1,
  28223. 0, 0, 1, 1, 0,
  28224. 0, 0, 1, 1, 0,
  28225. 0, 1, 1, 1, 0 // 15 - 19
  28226. ];
  28227. var indices = [];
  28228. var positions = [];
  28229. var normals = [];
  28230. var uvs = [];
  28231. var current_indice = 0;
  28232. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28233. var face_vertex_pos = new Array(3);
  28234. var face_vertex_uv = new Array(3);
  28235. var v012;
  28236. for (v012 = 0; v012 < 3; v012++) {
  28237. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28238. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28239. }
  28240. // create all with normals
  28241. for (var face = 0; face < 20; face++) {
  28242. // 3 vertex per face
  28243. for (v012 = 0; v012 < 3; v012++) {
  28244. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28245. var v_id = ico_indices[3 * face + v012];
  28246. // vertex have 3D position (x,y,z)
  28247. 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]);
  28248. // Normalize to get normal, then scale to radius
  28249. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28250. // uv Coordinates from vertex ID
  28251. 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);
  28252. }
  28253. // Subdivide the face (interpolate pos, norm, uv)
  28254. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28255. // - norm is linear interpolation of vertex corner normal
  28256. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28257. // - uv is linear interpolation
  28258. //
  28259. // Topology is as below for sub-divide by 2
  28260. // vertex shown as v0,v1,v2
  28261. // interp index is i1 to progress in range [v0,v1[
  28262. // interp index is i2 to progress in range [v0,v2[
  28263. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28264. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28265. //
  28266. //
  28267. // i2 v2
  28268. // ^ ^
  28269. // / / \
  28270. // / / \
  28271. // / / \
  28272. // / / (0,1) \
  28273. // / #---------\
  28274. // / / \ (0,0)'/ \
  28275. // / / \ / \
  28276. // / / \ / \
  28277. // / / (0,0) \ / (1,0) \
  28278. // / #---------#---------\
  28279. // v0 v1
  28280. //
  28281. // --------------------> i1
  28282. //
  28283. // interp of (i1,i2):
  28284. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28285. // along i1 : lerp(x0,x1, i1/(S-i2))
  28286. //
  28287. // centroid of triangle is needed to get help normal computation
  28288. // (c1,c2) are used for centroid location
  28289. var interp_vertex = function (i1, i2, c1, c2) {
  28290. // vertex is interpolated from
  28291. // - face_vertex_pos[0..2]
  28292. // - face_vertex_uv[0..2]
  28293. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28294. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28295. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28296. pos_interp.normalize();
  28297. var vertex_normal;
  28298. if (flat) {
  28299. // in flat mode, recalculate normal as face centroid normal
  28300. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28301. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28302. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28303. }
  28304. else {
  28305. // in smooth mode, recalculate normal from each single vertex position
  28306. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28307. }
  28308. // Vertex normal need correction due to X,Y,Z radius scaling
  28309. vertex_normal.x /= radiusX;
  28310. vertex_normal.y /= radiusY;
  28311. vertex_normal.z /= radiusZ;
  28312. vertex_normal.normalize();
  28313. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28314. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28315. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28316. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28317. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28318. uvs.push(uv_interp.x, uv_interp.y);
  28319. // push each vertex has member of a face
  28320. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28321. indices.push(current_indice);
  28322. current_indice++;
  28323. };
  28324. for (var i2 = 0; i2 < subdivisions; i2++) {
  28325. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28326. // face : (i1,i2) for /\ :
  28327. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28328. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28329. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28330. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28331. if (i1 + i2 + 1 < subdivisions) {
  28332. // face : (i1,i2)' for \/ :
  28333. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28334. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28335. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28336. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28337. }
  28338. }
  28339. }
  28340. }
  28341. // Sides
  28342. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28343. // Result
  28344. var vertexData = new VertexData();
  28345. vertexData.indices = indices;
  28346. vertexData.positions = positions;
  28347. vertexData.normals = normals;
  28348. vertexData.uvs = uvs;
  28349. return vertexData;
  28350. };
  28351. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28352. /**
  28353. * Creates the VertexData of the Polyhedron.
  28354. */
  28355. VertexData.CreatePolyhedron = function (options) {
  28356. // provided polyhedron types :
  28357. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28358. // 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)
  28359. var polyhedra = [];
  28360. 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]] };
  28361. 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]] };
  28362. polyhedra[2] = {
  28363. 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]],
  28364. 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]]
  28365. };
  28366. polyhedra[3] = {
  28367. 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]],
  28368. 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]]
  28369. };
  28370. polyhedra[4] = {
  28371. 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]],
  28372. 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]]
  28373. };
  28374. 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]] };
  28375. 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]] };
  28376. 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]] };
  28377. 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]] };
  28378. 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]] };
  28379. 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]] };
  28380. 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]] };
  28381. 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]] };
  28382. 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]] };
  28383. polyhedra[14] = {
  28384. 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]],
  28385. 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]]
  28386. };
  28387. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28388. var size = options.size;
  28389. var sizeX = options.sizeX || size || 1;
  28390. var sizeY = options.sizeY || size || 1;
  28391. var sizeZ = options.sizeZ || size || 1;
  28392. var data = options.custom || polyhedra[type];
  28393. var nbfaces = data.face.length;
  28394. var faceUV = options.faceUV || new Array(nbfaces);
  28395. var faceColors = options.faceColors;
  28396. var flat = (options.flat === undefined) ? true : options.flat;
  28397. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28398. var positions = [];
  28399. var indices = [];
  28400. var normals = [];
  28401. var uvs = [];
  28402. var colors = [];
  28403. var index = 0;
  28404. var faceIdx = 0; // face cursor in the array "indexes"
  28405. var indexes = [];
  28406. var i = 0;
  28407. var f = 0;
  28408. var u, v, ang, x, y, tmp;
  28409. // default face colors and UV if undefined
  28410. if (flat) {
  28411. for (f = 0; f < nbfaces; f++) {
  28412. if (faceColors && faceColors[f] === undefined) {
  28413. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28414. }
  28415. if (faceUV && faceUV[f] === undefined) {
  28416. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28417. }
  28418. }
  28419. }
  28420. if (!flat) {
  28421. for (i = 0; i < data.vertex.length; i++) {
  28422. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28423. uvs.push(0, 0);
  28424. }
  28425. for (f = 0; f < nbfaces; f++) {
  28426. for (i = 0; i < data.face[f].length - 2; i++) {
  28427. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28428. }
  28429. }
  28430. }
  28431. else {
  28432. for (f = 0; f < nbfaces; f++) {
  28433. var fl = data.face[f].length; // number of vertices of the current face
  28434. ang = 2 * Math.PI / fl;
  28435. x = 0.5 * Math.tan(ang / 2);
  28436. y = 0.5;
  28437. // positions, uvs, colors
  28438. for (i = 0; i < fl; i++) {
  28439. // positions
  28440. 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);
  28441. indexes.push(index);
  28442. index++;
  28443. // uvs
  28444. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28445. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28446. uvs.push(u, v);
  28447. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28448. y = x * Math.sin(ang) + y * Math.cos(ang);
  28449. x = tmp;
  28450. // colors
  28451. if (faceColors) {
  28452. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28453. }
  28454. }
  28455. // indices from indexes
  28456. for (i = 0; i < fl - 2; i++) {
  28457. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28458. }
  28459. faceIdx += fl;
  28460. }
  28461. }
  28462. VertexData.ComputeNormals(positions, indices, normals);
  28463. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28464. var vertexData = new VertexData();
  28465. vertexData.positions = positions;
  28466. vertexData.indices = indices;
  28467. vertexData.normals = normals;
  28468. vertexData.uvs = uvs;
  28469. if (faceColors && flat) {
  28470. vertexData.colors = colors;
  28471. }
  28472. return vertexData;
  28473. };
  28474. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28475. /**
  28476. * Creates the VertexData of the Torus Knot.
  28477. */
  28478. VertexData.CreateTorusKnot = function (options) {
  28479. var indices = [];
  28480. var positions = [];
  28481. var normals = [];
  28482. var uvs = [];
  28483. var radius = options.radius || 2;
  28484. var tube = options.tube || 0.5;
  28485. var radialSegments = options.radialSegments || 32;
  28486. var tubularSegments = options.tubularSegments || 32;
  28487. var p = options.p || 2;
  28488. var q = options.q || 3;
  28489. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28490. // Helper
  28491. var getPos = function (angle) {
  28492. var cu = Math.cos(angle);
  28493. var su = Math.sin(angle);
  28494. var quOverP = q / p * angle;
  28495. var cs = Math.cos(quOverP);
  28496. var tx = radius * (2 + cs) * 0.5 * cu;
  28497. var ty = radius * (2 + cs) * su * 0.5;
  28498. var tz = radius * Math.sin(quOverP) * 0.5;
  28499. return new BABYLON.Vector3(tx, ty, tz);
  28500. };
  28501. // Vertices
  28502. var i;
  28503. var j;
  28504. for (i = 0; i <= radialSegments; i++) {
  28505. var modI = i % radialSegments;
  28506. var u = modI / radialSegments * 2 * p * Math.PI;
  28507. var p1 = getPos(u);
  28508. var p2 = getPos(u + 0.01);
  28509. var tang = p2.subtract(p1);
  28510. var n = p2.add(p1);
  28511. var bitan = BABYLON.Vector3.Cross(tang, n);
  28512. n = BABYLON.Vector3.Cross(bitan, tang);
  28513. bitan.normalize();
  28514. n.normalize();
  28515. for (j = 0; j < tubularSegments; j++) {
  28516. var modJ = j % tubularSegments;
  28517. var v = modJ / tubularSegments * 2 * Math.PI;
  28518. var cx = -tube * Math.cos(v);
  28519. var cy = tube * Math.sin(v);
  28520. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28521. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28522. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28523. uvs.push(i / radialSegments);
  28524. uvs.push(j / tubularSegments);
  28525. }
  28526. }
  28527. for (i = 0; i < radialSegments; i++) {
  28528. for (j = 0; j < tubularSegments; j++) {
  28529. var jNext = (j + 1) % tubularSegments;
  28530. var a = i * tubularSegments + j;
  28531. var b = (i + 1) * tubularSegments + j;
  28532. var c = (i + 1) * tubularSegments + jNext;
  28533. var d = i * tubularSegments + jNext;
  28534. indices.push(d);
  28535. indices.push(b);
  28536. indices.push(a);
  28537. indices.push(d);
  28538. indices.push(c);
  28539. indices.push(b);
  28540. }
  28541. }
  28542. // Normals
  28543. VertexData.ComputeNormals(positions, indices, normals);
  28544. // Sides
  28545. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28546. // Result
  28547. var vertexData = new VertexData();
  28548. vertexData.indices = indices;
  28549. vertexData.positions = positions;
  28550. vertexData.normals = normals;
  28551. vertexData.uvs = uvs;
  28552. return vertexData;
  28553. };
  28554. // Tools
  28555. /**
  28556. * @param {any} - positions (number[] or Float32Array)
  28557. * @param {any} - indices (number[] or Uint16Array)
  28558. * @param {any} - normals (number[] or Float32Array)
  28559. * options (optional) :
  28560. * facetPositions : optional array of facet positions (vector3)
  28561. * facetNormals : optional array of facet normals (vector3)
  28562. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28563. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28564. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28565. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28566. * bInfo : optional bounding info, required for facetPartitioning computation
  28567. */
  28568. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28569. // temporary scalar variables
  28570. var index = 0; // facet index
  28571. var p1p2x = 0.0; // p1p2 vector x coordinate
  28572. var p1p2y = 0.0; // p1p2 vector y coordinate
  28573. var p1p2z = 0.0; // p1p2 vector z coordinate
  28574. var p3p2x = 0.0; // p3p2 vector x coordinate
  28575. var p3p2y = 0.0; // p3p2 vector y coordinate
  28576. var p3p2z = 0.0; // p3p2 vector z coordinate
  28577. var faceNormalx = 0.0; // facet normal x coordinate
  28578. var faceNormaly = 0.0; // facet normal y coordinate
  28579. var faceNormalz = 0.0; // facet normal z coordinate
  28580. var length = 0.0; // facet normal length before normalization
  28581. var v1x = 0; // vector1 x index in the positions array
  28582. var v1y = 0; // vector1 y index in the positions array
  28583. var v1z = 0; // vector1 z index in the positions array
  28584. var v2x = 0; // vector2 x index in the positions array
  28585. var v2y = 0; // vector2 y index in the positions array
  28586. var v2z = 0; // vector2 z index in the positions array
  28587. var v3x = 0; // vector3 x index in the positions array
  28588. var v3y = 0; // vector3 y index in the positions array
  28589. var v3z = 0; // vector3 z index in the positions array
  28590. var computeFacetNormals = false;
  28591. var computeFacetPositions = false;
  28592. var computeFacetPartitioning = false;
  28593. var faceNormalSign = 1;
  28594. if (options) {
  28595. computeFacetNormals = (options.facetNormals) ? true : false;
  28596. computeFacetPositions = (options.facetPositions) ? true : false;
  28597. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28598. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28599. }
  28600. // facetPartitioning reinit if needed
  28601. if (computeFacetPartitioning) {
  28602. var ox = 0; // X partitioning index for facet position
  28603. var oy = 0; // Y partinioning index for facet position
  28604. var oz = 0; // Z partinioning index for facet position
  28605. var b1x = 0; // X partitioning index for facet v1 vertex
  28606. var b1y = 0; // Y partitioning index for facet v1 vertex
  28607. var b1z = 0; // z partitioning index for facet v1 vertex
  28608. var b2x = 0; // X partitioning index for facet v2 vertex
  28609. var b2y = 0; // Y partitioning index for facet v2 vertex
  28610. var b2z = 0; // Z partitioning index for facet v2 vertex
  28611. var b3x = 0; // X partitioning index for facet v3 vertex
  28612. var b3y = 0; // Y partitioning index for facet v3 vertex
  28613. var b3z = 0; // Z partitioning index for facet v3 vertex
  28614. var block_idx_o = 0; // facet barycenter block index
  28615. var block_idx_v1 = 0; // v1 vertex block index
  28616. var block_idx_v2 = 0; // v2 vertex block index
  28617. var block_idx_v3 = 0; // v3 vertex block index
  28618. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28619. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28620. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28621. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28622. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28623. var subSq = options.subDiv.max * options.subDiv.max;
  28624. options.facetPartitioning.length = 0;
  28625. }
  28626. // reset the normals
  28627. for (index = 0; index < positions.length; index++) {
  28628. normals[index] = 0.0;
  28629. }
  28630. // Loop : 1 indice triplet = 1 facet
  28631. var nbFaces = indices.length / 3;
  28632. for (index = 0; index < nbFaces; index++) {
  28633. // get the indexes of the coordinates of each vertex of the facet
  28634. v1x = indices[index * 3] * 3;
  28635. v1y = v1x + 1;
  28636. v1z = v1x + 2;
  28637. v2x = indices[index * 3 + 1] * 3;
  28638. v2y = v2x + 1;
  28639. v2z = v2x + 2;
  28640. v3x = indices[index * 3 + 2] * 3;
  28641. v3y = v3x + 1;
  28642. v3z = v3x + 2;
  28643. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28644. p1p2y = positions[v1y] - positions[v2y];
  28645. p1p2z = positions[v1z] - positions[v2z];
  28646. p3p2x = positions[v3x] - positions[v2x];
  28647. p3p2y = positions[v3y] - positions[v2y];
  28648. p3p2z = positions[v3z] - positions[v2z];
  28649. // compute the face normal with the cross product
  28650. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28651. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28652. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28653. // normalize this normal and store it in the array facetData
  28654. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28655. length = (length === 0) ? 1.0 : length;
  28656. faceNormalx /= length;
  28657. faceNormaly /= length;
  28658. faceNormalz /= length;
  28659. if (computeFacetNormals) {
  28660. options.facetNormals[index].x = faceNormalx;
  28661. options.facetNormals[index].y = faceNormaly;
  28662. options.facetNormals[index].z = faceNormalz;
  28663. }
  28664. if (computeFacetPositions) {
  28665. // compute and the facet barycenter coordinates in the array facetPositions
  28666. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28667. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28668. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28669. }
  28670. if (computeFacetPartitioning) {
  28671. // store the facet indexes in arrays in the main facetPartitioning array :
  28672. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28673. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28674. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28675. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28676. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28677. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28678. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28679. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28680. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28681. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28682. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28683. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28684. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28685. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28686. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28687. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28688. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28689. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28690. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28691. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28692. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28693. // push each facet index in each block containing the vertex
  28694. options.facetPartitioning[block_idx_v1].push(index);
  28695. if (block_idx_v2 != block_idx_v1) {
  28696. options.facetPartitioning[block_idx_v2].push(index);
  28697. }
  28698. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28699. options.facetPartitioning[block_idx_v3].push(index);
  28700. }
  28701. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28702. options.facetPartitioning[block_idx_o].push(index);
  28703. }
  28704. }
  28705. // compute the normals anyway
  28706. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28707. normals[v1y] += faceNormaly;
  28708. normals[v1z] += faceNormalz;
  28709. normals[v2x] += faceNormalx;
  28710. normals[v2y] += faceNormaly;
  28711. normals[v2z] += faceNormalz;
  28712. normals[v3x] += faceNormalx;
  28713. normals[v3y] += faceNormaly;
  28714. normals[v3z] += faceNormalz;
  28715. }
  28716. // last normalization of each normal
  28717. for (index = 0; index < normals.length / 3; index++) {
  28718. faceNormalx = normals[index * 3];
  28719. faceNormaly = normals[index * 3 + 1];
  28720. faceNormalz = normals[index * 3 + 2];
  28721. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28722. length = (length === 0) ? 1.0 : length;
  28723. faceNormalx /= length;
  28724. faceNormaly /= length;
  28725. faceNormalz /= length;
  28726. normals[index * 3] = faceNormalx;
  28727. normals[index * 3 + 1] = faceNormaly;
  28728. normals[index * 3 + 2] = faceNormalz;
  28729. }
  28730. };
  28731. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28732. var li = indices.length;
  28733. var ln = normals.length;
  28734. var i;
  28735. var n;
  28736. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28737. switch (sideOrientation) {
  28738. case BABYLON.Mesh.FRONTSIDE:
  28739. // nothing changed
  28740. break;
  28741. case BABYLON.Mesh.BACKSIDE:
  28742. var tmp;
  28743. // indices
  28744. for (i = 0; i < li; i += 3) {
  28745. tmp = indices[i];
  28746. indices[i] = indices[i + 2];
  28747. indices[i + 2] = tmp;
  28748. }
  28749. // normals
  28750. for (n = 0; n < ln; n++) {
  28751. normals[n] = -normals[n];
  28752. }
  28753. break;
  28754. case BABYLON.Mesh.DOUBLESIDE:
  28755. // positions
  28756. var lp = positions.length;
  28757. var l = lp / 3;
  28758. for (var p = 0; p < lp; p++) {
  28759. positions[lp + p] = positions[p];
  28760. }
  28761. // indices
  28762. for (i = 0; i < li; i += 3) {
  28763. indices[i + li] = indices[i + 2] + l;
  28764. indices[i + 1 + li] = indices[i + 1] + l;
  28765. indices[i + 2 + li] = indices[i] + l;
  28766. }
  28767. // normals
  28768. for (n = 0; n < ln; n++) {
  28769. normals[ln + n] = -normals[n];
  28770. }
  28771. // uvs
  28772. var lu = uvs.length;
  28773. var u = 0;
  28774. for (u = 0; u < lu; u++) {
  28775. uvs[u + lu] = uvs[u];
  28776. }
  28777. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28778. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28779. u = 0;
  28780. for (i = 0; i < lu / 2; i++) {
  28781. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28782. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28783. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28784. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28785. u += 2;
  28786. }
  28787. break;
  28788. }
  28789. };
  28790. /**
  28791. * Creates a new VertexData from the imported parameters.
  28792. */
  28793. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28794. var vertexData = new VertexData();
  28795. // positions
  28796. var positions = parsedVertexData.positions;
  28797. if (positions) {
  28798. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28799. }
  28800. // normals
  28801. var normals = parsedVertexData.normals;
  28802. if (normals) {
  28803. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28804. }
  28805. // tangents
  28806. var tangents = parsedVertexData.tangents;
  28807. if (tangents) {
  28808. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28809. }
  28810. // uvs
  28811. var uvs = parsedVertexData.uvs;
  28812. if (uvs) {
  28813. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28814. }
  28815. // uv2s
  28816. var uv2s = parsedVertexData.uv2s;
  28817. if (uv2s) {
  28818. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28819. }
  28820. // uv3s
  28821. var uv3s = parsedVertexData.uv3s;
  28822. if (uv3s) {
  28823. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28824. }
  28825. // uv4s
  28826. var uv4s = parsedVertexData.uv4s;
  28827. if (uv4s) {
  28828. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28829. }
  28830. // uv5s
  28831. var uv5s = parsedVertexData.uv5s;
  28832. if (uv5s) {
  28833. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28834. }
  28835. // uv6s
  28836. var uv6s = parsedVertexData.uv6s;
  28837. if (uv6s) {
  28838. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28839. }
  28840. // colors
  28841. var colors = parsedVertexData.colors;
  28842. if (colors) {
  28843. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28844. }
  28845. // matricesIndices
  28846. var matricesIndices = parsedVertexData.matricesIndices;
  28847. if (matricesIndices) {
  28848. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28849. }
  28850. // matricesWeights
  28851. var matricesWeights = parsedVertexData.matricesWeights;
  28852. if (matricesWeights) {
  28853. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28854. }
  28855. // indices
  28856. var indices = parsedVertexData.indices;
  28857. if (indices) {
  28858. vertexData.indices = indices;
  28859. }
  28860. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28861. };
  28862. return VertexData;
  28863. }());
  28864. BABYLON.VertexData = VertexData;
  28865. })(BABYLON || (BABYLON = {}));
  28866. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28867. var BABYLON;
  28868. (function (BABYLON) {
  28869. var Geometry = (function () {
  28870. function Geometry(id, scene, vertexData, updatable, mesh) {
  28871. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28872. this._totalVertices = 0;
  28873. this._isDisposed = false;
  28874. this.id = id;
  28875. this._engine = scene.getEngine();
  28876. this._meshes = [];
  28877. this._scene = scene;
  28878. //Init vertex buffer cache
  28879. this._vertexBuffers = {};
  28880. this._indices = [];
  28881. this._updatable = updatable;
  28882. // vertexData
  28883. if (vertexData) {
  28884. this.setAllVerticesData(vertexData, updatable);
  28885. }
  28886. else {
  28887. this._totalVertices = 0;
  28888. this._indices = [];
  28889. }
  28890. if (this._engine.getCaps().vertexArrayObject) {
  28891. this._vertexArrayObjects = {};
  28892. }
  28893. // applyToMesh
  28894. if (mesh) {
  28895. if (mesh.getClassName() === "LinesMesh") {
  28896. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28897. this.updateExtend();
  28898. }
  28899. this.applyToMesh(mesh);
  28900. mesh.computeWorldMatrix(true);
  28901. }
  28902. }
  28903. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28904. /**
  28905. * 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
  28906. * @returns The Bias Vector
  28907. */
  28908. get: function () {
  28909. return this._boundingBias;
  28910. },
  28911. set: function (value) {
  28912. if (this._boundingBias && this._boundingBias.equals(value)) {
  28913. return;
  28914. }
  28915. this._boundingBias = value.clone();
  28916. this.updateBoundingInfo(true, null);
  28917. },
  28918. enumerable: true,
  28919. configurable: true
  28920. });
  28921. Object.defineProperty(Geometry.prototype, "extend", {
  28922. get: function () {
  28923. return this._extend;
  28924. },
  28925. enumerable: true,
  28926. configurable: true
  28927. });
  28928. Geometry.prototype.getScene = function () {
  28929. return this._scene;
  28930. };
  28931. Geometry.prototype.getEngine = function () {
  28932. return this._engine;
  28933. };
  28934. Geometry.prototype.isReady = function () {
  28935. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28936. };
  28937. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28938. get: function () {
  28939. for (var index = 0; index < this._meshes.length; index++) {
  28940. if (!this._meshes[index].doNotSerialize) {
  28941. return false;
  28942. }
  28943. }
  28944. return true;
  28945. },
  28946. enumerable: true,
  28947. configurable: true
  28948. });
  28949. Geometry.prototype._rebuild = function () {
  28950. if (this._vertexArrayObjects) {
  28951. this._vertexArrayObjects = {};
  28952. }
  28953. // Index buffer
  28954. if (this._meshes.length !== 0 && this._indices) {
  28955. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28956. }
  28957. // Vertex buffers
  28958. for (var key in this._vertexBuffers) {
  28959. var vertexBuffer = this._vertexBuffers[key];
  28960. vertexBuffer._rebuild();
  28961. }
  28962. };
  28963. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28964. vertexData.applyToGeometry(this, updatable);
  28965. this.notifyUpdate();
  28966. };
  28967. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28968. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28969. this.setVerticesBuffer(buffer);
  28970. };
  28971. Geometry.prototype.removeVerticesData = function (kind) {
  28972. if (this._vertexBuffers[kind]) {
  28973. this._vertexBuffers[kind].dispose();
  28974. delete this._vertexBuffers[kind];
  28975. }
  28976. };
  28977. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28978. var kind = buffer.getKind();
  28979. if (this._vertexBuffers[kind]) {
  28980. this._vertexBuffers[kind].dispose();
  28981. }
  28982. this._vertexBuffers[kind] = buffer;
  28983. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28984. var data = buffer.getData();
  28985. var stride = buffer.getStrideSize();
  28986. this._totalVertices = data.length / stride;
  28987. this.updateExtend(data, stride);
  28988. this._resetPointsArrayCache();
  28989. var meshes = this._meshes;
  28990. var numOfMeshes = meshes.length;
  28991. for (var index = 0; index < numOfMeshes; index++) {
  28992. var mesh = meshes[index];
  28993. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28994. mesh._createGlobalSubMesh(false);
  28995. mesh.computeWorldMatrix(true);
  28996. }
  28997. }
  28998. this.notifyUpdate(kind);
  28999. if (this._vertexArrayObjects) {
  29000. this._disposeVertexArrayObjects();
  29001. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  29002. }
  29003. };
  29004. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29005. var vertexBuffer = this.getVertexBuffer(kind);
  29006. if (!vertexBuffer) {
  29007. return;
  29008. }
  29009. vertexBuffer.updateDirectly(data, offset);
  29010. this.notifyUpdate(kind);
  29011. };
  29012. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29013. var vertexBuffer = this.getVertexBuffer(kind);
  29014. if (!vertexBuffer) {
  29015. return;
  29016. }
  29017. vertexBuffer.update(data);
  29018. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29019. var stride = vertexBuffer.getStrideSize();
  29020. this._totalVertices = data.length / stride;
  29021. this.updateBoundingInfo(updateExtends, data);
  29022. }
  29023. this.notifyUpdate(kind);
  29024. };
  29025. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  29026. if (updateExtends) {
  29027. this.updateExtend(data);
  29028. }
  29029. var meshes = this._meshes;
  29030. var numOfMeshes = meshes.length;
  29031. this._resetPointsArrayCache();
  29032. for (var index = 0; index < numOfMeshes; index++) {
  29033. var mesh = meshes[index];
  29034. if (updateExtends) {
  29035. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29036. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29037. var subMesh = mesh.subMeshes[subIndex];
  29038. subMesh.refreshBoundingInfo();
  29039. }
  29040. }
  29041. }
  29042. };
  29043. Geometry.prototype._bind = function (effect, indexToBind) {
  29044. if (indexToBind === void 0) { indexToBind = undefined; }
  29045. if (indexToBind === undefined) {
  29046. indexToBind = this._indexBuffer;
  29047. }
  29048. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  29049. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  29050. return;
  29051. }
  29052. // Using VAO
  29053. if (!this._vertexArrayObjects[effect.key]) {
  29054. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  29055. }
  29056. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  29057. };
  29058. Geometry.prototype.getTotalVertices = function () {
  29059. if (!this.isReady()) {
  29060. return 0;
  29061. }
  29062. return this._totalVertices;
  29063. };
  29064. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  29065. var vertexBuffer = this.getVertexBuffer(kind);
  29066. if (!vertexBuffer) {
  29067. return null;
  29068. }
  29069. var orig = vertexBuffer.getData();
  29070. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  29071. return orig;
  29072. }
  29073. else {
  29074. var len = orig.length;
  29075. var copy = [];
  29076. for (var i = 0; i < len; i++) {
  29077. copy.push(orig[i]);
  29078. }
  29079. return copy;
  29080. }
  29081. };
  29082. Geometry.prototype.getVertexBuffer = function (kind) {
  29083. if (!this.isReady()) {
  29084. return null;
  29085. }
  29086. return this._vertexBuffers[kind];
  29087. };
  29088. Geometry.prototype.getVertexBuffers = function () {
  29089. if (!this.isReady()) {
  29090. return null;
  29091. }
  29092. return this._vertexBuffers;
  29093. };
  29094. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29095. if (!this._vertexBuffers) {
  29096. if (this._delayInfo) {
  29097. return this._delayInfo.indexOf(kind) !== -1;
  29098. }
  29099. return false;
  29100. }
  29101. return this._vertexBuffers[kind] !== undefined;
  29102. };
  29103. Geometry.prototype.getVerticesDataKinds = function () {
  29104. var result = [];
  29105. var kind;
  29106. if (!this._vertexBuffers && this._delayInfo) {
  29107. for (kind in this._delayInfo) {
  29108. result.push(kind);
  29109. }
  29110. }
  29111. else {
  29112. for (kind in this._vertexBuffers) {
  29113. result.push(kind);
  29114. }
  29115. }
  29116. return result;
  29117. };
  29118. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29119. if (this._indexBuffer) {
  29120. this._engine._releaseBuffer(this._indexBuffer);
  29121. }
  29122. this._disposeVertexArrayObjects();
  29123. this._indices = indices;
  29124. if (this._meshes.length !== 0 && this._indices) {
  29125. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29126. }
  29127. if (totalVertices !== undefined) {
  29128. this._totalVertices = totalVertices;
  29129. }
  29130. var meshes = this._meshes;
  29131. var numOfMeshes = meshes.length;
  29132. for (var index = 0; index < numOfMeshes; index++) {
  29133. meshes[index]._createGlobalSubMesh(true);
  29134. }
  29135. this.notifyUpdate();
  29136. };
  29137. Geometry.prototype.getTotalIndices = function () {
  29138. if (!this.isReady()) {
  29139. return 0;
  29140. }
  29141. return this._indices.length;
  29142. };
  29143. Geometry.prototype.getIndices = function (copyWhenShared) {
  29144. if (!this.isReady()) {
  29145. return null;
  29146. }
  29147. var orig = this._indices;
  29148. if (!copyWhenShared || this._meshes.length === 1) {
  29149. return orig;
  29150. }
  29151. else {
  29152. var len = orig.length;
  29153. var copy = [];
  29154. for (var i = 0; i < len; i++) {
  29155. copy.push(orig[i]);
  29156. }
  29157. return copy;
  29158. }
  29159. };
  29160. Geometry.prototype.getIndexBuffer = function () {
  29161. if (!this.isReady()) {
  29162. return null;
  29163. }
  29164. return this._indexBuffer;
  29165. };
  29166. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  29167. if (!effect || !this._vertexArrayObjects) {
  29168. return;
  29169. }
  29170. if (this._vertexArrayObjects[effect.key]) {
  29171. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  29172. delete this._vertexArrayObjects[effect.key];
  29173. }
  29174. };
  29175. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29176. var meshes = this._meshes;
  29177. var index = meshes.indexOf(mesh);
  29178. if (index === -1) {
  29179. return;
  29180. }
  29181. meshes.splice(index, 1);
  29182. mesh._geometry = null;
  29183. if (meshes.length === 0 && shouldDispose) {
  29184. this.dispose();
  29185. }
  29186. };
  29187. Geometry.prototype.applyToMesh = function (mesh) {
  29188. if (mesh._geometry === this) {
  29189. return;
  29190. }
  29191. var previousGeometry = mesh._geometry;
  29192. if (previousGeometry) {
  29193. previousGeometry.releaseForMesh(mesh);
  29194. }
  29195. var meshes = this._meshes;
  29196. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29197. mesh._geometry = this;
  29198. this._scene.pushGeometry(this);
  29199. meshes.push(mesh);
  29200. if (this.isReady()) {
  29201. this._applyToMesh(mesh);
  29202. }
  29203. else {
  29204. mesh._boundingInfo = this._boundingInfo;
  29205. }
  29206. };
  29207. Geometry.prototype.updateExtend = function (data, stride) {
  29208. if (data === void 0) { data = null; }
  29209. if (!data) {
  29210. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  29211. }
  29212. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  29213. };
  29214. Geometry.prototype._applyToMesh = function (mesh) {
  29215. var numOfMeshes = this._meshes.length;
  29216. // vertexBuffers
  29217. for (var kind in this._vertexBuffers) {
  29218. if (numOfMeshes === 1) {
  29219. this._vertexBuffers[kind].create();
  29220. }
  29221. var buffer = this._vertexBuffers[kind].getBuffer();
  29222. if (buffer)
  29223. buffer.references = numOfMeshes;
  29224. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29225. if (!this._extend) {
  29226. this.updateExtend(this._vertexBuffers[kind].getData());
  29227. }
  29228. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29229. mesh._createGlobalSubMesh(false);
  29230. //bounding info was just created again, world matrix should be applied again.
  29231. mesh._updateBoundingInfo();
  29232. }
  29233. }
  29234. // indexBuffer
  29235. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  29236. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29237. }
  29238. if (this._indexBuffer) {
  29239. this._indexBuffer.references = numOfMeshes;
  29240. }
  29241. };
  29242. Geometry.prototype.notifyUpdate = function (kind) {
  29243. if (this.onGeometryUpdated) {
  29244. this.onGeometryUpdated(this, kind);
  29245. }
  29246. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  29247. var mesh = _a[_i];
  29248. mesh._markSubMeshesAsAttributesDirty();
  29249. }
  29250. };
  29251. Geometry.prototype.load = function (scene, onLoaded) {
  29252. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29253. return;
  29254. }
  29255. if (this.isReady()) {
  29256. if (onLoaded) {
  29257. onLoaded();
  29258. }
  29259. return;
  29260. }
  29261. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29262. this._queueLoad(scene, onLoaded);
  29263. };
  29264. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  29265. var _this = this;
  29266. scene._addPendingData(this);
  29267. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29268. _this._delayLoadingFunction(JSON.parse(data), _this);
  29269. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29270. _this._delayInfo = [];
  29271. scene._removePendingData(_this);
  29272. var meshes = _this._meshes;
  29273. var numOfMeshes = meshes.length;
  29274. for (var index = 0; index < numOfMeshes; index++) {
  29275. _this._applyToMesh(meshes[index]);
  29276. }
  29277. if (onLoaded) {
  29278. onLoaded();
  29279. }
  29280. }, function () { }, scene.database);
  29281. };
  29282. /**
  29283. * Invert the geometry to move from a right handed system to a left handed one.
  29284. */
  29285. Geometry.prototype.toLeftHanded = function () {
  29286. // Flip faces
  29287. var tIndices = this.getIndices(false);
  29288. if (tIndices != null && tIndices.length > 0) {
  29289. for (var i = 0; i < tIndices.length; i += 3) {
  29290. var tTemp = tIndices[i + 0];
  29291. tIndices[i + 0] = tIndices[i + 2];
  29292. tIndices[i + 2] = tTemp;
  29293. }
  29294. this.setIndices(tIndices);
  29295. }
  29296. // Negate position.z
  29297. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29298. if (tPositions != null && tPositions.length > 0) {
  29299. for (var i = 0; i < tPositions.length; i += 3) {
  29300. tPositions[i + 2] = -tPositions[i + 2];
  29301. }
  29302. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29303. }
  29304. // Negate normal.z
  29305. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29306. if (tNormals != null && tNormals.length > 0) {
  29307. for (var i = 0; i < tNormals.length; i += 3) {
  29308. tNormals[i + 2] = -tNormals[i + 2];
  29309. }
  29310. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29311. }
  29312. };
  29313. // Cache
  29314. Geometry.prototype._resetPointsArrayCache = function () {
  29315. this._positions = null;
  29316. };
  29317. Geometry.prototype._generatePointsArray = function () {
  29318. if (this._positions)
  29319. return true;
  29320. this._positions = [];
  29321. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29322. if (!data) {
  29323. return false;
  29324. }
  29325. for (var index = 0; index < data.length; index += 3) {
  29326. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29327. }
  29328. return true;
  29329. };
  29330. Geometry.prototype.isDisposed = function () {
  29331. return this._isDisposed;
  29332. };
  29333. Geometry.prototype._disposeVertexArrayObjects = function () {
  29334. if (this._vertexArrayObjects) {
  29335. for (var kind in this._vertexArrayObjects) {
  29336. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29337. }
  29338. this._vertexArrayObjects = {};
  29339. }
  29340. };
  29341. Geometry.prototype.dispose = function () {
  29342. var meshes = this._meshes;
  29343. var numOfMeshes = meshes.length;
  29344. var index;
  29345. for (index = 0; index < numOfMeshes; index++) {
  29346. this.releaseForMesh(meshes[index]);
  29347. }
  29348. this._meshes = [];
  29349. this._disposeVertexArrayObjects();
  29350. for (var kind in this._vertexBuffers) {
  29351. this._vertexBuffers[kind].dispose();
  29352. }
  29353. this._vertexBuffers = {};
  29354. this._totalVertices = 0;
  29355. if (this._indexBuffer) {
  29356. this._engine._releaseBuffer(this._indexBuffer);
  29357. }
  29358. this._indexBuffer = null;
  29359. this._indices = [];
  29360. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29361. this.delayLoadingFile = null;
  29362. this._delayLoadingFunction = null;
  29363. this._delayInfo = [];
  29364. this._boundingInfo = null;
  29365. this._scene.removeGeometry(this);
  29366. this._isDisposed = true;
  29367. };
  29368. Geometry.prototype.copy = function (id) {
  29369. var vertexData = new BABYLON.VertexData();
  29370. vertexData.indices = [];
  29371. var indices = this.getIndices();
  29372. for (var index = 0; index < indices.length; index++) {
  29373. vertexData.indices.push(indices[index]);
  29374. }
  29375. var updatable = false;
  29376. var stopChecking = false;
  29377. var kind;
  29378. for (kind in this._vertexBuffers) {
  29379. // using slice() to make a copy of the array and not just reference it
  29380. var data = this.getVerticesData(kind);
  29381. if (data instanceof Float32Array) {
  29382. vertexData.set(new Float32Array(data), kind);
  29383. }
  29384. else {
  29385. vertexData.set(data.slice(0), kind);
  29386. }
  29387. if (!stopChecking) {
  29388. updatable = this.getVertexBuffer(kind).isUpdatable();
  29389. stopChecking = !updatable;
  29390. }
  29391. }
  29392. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29393. geometry.delayLoadState = this.delayLoadState;
  29394. geometry.delayLoadingFile = this.delayLoadingFile;
  29395. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29396. for (kind in this._delayInfo) {
  29397. geometry._delayInfo = geometry._delayInfo || [];
  29398. geometry._delayInfo.push(kind);
  29399. }
  29400. // Bounding info
  29401. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29402. return geometry;
  29403. };
  29404. Geometry.prototype.serialize = function () {
  29405. var serializationObject = {};
  29406. serializationObject.id = this.id;
  29407. serializationObject.updatable = this._updatable;
  29408. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29409. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29410. }
  29411. return serializationObject;
  29412. };
  29413. Geometry.prototype.toNumberArray = function (origin) {
  29414. if (Array.isArray(origin)) {
  29415. return origin;
  29416. }
  29417. else {
  29418. return Array.prototype.slice.call(origin);
  29419. }
  29420. };
  29421. Geometry.prototype.serializeVerticeData = function () {
  29422. var serializationObject = this.serialize();
  29423. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29424. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29425. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29426. serializationObject.positions._updatable = true;
  29427. }
  29428. }
  29429. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29430. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29431. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29432. serializationObject.normals._updatable = true;
  29433. }
  29434. }
  29435. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29436. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29437. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29438. serializationObject.uvs._updatable = true;
  29439. }
  29440. }
  29441. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29442. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29443. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29444. serializationObject.uv2s._updatable = true;
  29445. }
  29446. }
  29447. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29448. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29449. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29450. serializationObject.uv3s._updatable = true;
  29451. }
  29452. }
  29453. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29454. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29455. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29456. serializationObject.uv4s._updatable = true;
  29457. }
  29458. }
  29459. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29460. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29461. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29462. serializationObject.uv5s._updatable = true;
  29463. }
  29464. }
  29465. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29466. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29467. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29468. serializationObject.uv6s._updatable = true;
  29469. }
  29470. }
  29471. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29472. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29473. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29474. serializationObject.colors._updatable = true;
  29475. }
  29476. }
  29477. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29478. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29479. serializationObject.matricesIndices._isExpanded = true;
  29480. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29481. serializationObject.matricesIndices._updatable = true;
  29482. }
  29483. }
  29484. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29485. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29486. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29487. serializationObject.matricesWeights._updatable = true;
  29488. }
  29489. }
  29490. serializationObject.indices = this.toNumberArray(this.getIndices());
  29491. return serializationObject;
  29492. };
  29493. // Statics
  29494. Geometry.ExtractFromMesh = function (mesh, id) {
  29495. var geometry = mesh._geometry;
  29496. if (!geometry) {
  29497. return null;
  29498. }
  29499. return geometry.copy(id);
  29500. };
  29501. /**
  29502. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29503. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29504. * Be aware Math.random() could cause collisions, but:
  29505. * "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"
  29506. */
  29507. Geometry.RandomId = function () {
  29508. return BABYLON.Tools.RandomId();
  29509. };
  29510. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29511. var scene = mesh.getScene();
  29512. // Geometry
  29513. var geometryId = parsedGeometry.geometryId;
  29514. if (geometryId) {
  29515. var geometry = scene.getGeometryByID(geometryId);
  29516. if (geometry) {
  29517. geometry.applyToMesh(mesh);
  29518. }
  29519. }
  29520. else if (parsedGeometry instanceof ArrayBuffer) {
  29521. var binaryInfo = mesh._binaryInfo;
  29522. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29523. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29524. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29525. }
  29526. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29527. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29528. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29529. }
  29530. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29531. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29532. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29533. }
  29534. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29535. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29536. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29537. }
  29538. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29539. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29540. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29541. }
  29542. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29543. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29544. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29545. }
  29546. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29547. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29548. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29549. }
  29550. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29551. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29552. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29553. }
  29554. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29555. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29556. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29557. }
  29558. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29559. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29560. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29561. }
  29562. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29563. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29564. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29565. }
  29566. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29567. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29568. mesh.setIndices(indicesData);
  29569. }
  29570. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29571. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29572. mesh.subMeshes = [];
  29573. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29574. var materialIndex = subMeshesData[(i * 5) + 0];
  29575. var verticesStart = subMeshesData[(i * 5) + 1];
  29576. var verticesCount = subMeshesData[(i * 5) + 2];
  29577. var indexStart = subMeshesData[(i * 5) + 3];
  29578. var indexCount = subMeshesData[(i * 5) + 4];
  29579. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29580. }
  29581. }
  29582. }
  29583. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29584. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29585. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29586. if (parsedGeometry.uvs) {
  29587. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29588. }
  29589. if (parsedGeometry.uvs2) {
  29590. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29591. }
  29592. if (parsedGeometry.uvs3) {
  29593. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29594. }
  29595. if (parsedGeometry.uvs4) {
  29596. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29597. }
  29598. if (parsedGeometry.uvs5) {
  29599. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29600. }
  29601. if (parsedGeometry.uvs6) {
  29602. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29603. }
  29604. if (parsedGeometry.colors) {
  29605. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29606. }
  29607. if (parsedGeometry.matricesIndices) {
  29608. if (!parsedGeometry.matricesIndices._isExpanded) {
  29609. var floatIndices = [];
  29610. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29611. var matricesIndex = parsedGeometry.matricesIndices[i];
  29612. floatIndices.push(matricesIndex & 0x000000FF);
  29613. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29614. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29615. floatIndices.push(matricesIndex >> 24);
  29616. }
  29617. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29618. }
  29619. else {
  29620. delete parsedGeometry.matricesIndices._isExpanded;
  29621. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29622. }
  29623. }
  29624. if (parsedGeometry.matricesIndicesExtra) {
  29625. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29626. var floatIndices = [];
  29627. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29628. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29629. floatIndices.push(matricesIndex & 0x000000FF);
  29630. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29631. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29632. floatIndices.push(matricesIndex >> 24);
  29633. }
  29634. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29635. }
  29636. else {
  29637. delete parsedGeometry.matricesIndices._isExpanded;
  29638. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29639. }
  29640. }
  29641. if (parsedGeometry.matricesWeights) {
  29642. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29643. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29644. }
  29645. if (parsedGeometry.matricesWeightsExtra) {
  29646. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29647. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29648. }
  29649. mesh.setIndices(parsedGeometry.indices);
  29650. }
  29651. // SubMeshes
  29652. if (parsedGeometry.subMeshes) {
  29653. mesh.subMeshes = [];
  29654. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29655. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29656. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29657. }
  29658. }
  29659. // Flat shading
  29660. if (mesh._shouldGenerateFlatShading) {
  29661. mesh.convertToFlatShadedMesh();
  29662. delete mesh._shouldGenerateFlatShading;
  29663. }
  29664. // Update
  29665. mesh.computeWorldMatrix(true);
  29666. // Octree
  29667. if (scene['_selectionOctree']) {
  29668. scene['_selectionOctree'].addMesh(mesh);
  29669. }
  29670. };
  29671. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29672. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29673. return;
  29674. }
  29675. var size = matricesWeights.length;
  29676. for (var i = 0; i < size; i += influencers) {
  29677. var weight = 0;
  29678. var biggerIndex = i;
  29679. var biggerWeight = 0;
  29680. for (var j = 0; j < influencers - 1; j++) {
  29681. weight += matricesWeights[i + j];
  29682. if (matricesWeights[i + j] > biggerWeight) {
  29683. biggerWeight = matricesWeights[i + j];
  29684. biggerIndex = i + j;
  29685. }
  29686. }
  29687. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29688. }
  29689. };
  29690. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29691. if (scene.getGeometryByID(parsedVertexData.id)) {
  29692. return null; // null since geometry could be something else than a box...
  29693. }
  29694. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29695. if (BABYLON.Tags) {
  29696. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29697. }
  29698. if (parsedVertexData.delayLoadingFile) {
  29699. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29700. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29701. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29702. geometry._delayInfo = [];
  29703. if (parsedVertexData.hasUVs) {
  29704. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29705. }
  29706. if (parsedVertexData.hasUVs2) {
  29707. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29708. }
  29709. if (parsedVertexData.hasUVs3) {
  29710. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29711. }
  29712. if (parsedVertexData.hasUVs4) {
  29713. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29714. }
  29715. if (parsedVertexData.hasUVs5) {
  29716. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29717. }
  29718. if (parsedVertexData.hasUVs6) {
  29719. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29720. }
  29721. if (parsedVertexData.hasColors) {
  29722. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29723. }
  29724. if (parsedVertexData.hasMatricesIndices) {
  29725. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29726. }
  29727. if (parsedVertexData.hasMatricesWeights) {
  29728. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29729. }
  29730. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29731. }
  29732. else {
  29733. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29734. }
  29735. scene.pushGeometry(geometry, true);
  29736. return geometry;
  29737. };
  29738. return Geometry;
  29739. }());
  29740. BABYLON.Geometry = Geometry;
  29741. /////// Primitives //////////////////////////////////////////////
  29742. (function (Geometry) {
  29743. var Primitives;
  29744. (function (Primitives) {
  29745. /// Abstract class
  29746. var _Primitive = (function (_super) {
  29747. __extends(_Primitive, _super);
  29748. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29749. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29750. _this._canBeRegenerated = _canBeRegenerated;
  29751. _this._beingRegenerated = true;
  29752. _this.regenerate();
  29753. _this._beingRegenerated = false;
  29754. return _this;
  29755. }
  29756. _Primitive.prototype.canBeRegenerated = function () {
  29757. return this._canBeRegenerated;
  29758. };
  29759. _Primitive.prototype.regenerate = function () {
  29760. if (!this._canBeRegenerated) {
  29761. return;
  29762. }
  29763. this._beingRegenerated = true;
  29764. this.setAllVerticesData(this._regenerateVertexData(), false);
  29765. this._beingRegenerated = false;
  29766. };
  29767. _Primitive.prototype.asNewGeometry = function (id) {
  29768. return _super.prototype.copy.call(this, id);
  29769. };
  29770. // overrides
  29771. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29772. if (!this._beingRegenerated) {
  29773. return;
  29774. }
  29775. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29776. };
  29777. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29778. if (!this._beingRegenerated) {
  29779. return;
  29780. }
  29781. _super.prototype.setVerticesData.call(this, kind, data, false);
  29782. };
  29783. // to override
  29784. // protected
  29785. _Primitive.prototype._regenerateVertexData = function () {
  29786. throw new Error("Abstract method");
  29787. };
  29788. _Primitive.prototype.copy = function (id) {
  29789. throw new Error("Must be overriden in sub-classes.");
  29790. };
  29791. _Primitive.prototype.serialize = function () {
  29792. var serializationObject = _super.prototype.serialize.call(this);
  29793. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29794. return serializationObject;
  29795. };
  29796. return _Primitive;
  29797. }(Geometry));
  29798. Primitives._Primitive = _Primitive;
  29799. var Ribbon = (function (_super) {
  29800. __extends(Ribbon, _super);
  29801. // Members
  29802. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29803. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29804. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29805. _this.pathArray = pathArray;
  29806. _this.closeArray = closeArray;
  29807. _this.closePath = closePath;
  29808. _this.offset = offset;
  29809. _this.side = side;
  29810. return _this;
  29811. }
  29812. Ribbon.prototype._regenerateVertexData = function () {
  29813. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29814. };
  29815. Ribbon.prototype.copy = function (id) {
  29816. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29817. };
  29818. return Ribbon;
  29819. }(_Primitive));
  29820. Primitives.Ribbon = Ribbon;
  29821. var Box = (function (_super) {
  29822. __extends(Box, _super);
  29823. // Members
  29824. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29825. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29826. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29827. _this.size = size;
  29828. _this.side = side;
  29829. return _this;
  29830. }
  29831. Box.prototype._regenerateVertexData = function () {
  29832. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29833. };
  29834. Box.prototype.copy = function (id) {
  29835. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29836. };
  29837. Box.prototype.serialize = function () {
  29838. var serializationObject = _super.prototype.serialize.call(this);
  29839. serializationObject.size = this.size;
  29840. return serializationObject;
  29841. };
  29842. Box.Parse = function (parsedBox, scene) {
  29843. if (scene.getGeometryByID(parsedBox.id)) {
  29844. return null; // null since geometry could be something else than a box...
  29845. }
  29846. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29847. if (BABYLON.Tags) {
  29848. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29849. }
  29850. scene.pushGeometry(box, true);
  29851. return box;
  29852. };
  29853. return Box;
  29854. }(_Primitive));
  29855. Primitives.Box = Box;
  29856. var Sphere = (function (_super) {
  29857. __extends(Sphere, _super);
  29858. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29859. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29860. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29861. _this.segments = segments;
  29862. _this.diameter = diameter;
  29863. _this.side = side;
  29864. return _this;
  29865. }
  29866. Sphere.prototype._regenerateVertexData = function () {
  29867. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29868. };
  29869. Sphere.prototype.copy = function (id) {
  29870. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29871. };
  29872. Sphere.prototype.serialize = function () {
  29873. var serializationObject = _super.prototype.serialize.call(this);
  29874. serializationObject.segments = this.segments;
  29875. serializationObject.diameter = this.diameter;
  29876. return serializationObject;
  29877. };
  29878. Sphere.Parse = function (parsedSphere, scene) {
  29879. if (scene.getGeometryByID(parsedSphere.id)) {
  29880. return null; // null since geometry could be something else than a sphere...
  29881. }
  29882. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29883. if (BABYLON.Tags) {
  29884. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29885. }
  29886. scene.pushGeometry(sphere, true);
  29887. return sphere;
  29888. };
  29889. return Sphere;
  29890. }(_Primitive));
  29891. Primitives.Sphere = Sphere;
  29892. var Disc = (function (_super) {
  29893. __extends(Disc, _super);
  29894. // Members
  29895. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29896. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29897. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29898. _this.radius = radius;
  29899. _this.tessellation = tessellation;
  29900. _this.side = side;
  29901. return _this;
  29902. }
  29903. Disc.prototype._regenerateVertexData = function () {
  29904. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29905. };
  29906. Disc.prototype.copy = function (id) {
  29907. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29908. };
  29909. return Disc;
  29910. }(_Primitive));
  29911. Primitives.Disc = Disc;
  29912. var Cylinder = (function (_super) {
  29913. __extends(Cylinder, _super);
  29914. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29915. if (subdivisions === void 0) { subdivisions = 1; }
  29916. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29917. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29918. _this.height = height;
  29919. _this.diameterTop = diameterTop;
  29920. _this.diameterBottom = diameterBottom;
  29921. _this.tessellation = tessellation;
  29922. _this.subdivisions = subdivisions;
  29923. _this.side = side;
  29924. return _this;
  29925. }
  29926. Cylinder.prototype._regenerateVertexData = function () {
  29927. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29928. };
  29929. Cylinder.prototype.copy = function (id) {
  29930. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29931. };
  29932. Cylinder.prototype.serialize = function () {
  29933. var serializationObject = _super.prototype.serialize.call(this);
  29934. serializationObject.height = this.height;
  29935. serializationObject.diameterTop = this.diameterTop;
  29936. serializationObject.diameterBottom = this.diameterBottom;
  29937. serializationObject.tessellation = this.tessellation;
  29938. return serializationObject;
  29939. };
  29940. Cylinder.Parse = function (parsedCylinder, scene) {
  29941. if (scene.getGeometryByID(parsedCylinder.id)) {
  29942. return null; // null since geometry could be something else than a cylinder...
  29943. }
  29944. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29945. if (BABYLON.Tags) {
  29946. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29947. }
  29948. scene.pushGeometry(cylinder, true);
  29949. return cylinder;
  29950. };
  29951. return Cylinder;
  29952. }(_Primitive));
  29953. Primitives.Cylinder = Cylinder;
  29954. var Torus = (function (_super) {
  29955. __extends(Torus, _super);
  29956. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29957. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29958. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29959. _this.diameter = diameter;
  29960. _this.thickness = thickness;
  29961. _this.tessellation = tessellation;
  29962. _this.side = side;
  29963. return _this;
  29964. }
  29965. Torus.prototype._regenerateVertexData = function () {
  29966. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29967. };
  29968. Torus.prototype.copy = function (id) {
  29969. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29970. };
  29971. Torus.prototype.serialize = function () {
  29972. var serializationObject = _super.prototype.serialize.call(this);
  29973. serializationObject.diameter = this.diameter;
  29974. serializationObject.thickness = this.thickness;
  29975. serializationObject.tessellation = this.tessellation;
  29976. return serializationObject;
  29977. };
  29978. Torus.Parse = function (parsedTorus, scene) {
  29979. if (scene.getGeometryByID(parsedTorus.id)) {
  29980. return null; // null since geometry could be something else than a torus...
  29981. }
  29982. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29983. if (BABYLON.Tags) {
  29984. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29985. }
  29986. scene.pushGeometry(torus, true);
  29987. return torus;
  29988. };
  29989. return Torus;
  29990. }(_Primitive));
  29991. Primitives.Torus = Torus;
  29992. var Ground = (function (_super) {
  29993. __extends(Ground, _super);
  29994. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29995. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29996. _this.width = width;
  29997. _this.height = height;
  29998. _this.subdivisions = subdivisions;
  29999. return _this;
  30000. }
  30001. Ground.prototype._regenerateVertexData = function () {
  30002. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  30003. };
  30004. Ground.prototype.copy = function (id) {
  30005. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  30006. };
  30007. Ground.prototype.serialize = function () {
  30008. var serializationObject = _super.prototype.serialize.call(this);
  30009. serializationObject.width = this.width;
  30010. serializationObject.height = this.height;
  30011. serializationObject.subdivisions = this.subdivisions;
  30012. return serializationObject;
  30013. };
  30014. Ground.Parse = function (parsedGround, scene) {
  30015. if (scene.getGeometryByID(parsedGround.id)) {
  30016. return null; // null since geometry could be something else than a ground...
  30017. }
  30018. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  30019. if (BABYLON.Tags) {
  30020. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  30021. }
  30022. scene.pushGeometry(ground, true);
  30023. return ground;
  30024. };
  30025. return Ground;
  30026. }(_Primitive));
  30027. Primitives.Ground = Ground;
  30028. var TiledGround = (function (_super) {
  30029. __extends(TiledGround, _super);
  30030. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  30031. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30032. _this.xmin = xmin;
  30033. _this.zmin = zmin;
  30034. _this.xmax = xmax;
  30035. _this.zmax = zmax;
  30036. _this.subdivisions = subdivisions;
  30037. _this.precision = precision;
  30038. return _this;
  30039. }
  30040. TiledGround.prototype._regenerateVertexData = function () {
  30041. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30042. };
  30043. TiledGround.prototype.copy = function (id) {
  30044. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30045. };
  30046. return TiledGround;
  30047. }(_Primitive));
  30048. Primitives.TiledGround = TiledGround;
  30049. var Plane = (function (_super) {
  30050. __extends(Plane, _super);
  30051. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30052. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30053. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30054. _this.size = size;
  30055. _this.side = side;
  30056. return _this;
  30057. }
  30058. Plane.prototype._regenerateVertexData = function () {
  30059. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30060. };
  30061. Plane.prototype.copy = function (id) {
  30062. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30063. };
  30064. Plane.prototype.serialize = function () {
  30065. var serializationObject = _super.prototype.serialize.call(this);
  30066. serializationObject.size = this.size;
  30067. return serializationObject;
  30068. };
  30069. Plane.Parse = function (parsedPlane, scene) {
  30070. if (scene.getGeometryByID(parsedPlane.id)) {
  30071. return null; // null since geometry could be something else than a ground...
  30072. }
  30073. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30074. if (BABYLON.Tags) {
  30075. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30076. }
  30077. scene.pushGeometry(plane, true);
  30078. return plane;
  30079. };
  30080. return Plane;
  30081. }(_Primitive));
  30082. Primitives.Plane = Plane;
  30083. var TorusKnot = (function (_super) {
  30084. __extends(TorusKnot, _super);
  30085. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30086. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30087. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30088. _this.radius = radius;
  30089. _this.tube = tube;
  30090. _this.radialSegments = radialSegments;
  30091. _this.tubularSegments = tubularSegments;
  30092. _this.p = p;
  30093. _this.q = q;
  30094. _this.side = side;
  30095. return _this;
  30096. }
  30097. TorusKnot.prototype._regenerateVertexData = function () {
  30098. 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 });
  30099. };
  30100. TorusKnot.prototype.copy = function (id) {
  30101. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30102. };
  30103. TorusKnot.prototype.serialize = function () {
  30104. var serializationObject = _super.prototype.serialize.call(this);
  30105. serializationObject.radius = this.radius;
  30106. serializationObject.tube = this.tube;
  30107. serializationObject.radialSegments = this.radialSegments;
  30108. serializationObject.tubularSegments = this.tubularSegments;
  30109. serializationObject.p = this.p;
  30110. serializationObject.q = this.q;
  30111. return serializationObject;
  30112. };
  30113. ;
  30114. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30115. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30116. return null; // null since geometry could be something else than a ground...
  30117. }
  30118. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30119. if (BABYLON.Tags) {
  30120. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30121. }
  30122. scene.pushGeometry(torusKnot, true);
  30123. return torusKnot;
  30124. };
  30125. return TorusKnot;
  30126. }(_Primitive));
  30127. Primitives.TorusKnot = TorusKnot;
  30128. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30129. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30130. })(BABYLON || (BABYLON = {}));
  30131. //# sourceMappingURL=babylon.geometry.js.map
  30132. var BABYLON;
  30133. (function (BABYLON) {
  30134. var PostProcessManager = (function () {
  30135. function PostProcessManager(scene) {
  30136. this._vertexBuffers = {};
  30137. this._scene = scene;
  30138. }
  30139. PostProcessManager.prototype._prepareBuffers = function () {
  30140. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30141. return;
  30142. }
  30143. // VBO
  30144. var vertices = [];
  30145. vertices.push(1, 1);
  30146. vertices.push(-1, 1);
  30147. vertices.push(-1, -1);
  30148. vertices.push(1, -1);
  30149. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30150. this._buildIndexBuffer();
  30151. };
  30152. PostProcessManager.prototype._buildIndexBuffer = function () {
  30153. // Indices
  30154. var indices = [];
  30155. indices.push(0);
  30156. indices.push(1);
  30157. indices.push(2);
  30158. indices.push(0);
  30159. indices.push(2);
  30160. indices.push(3);
  30161. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30162. };
  30163. PostProcessManager.prototype._rebuild = function () {
  30164. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30165. return;
  30166. }
  30167. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  30168. this._buildIndexBuffer();
  30169. };
  30170. // Methods
  30171. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  30172. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30173. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30174. return false;
  30175. }
  30176. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  30177. return true;
  30178. };
  30179. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  30180. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30181. var engine = this._scene.getEngine();
  30182. for (var index = 0; index < postProcesses.length; index++) {
  30183. if (index < postProcesses.length - 1) {
  30184. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30185. }
  30186. else {
  30187. if (targetTexture) {
  30188. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  30189. }
  30190. else {
  30191. engine.restoreDefaultFramebuffer();
  30192. }
  30193. }
  30194. var pp = postProcesses[index];
  30195. var effect = pp.apply();
  30196. if (effect) {
  30197. pp.onBeforeRenderObservable.notifyObservers(effect);
  30198. // VBOs
  30199. this._prepareBuffers();
  30200. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30201. // Draw order
  30202. engine.draw(true, 0, 6);
  30203. pp.onAfterRenderObservable.notifyObservers(effect);
  30204. }
  30205. }
  30206. // Restore depth buffer
  30207. engine.setDepthBuffer(true);
  30208. engine.setDepthWrite(true);
  30209. };
  30210. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  30211. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30212. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30213. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30214. return;
  30215. }
  30216. var engine = this._scene.getEngine();
  30217. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30218. if (index < len - 1) {
  30219. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30220. }
  30221. else {
  30222. if (targetTexture) {
  30223. engine.bindFramebuffer(targetTexture, faceIndex, null, null, forceFullscreenViewport);
  30224. }
  30225. else {
  30226. engine.restoreDefaultFramebuffer();
  30227. }
  30228. }
  30229. if (doNotPresent) {
  30230. break;
  30231. }
  30232. var pp = postProcesses[index];
  30233. var effect = pp.apply();
  30234. if (effect) {
  30235. pp.onBeforeRenderObservable.notifyObservers(effect);
  30236. // VBOs
  30237. this._prepareBuffers();
  30238. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30239. // Draw order
  30240. engine.draw(true, 0, 6);
  30241. pp.onAfterRenderObservable.notifyObservers(effect);
  30242. }
  30243. }
  30244. // Restore states
  30245. engine.setDepthBuffer(true);
  30246. engine.setDepthWrite(true);
  30247. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30248. };
  30249. PostProcessManager.prototype.dispose = function () {
  30250. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30251. if (buffer) {
  30252. buffer.dispose();
  30253. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30254. }
  30255. if (this._indexBuffer) {
  30256. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30257. this._indexBuffer = null;
  30258. }
  30259. };
  30260. return PostProcessManager;
  30261. }());
  30262. BABYLON.PostProcessManager = PostProcessManager;
  30263. })(BABYLON || (BABYLON = {}));
  30264. //# sourceMappingURL=babylon.postProcessManager.js.map
  30265. var BABYLON;
  30266. (function (BABYLON) {
  30267. /**
  30268. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  30269. */
  30270. var PerformanceMonitor = (function () {
  30271. /**
  30272. * constructor
  30273. * @param frameSampleSize The number of samples required to saturate the sliding window
  30274. */
  30275. function PerformanceMonitor(frameSampleSize) {
  30276. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  30277. this._enabled = true;
  30278. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  30279. }
  30280. /**
  30281. * Samples current frame
  30282. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  30283. */
  30284. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  30285. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  30286. if (!this._enabled)
  30287. return;
  30288. if (this._lastFrameTimeMs != null) {
  30289. var dt = timeMs - this._lastFrameTimeMs;
  30290. this._rollingFrameTime.add(dt);
  30291. }
  30292. this._lastFrameTimeMs = timeMs;
  30293. };
  30294. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30295. /**
  30296. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30297. * @return Average frame time in milliseconds
  30298. */
  30299. get: function () {
  30300. return this._rollingFrameTime.average;
  30301. },
  30302. enumerable: true,
  30303. configurable: true
  30304. });
  30305. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30306. /**
  30307. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30308. * @return Frame time variance in milliseconds squared
  30309. */
  30310. get: function () {
  30311. return this._rollingFrameTime.variance;
  30312. },
  30313. enumerable: true,
  30314. configurable: true
  30315. });
  30316. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30317. /**
  30318. * Returns the frame time of the most recent frame
  30319. * @return Frame time in milliseconds
  30320. */
  30321. get: function () {
  30322. return this._rollingFrameTime.history(0);
  30323. },
  30324. enumerable: true,
  30325. configurable: true
  30326. });
  30327. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30328. /**
  30329. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30330. * @return Framerate in frames per second
  30331. */
  30332. get: function () {
  30333. return 1000.0 / this._rollingFrameTime.average;
  30334. },
  30335. enumerable: true,
  30336. configurable: true
  30337. });
  30338. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30339. /**
  30340. * Returns the average framerate in frames per second using the most recent frame time
  30341. * @return Framerate in frames per second
  30342. */
  30343. get: function () {
  30344. return 1000.0 / this._rollingFrameTime.history(0);
  30345. },
  30346. enumerable: true,
  30347. configurable: true
  30348. });
  30349. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30350. /**
  30351. * Returns true if enough samples have been taken to completely fill the sliding window
  30352. * @return true if saturated
  30353. */
  30354. get: function () {
  30355. return this._rollingFrameTime.isSaturated();
  30356. },
  30357. enumerable: true,
  30358. configurable: true
  30359. });
  30360. /**
  30361. * Enables contributions to the sliding window sample set
  30362. */
  30363. PerformanceMonitor.prototype.enable = function () {
  30364. this._enabled = true;
  30365. };
  30366. /**
  30367. * Disables contributions to the sliding window sample set
  30368. * Samples will not be interpolated over the disabled period
  30369. */
  30370. PerformanceMonitor.prototype.disable = function () {
  30371. this._enabled = false;
  30372. //clear last sample to avoid interpolating over the disabled period when next enabled
  30373. this._lastFrameTimeMs = null;
  30374. this._lastChangeTimeMs = null;
  30375. };
  30376. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30377. /**
  30378. * Returns true if sampling is enabled
  30379. * @return true if enabled
  30380. */
  30381. get: function () {
  30382. return this._enabled;
  30383. },
  30384. enumerable: true,
  30385. configurable: true
  30386. });
  30387. /**
  30388. * Resets performance monitor
  30389. */
  30390. PerformanceMonitor.prototype.reset = function () {
  30391. //clear last sample to avoid interpolating over the disabled period when next enabled
  30392. this._lastFrameTimeMs = null;
  30393. this._lastChangeTimeMs = null;
  30394. //wipe record
  30395. this._rollingFrameTime.reset();
  30396. };
  30397. return PerformanceMonitor;
  30398. }());
  30399. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30400. /**
  30401. * RollingAverage
  30402. *
  30403. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30404. */
  30405. var RollingAverage = (function () {
  30406. /**
  30407. * constructor
  30408. * @param length The number of samples required to saturate the sliding window
  30409. */
  30410. function RollingAverage(length) {
  30411. this._samples = new Array(length);
  30412. this.reset();
  30413. }
  30414. /**
  30415. * Adds a sample to the sample set
  30416. * @param v The sample value
  30417. */
  30418. RollingAverage.prototype.add = function (v) {
  30419. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30420. var delta;
  30421. //we need to check if we've already wrapped round
  30422. if (this.isSaturated()) {
  30423. //remove bottom of stack from mean
  30424. var bottomValue = this._samples[this._pos];
  30425. delta = bottomValue - this.average;
  30426. this.average -= delta / (this._sampleCount - 1);
  30427. this._m2 -= delta * (bottomValue - this.average);
  30428. }
  30429. else {
  30430. this._sampleCount++;
  30431. }
  30432. //add new value to mean
  30433. delta = v - this.average;
  30434. this.average += delta / (this._sampleCount);
  30435. this._m2 += delta * (v - this.average);
  30436. //set the new variance
  30437. this.variance = this._m2 / (this._sampleCount - 1);
  30438. this._samples[this._pos] = v;
  30439. this._pos++;
  30440. this._pos %= this._samples.length; //positive wrap around
  30441. };
  30442. /**
  30443. * Returns previously added values or null if outside of history or outside the sliding window domain
  30444. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30445. * @return Value previously recorded with add() or null if outside of range
  30446. */
  30447. RollingAverage.prototype.history = function (i) {
  30448. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30449. return null;
  30450. }
  30451. var i0 = this._wrapPosition(this._pos - 1.0);
  30452. return this._samples[this._wrapPosition(i0 - i)];
  30453. };
  30454. /**
  30455. * Returns true if enough samples have been taken to completely fill the sliding window
  30456. * @return true if sample-set saturated
  30457. */
  30458. RollingAverage.prototype.isSaturated = function () {
  30459. return this._sampleCount >= this._samples.length;
  30460. };
  30461. /**
  30462. * Resets the rolling average (equivalent to 0 samples taken so far)
  30463. */
  30464. RollingAverage.prototype.reset = function () {
  30465. this.average = 0;
  30466. this.variance = 0;
  30467. this._sampleCount = 0;
  30468. this._pos = 0;
  30469. this._m2 = 0;
  30470. };
  30471. /**
  30472. * Wraps a value around the sample range boundaries
  30473. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30474. * @return Wrapped position in sample range
  30475. */
  30476. RollingAverage.prototype._wrapPosition = function (i) {
  30477. var max = this._samples.length;
  30478. return ((i % max) + max) % max;
  30479. };
  30480. return RollingAverage;
  30481. }());
  30482. BABYLON.RollingAverage = RollingAverage;
  30483. })(BABYLON || (BABYLON = {}));
  30484. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30485. var BABYLON;
  30486. (function (BABYLON) {
  30487. var StandardMaterialDefines = (function (_super) {
  30488. __extends(StandardMaterialDefines, _super);
  30489. function StandardMaterialDefines() {
  30490. var _this = _super.call(this) || this;
  30491. _this.MAINUV1 = false;
  30492. _this.MAINUV2 = false;
  30493. _this.DIFFUSE = false;
  30494. _this.DIFFUSEDIRECTUV = 0;
  30495. _this.AMBIENT = false;
  30496. _this.AMBIENTDIRECTUV = 0;
  30497. _this.OPACITY = false;
  30498. _this.OPACITYDIRECTUV = 0;
  30499. _this.OPACITYRGB = false;
  30500. _this.REFLECTION = false;
  30501. _this.EMISSIVE = false;
  30502. _this.EMISSIVEDIRECTUV = 0;
  30503. _this.SPECULAR = false;
  30504. _this.SPECULARDIRECTUV = 0;
  30505. _this.BUMP = false;
  30506. _this.BUMPDIRECTUV = 0;
  30507. _this.PARALLAX = false;
  30508. _this.PARALLAXOCCLUSION = false;
  30509. _this.SPECULAROVERALPHA = false;
  30510. _this.CLIPPLANE = false;
  30511. _this.ALPHATEST = false;
  30512. _this.DEPTHPREPASS = false;
  30513. _this.ALPHAFROMDIFFUSE = false;
  30514. _this.POINTSIZE = false;
  30515. _this.FOG = false;
  30516. _this.SPECULARTERM = false;
  30517. _this.DIFFUSEFRESNEL = false;
  30518. _this.OPACITYFRESNEL = false;
  30519. _this.REFLECTIONFRESNEL = false;
  30520. _this.REFRACTIONFRESNEL = false;
  30521. _this.EMISSIVEFRESNEL = false;
  30522. _this.FRESNEL = false;
  30523. _this.NORMAL = false;
  30524. _this.UV1 = false;
  30525. _this.UV2 = false;
  30526. _this.VERTEXCOLOR = false;
  30527. _this.VERTEXALPHA = false;
  30528. _this.NUM_BONE_INFLUENCERS = 0;
  30529. _this.BonesPerMesh = 0;
  30530. _this.INSTANCES = false;
  30531. _this.GLOSSINESS = false;
  30532. _this.ROUGHNESS = false;
  30533. _this.EMISSIVEASILLUMINATION = false;
  30534. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30535. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30536. _this.LIGHTMAP = false;
  30537. _this.LIGHTMAPDIRECTUV = 0;
  30538. _this.USELIGHTMAPASSHADOWMAP = false;
  30539. _this.REFLECTIONMAP_3D = false;
  30540. _this.REFLECTIONMAP_SPHERICAL = false;
  30541. _this.REFLECTIONMAP_PLANAR = false;
  30542. _this.REFLECTIONMAP_CUBIC = false;
  30543. _this.REFLECTIONMAP_PROJECTION = false;
  30544. _this.REFLECTIONMAP_SKYBOX = false;
  30545. _this.REFLECTIONMAP_EXPLICIT = false;
  30546. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30547. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30548. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30549. _this.INVERTCUBICMAP = false;
  30550. _this.LOGARITHMICDEPTH = false;
  30551. _this.REFRACTION = false;
  30552. _this.REFRACTIONMAP_3D = false;
  30553. _this.REFLECTIONOVERALPHA = false;
  30554. _this.TWOSIDEDLIGHTING = false;
  30555. _this.SHADOWFLOAT = false;
  30556. _this.MORPHTARGETS = false;
  30557. _this.MORPHTARGETS_NORMAL = false;
  30558. _this.MORPHTARGETS_TANGENT = false;
  30559. _this.NUM_MORPH_INFLUENCERS = 0;
  30560. _this.USERIGHTHANDEDSYSTEM = false;
  30561. _this.IMAGEPROCESSING = false;
  30562. _this.VIGNETTE = false;
  30563. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30564. _this.VIGNETTEBLENDMODEOPAQUE = false;
  30565. _this.TONEMAPPING = false;
  30566. _this.CONTRAST = false;
  30567. _this.COLORCURVES = false;
  30568. _this.COLORGRADING = false;
  30569. _this.SAMPLER3DGREENDEPTH = false;
  30570. _this.SAMPLER3DBGRMAP = false;
  30571. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  30572. _this.EXPOSURE = false;
  30573. _this.rebuild();
  30574. return _this;
  30575. }
  30576. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  30577. var modes = [
  30578. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  30579. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  30580. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  30581. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  30582. ];
  30583. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  30584. var mode = modes_1[_i];
  30585. this[mode] = (mode === modeToEnable);
  30586. }
  30587. };
  30588. return StandardMaterialDefines;
  30589. }(BABYLON.MaterialDefines));
  30590. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30591. var StandardMaterial = (function (_super) {
  30592. __extends(StandardMaterial, _super);
  30593. function StandardMaterial(name, scene) {
  30594. var _this = _super.call(this, name, scene) || this;
  30595. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30596. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30597. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30598. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30599. _this.specularPower = 64;
  30600. _this._useAlphaFromDiffuseTexture = false;
  30601. _this._useEmissiveAsIllumination = false;
  30602. _this._linkEmissiveWithDiffuse = false;
  30603. _this._useSpecularOverAlpha = false;
  30604. _this._useReflectionOverAlpha = false;
  30605. _this._disableLighting = false;
  30606. _this._useParallax = false;
  30607. _this._useParallaxOcclusion = false;
  30608. _this.parallaxScaleBias = 0.05;
  30609. _this._roughness = 0;
  30610. _this.indexOfRefraction = 0.98;
  30611. _this.invertRefractionY = true;
  30612. _this._useLightmapAsShadowmap = false;
  30613. _this._useReflectionFresnelFromSpecular = false;
  30614. _this._useGlossinessFromSpecularMapAlpha = false;
  30615. _this._maxSimultaneousLights = 4;
  30616. /**
  30617. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30618. */
  30619. _this._invertNormalMapX = false;
  30620. /**
  30621. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30622. */
  30623. _this._invertNormalMapY = false;
  30624. /**
  30625. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30626. */
  30627. _this._twoSidedLighting = false;
  30628. _this._renderTargets = new BABYLON.SmartArray(16);
  30629. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30630. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30631. // Setup the default processing configuration to the scene.
  30632. _this._attachImageProcessingConfiguration(null);
  30633. _this.getRenderTargetTextures = function () {
  30634. _this._renderTargets.reset();
  30635. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30636. _this._renderTargets.push(_this._reflectionTexture);
  30637. }
  30638. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30639. _this._renderTargets.push(_this._refractionTexture);
  30640. }
  30641. return _this._renderTargets;
  30642. };
  30643. return _this;
  30644. }
  30645. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  30646. /**
  30647. * Gets the image processing configuration used either in this material.
  30648. */
  30649. get: function () {
  30650. return this._imageProcessingConfiguration;
  30651. },
  30652. /**
  30653. * Sets the Default image processing configuration used either in the this material.
  30654. *
  30655. * If sets to null, the scene one is in use.
  30656. */
  30657. set: function (value) {
  30658. this._attachImageProcessingConfiguration(value);
  30659. // Ensure the effect will be rebuilt.
  30660. this._markAllSubMeshesAsTexturesDirty();
  30661. },
  30662. enumerable: true,
  30663. configurable: true
  30664. });
  30665. /**
  30666. * Attaches a new image processing configuration to the Standard Material.
  30667. * @param configuration
  30668. */
  30669. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30670. var _this = this;
  30671. if (configuration === this._imageProcessingConfiguration) {
  30672. return;
  30673. }
  30674. // Detaches observer.
  30675. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30676. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30677. }
  30678. // Pick the scene configuration if needed.
  30679. if (!configuration) {
  30680. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30681. }
  30682. else {
  30683. this._imageProcessingConfiguration = configuration;
  30684. }
  30685. // Attaches observer.
  30686. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30687. _this._markAllSubMeshesAsImageProcessingDirty();
  30688. });
  30689. };
  30690. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  30691. /**
  30692. * Gets wether the color curves effect is enabled.
  30693. */
  30694. get: function () {
  30695. return this.imageProcessingConfiguration.colorCurvesEnabled;
  30696. },
  30697. /**
  30698. * Sets wether the color curves effect is enabled.
  30699. */
  30700. set: function (value) {
  30701. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  30702. },
  30703. enumerable: true,
  30704. configurable: true
  30705. });
  30706. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  30707. /**
  30708. * Gets wether the color grading effect is enabled.
  30709. */
  30710. get: function () {
  30711. return this.imageProcessingConfiguration.colorGradingEnabled;
  30712. },
  30713. /**
  30714. * Gets wether the color grading effect is enabled.
  30715. */
  30716. set: function (value) {
  30717. this.imageProcessingConfiguration.colorGradingEnabled = value;
  30718. },
  30719. enumerable: true,
  30720. configurable: true
  30721. });
  30722. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  30723. /**
  30724. * Gets wether tonemapping is enabled or not.
  30725. */
  30726. get: function () {
  30727. return this._imageProcessingConfiguration.toneMappingEnabled;
  30728. },
  30729. /**
  30730. * Sets wether tonemapping is enabled or not
  30731. */
  30732. set: function (value) {
  30733. this._imageProcessingConfiguration.toneMappingEnabled = value;
  30734. },
  30735. enumerable: true,
  30736. configurable: true
  30737. });
  30738. ;
  30739. ;
  30740. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  30741. /**
  30742. * The camera exposure used on this material.
  30743. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30744. * This corresponds to a photographic exposure.
  30745. */
  30746. get: function () {
  30747. return this._imageProcessingConfiguration.exposure;
  30748. },
  30749. /**
  30750. * The camera exposure used on this material.
  30751. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30752. * This corresponds to a photographic exposure.
  30753. */
  30754. set: function (value) {
  30755. this._imageProcessingConfiguration.exposure = value;
  30756. },
  30757. enumerable: true,
  30758. configurable: true
  30759. });
  30760. ;
  30761. ;
  30762. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  30763. /**
  30764. * Gets The camera contrast used on this material.
  30765. */
  30766. get: function () {
  30767. return this._imageProcessingConfiguration.contrast;
  30768. },
  30769. /**
  30770. * Sets The camera contrast used on this material.
  30771. */
  30772. set: function (value) {
  30773. this._imageProcessingConfiguration.contrast = value;
  30774. },
  30775. enumerable: true,
  30776. configurable: true
  30777. });
  30778. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  30779. /**
  30780. * Gets the Color Grading 2D Lookup Texture.
  30781. */
  30782. get: function () {
  30783. return this._imageProcessingConfiguration.colorGradingTexture;
  30784. },
  30785. /**
  30786. * Sets the Color Grading 2D Lookup Texture.
  30787. */
  30788. set: function (value) {
  30789. this._imageProcessingConfiguration.colorGradingTexture = value;
  30790. },
  30791. enumerable: true,
  30792. configurable: true
  30793. });
  30794. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  30795. /**
  30796. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30797. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30798. * 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;
  30799. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30800. */
  30801. get: function () {
  30802. return this._imageProcessingConfiguration.colorCurves;
  30803. },
  30804. /**
  30805. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30806. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30807. * 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;
  30808. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30809. */
  30810. set: function (value) {
  30811. this._imageProcessingConfiguration.colorCurves = value;
  30812. },
  30813. enumerable: true,
  30814. configurable: true
  30815. });
  30816. StandardMaterial.prototype.getClassName = function () {
  30817. return "StandardMaterial";
  30818. };
  30819. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30820. get: function () {
  30821. return this._useLogarithmicDepth;
  30822. },
  30823. set: function (value) {
  30824. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30825. this._markAllSubMeshesAsMiscDirty();
  30826. },
  30827. enumerable: true,
  30828. configurable: true
  30829. });
  30830. StandardMaterial.prototype.needAlphaBlending = function () {
  30831. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  30832. };
  30833. StandardMaterial.prototype.needAlphaTesting = function () {
  30834. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  30835. };
  30836. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30837. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  30838. };
  30839. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30840. return this._diffuseTexture;
  30841. };
  30842. /**
  30843. * Child classes can use it to update shaders
  30844. */
  30845. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30846. if (this.isFrozen) {
  30847. if (this._wasPreviouslyReady && subMesh.effect) {
  30848. return true;
  30849. }
  30850. }
  30851. if (!subMesh._materialDefines) {
  30852. subMesh._materialDefines = new StandardMaterialDefines();
  30853. }
  30854. var scene = this.getScene();
  30855. var defines = subMesh._materialDefines;
  30856. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30857. if (defines._renderId === scene.getRenderId()) {
  30858. return true;
  30859. }
  30860. }
  30861. var engine = scene.getEngine();
  30862. // Lights
  30863. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30864. // Textures
  30865. if (defines._areTexturesDirty) {
  30866. defines._needUVs = false;
  30867. defines.MAINUV1 = false;
  30868. defines.MAINUV2 = false;
  30869. if (scene.texturesEnabled) {
  30870. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30871. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  30872. return false;
  30873. }
  30874. else {
  30875. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  30876. }
  30877. }
  30878. else {
  30879. defines.DIFFUSE = false;
  30880. }
  30881. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30882. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30883. return false;
  30884. }
  30885. else {
  30886. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  30887. }
  30888. }
  30889. else {
  30890. defines.AMBIENT = false;
  30891. }
  30892. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30893. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30894. return false;
  30895. }
  30896. else {
  30897. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  30898. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  30899. }
  30900. }
  30901. else {
  30902. defines.OPACITY = false;
  30903. }
  30904. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30905. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  30906. return false;
  30907. }
  30908. else {
  30909. defines._needNormals = true;
  30910. defines.REFLECTION = true;
  30911. defines.ROUGHNESS = (this._roughness > 0);
  30912. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  30913. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  30914. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  30915. switch (this._reflectionTexture.coordinatesMode) {
  30916. case BABYLON.Texture.CUBIC_MODE:
  30917. case BABYLON.Texture.INVCUBIC_MODE:
  30918. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  30919. break;
  30920. case BABYLON.Texture.EXPLICIT_MODE:
  30921. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  30922. break;
  30923. case BABYLON.Texture.PLANAR_MODE:
  30924. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  30925. break;
  30926. case BABYLON.Texture.PROJECTION_MODE:
  30927. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  30928. break;
  30929. case BABYLON.Texture.SKYBOX_MODE:
  30930. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  30931. break;
  30932. case BABYLON.Texture.SPHERICAL_MODE:
  30933. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  30934. break;
  30935. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30936. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  30937. break;
  30938. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30939. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  30940. break;
  30941. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30942. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  30943. break;
  30944. }
  30945. }
  30946. }
  30947. else {
  30948. defines.REFLECTION = false;
  30949. }
  30950. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30951. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30952. return false;
  30953. }
  30954. else {
  30955. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  30956. }
  30957. }
  30958. else {
  30959. defines.EMISSIVE = false;
  30960. }
  30961. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30962. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30963. return false;
  30964. }
  30965. else {
  30966. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  30967. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30968. }
  30969. }
  30970. else {
  30971. defines.LIGHTMAP = false;
  30972. }
  30973. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30974. if (!this._specularTexture.isReadyOrNotBlocking()) {
  30975. return false;
  30976. }
  30977. else {
  30978. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  30979. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  30980. }
  30981. }
  30982. else {
  30983. defines.SPECULAR = false;
  30984. }
  30985. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30986. // Bump texure can not be not blocking.
  30987. if (!this._bumpTexture.isReady()) {
  30988. return false;
  30989. }
  30990. else {
  30991. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  30992. defines.PARALLAX = this._useParallax;
  30993. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  30994. }
  30995. }
  30996. else {
  30997. defines.BUMP = false;
  30998. }
  30999. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31000. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  31001. return false;
  31002. }
  31003. else {
  31004. defines._needUVs = true;
  31005. defines.REFRACTION = true;
  31006. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  31007. }
  31008. }
  31009. else {
  31010. defines.REFRACTION = false;
  31011. }
  31012. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  31013. }
  31014. else {
  31015. defines.DIFFUSE = false;
  31016. defines.AMBIENT = false;
  31017. defines.OPACITY = false;
  31018. defines.REFLECTION = false;
  31019. defines.EMISSIVE = false;
  31020. defines.LIGHTMAP = false;
  31021. defines.BUMP = false;
  31022. defines.REFRACTION = false;
  31023. }
  31024. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  31025. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  31026. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  31027. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  31028. }
  31029. if (defines._areImageProcessingDirty) {
  31030. if (!this._imageProcessingConfiguration.isReady()) {
  31031. return false;
  31032. }
  31033. this._imageProcessingConfiguration.prepareDefines(defines);
  31034. }
  31035. if (defines._areFresnelDirty) {
  31036. if (StandardMaterial.FresnelEnabled) {
  31037. // Fresnel
  31038. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  31039. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  31040. this._reflectionFresnelParameters) {
  31041. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  31042. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  31043. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  31044. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  31045. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  31046. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  31047. defines._needNormals = true;
  31048. defines.FRESNEL = true;
  31049. }
  31050. }
  31051. else {
  31052. defines.FRESNEL = false;
  31053. }
  31054. }
  31055. // Misc.
  31056. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  31057. // Attribs
  31058. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  31059. // Values that need to be evaluated on every frame
  31060. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  31061. // Get correct effect
  31062. if (defines.isDirty) {
  31063. defines.markAsProcessed();
  31064. scene.resetCachedMaterial();
  31065. // Fallbacks
  31066. var fallbacks = new BABYLON.EffectFallbacks();
  31067. if (defines.REFLECTION) {
  31068. fallbacks.addFallback(0, "REFLECTION");
  31069. }
  31070. if (defines.SPECULAR) {
  31071. fallbacks.addFallback(0, "SPECULAR");
  31072. }
  31073. if (defines.BUMP) {
  31074. fallbacks.addFallback(0, "BUMP");
  31075. }
  31076. if (defines.PARALLAX) {
  31077. fallbacks.addFallback(1, "PARALLAX");
  31078. }
  31079. if (defines.PARALLAXOCCLUSION) {
  31080. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  31081. }
  31082. if (defines.SPECULAROVERALPHA) {
  31083. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  31084. }
  31085. if (defines.FOG) {
  31086. fallbacks.addFallback(1, "FOG");
  31087. }
  31088. if (defines.POINTSIZE) {
  31089. fallbacks.addFallback(0, "POINTSIZE");
  31090. }
  31091. if (defines.LOGARITHMICDEPTH) {
  31092. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  31093. }
  31094. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  31095. if (defines.SPECULARTERM) {
  31096. fallbacks.addFallback(0, "SPECULARTERM");
  31097. }
  31098. if (defines.DIFFUSEFRESNEL) {
  31099. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  31100. }
  31101. if (defines.OPACITYFRESNEL) {
  31102. fallbacks.addFallback(2, "OPACITYFRESNEL");
  31103. }
  31104. if (defines.REFLECTIONFRESNEL) {
  31105. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  31106. }
  31107. if (defines.EMISSIVEFRESNEL) {
  31108. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  31109. }
  31110. if (defines.FRESNEL) {
  31111. fallbacks.addFallback(4, "FRESNEL");
  31112. }
  31113. //Attributes
  31114. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31115. if (defines.NORMAL) {
  31116. attribs.push(BABYLON.VertexBuffer.NormalKind);
  31117. }
  31118. if (defines.UV1) {
  31119. attribs.push(BABYLON.VertexBuffer.UVKind);
  31120. }
  31121. if (defines.UV2) {
  31122. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31123. }
  31124. if (defines.VERTEXCOLOR) {
  31125. attribs.push(BABYLON.VertexBuffer.ColorKind);
  31126. }
  31127. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  31128. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  31129. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  31130. var shaderName = "default";
  31131. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  31132. "vFogInfos", "vFogColor", "pointSize",
  31133. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  31134. "mBones",
  31135. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  31136. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  31137. "logarithmicDepthConstant", "vNormalReoderParams"
  31138. ];
  31139. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  31140. var uniformBuffers = ["Material", "Scene"];
  31141. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  31142. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  31143. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  31144. uniformsNames: uniforms,
  31145. uniformBuffersNames: uniformBuffers,
  31146. samplers: samplers,
  31147. defines: defines,
  31148. maxSimultaneousLights: this._maxSimultaneousLights
  31149. });
  31150. if (this.customShaderNameResolve) {
  31151. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  31152. }
  31153. var join = defines.toString();
  31154. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  31155. attributes: attribs,
  31156. uniformsNames: uniforms,
  31157. uniformBuffersNames: uniformBuffers,
  31158. samplers: samplers,
  31159. defines: join,
  31160. fallbacks: fallbacks,
  31161. onCompiled: this.onCompiled,
  31162. onError: this.onError,
  31163. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  31164. }, engine), defines);
  31165. this.buildUniformLayout();
  31166. }
  31167. if (!subMesh.effect.isReady()) {
  31168. return false;
  31169. }
  31170. defines._renderId = scene.getRenderId();
  31171. this._wasPreviouslyReady = true;
  31172. return true;
  31173. };
  31174. StandardMaterial.prototype.buildUniformLayout = function () {
  31175. // Order is important !
  31176. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  31177. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  31178. this._uniformBuffer.addUniform("opacityParts", 4);
  31179. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  31180. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  31181. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  31182. this._uniformBuffer.addUniform("refractionRightColor", 4);
  31183. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  31184. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  31185. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  31186. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  31187. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  31188. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  31189. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  31190. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  31191. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  31192. this._uniformBuffer.addUniform("vBumpInfos", 3);
  31193. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  31194. this._uniformBuffer.addUniform("ambientMatrix", 16);
  31195. this._uniformBuffer.addUniform("opacityMatrix", 16);
  31196. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  31197. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  31198. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  31199. this._uniformBuffer.addUniform("specularMatrix", 16);
  31200. this._uniformBuffer.addUniform("bumpMatrix", 16);
  31201. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  31202. this._uniformBuffer.addUniform("refractionMatrix", 16);
  31203. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  31204. this._uniformBuffer.addUniform("vSpecularColor", 4);
  31205. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  31206. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  31207. this._uniformBuffer.addUniform("pointSize", 1);
  31208. this._uniformBuffer.create();
  31209. };
  31210. StandardMaterial.prototype.unbind = function () {
  31211. if (this._activeEffect) {
  31212. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31213. this._activeEffect.setTexture("reflection2DSampler", null);
  31214. }
  31215. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31216. this._activeEffect.setTexture("refraction2DSampler", null);
  31217. }
  31218. }
  31219. _super.prototype.unbind.call(this);
  31220. };
  31221. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31222. var scene = this.getScene();
  31223. var defines = subMesh._materialDefines;
  31224. if (!defines) {
  31225. return;
  31226. }
  31227. var effect = subMesh.effect;
  31228. this._activeEffect = effect;
  31229. // Matrices
  31230. this.bindOnlyWorldMatrix(world);
  31231. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  31232. // Bones
  31233. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  31234. if (mustRebind) {
  31235. this._uniformBuffer.bindToEffect(effect, "Material");
  31236. this.bindViewProjection(effect);
  31237. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  31238. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  31239. // Fresnel
  31240. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  31241. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  31242. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  31243. }
  31244. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  31245. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  31246. }
  31247. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  31248. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  31249. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  31250. }
  31251. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  31252. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  31253. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  31254. }
  31255. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  31256. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  31257. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  31258. }
  31259. }
  31260. // Textures
  31261. if (scene.texturesEnabled) {
  31262. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31263. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  31264. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  31265. }
  31266. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31267. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  31268. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  31269. }
  31270. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31271. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31272. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  31273. }
  31274. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31275. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  31276. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  31277. }
  31278. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31279. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31280. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  31281. }
  31282. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31283. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31284. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  31285. }
  31286. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31287. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  31288. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  31289. }
  31290. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31291. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  31292. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  31293. if (scene._mirroredCameraPosition) {
  31294. 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);
  31295. }
  31296. else {
  31297. 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);
  31298. }
  31299. }
  31300. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31301. var depth = 1.0;
  31302. if (!this._refractionTexture.isCube) {
  31303. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  31304. if (this._refractionTexture.depth) {
  31305. depth = this._refractionTexture.depth;
  31306. }
  31307. }
  31308. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  31309. }
  31310. }
  31311. // Point size
  31312. if (this.pointsCloud) {
  31313. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  31314. }
  31315. if (defines.SPECULARTERM) {
  31316. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  31317. }
  31318. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  31319. // Diffuse
  31320. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  31321. }
  31322. // Textures
  31323. if (scene.texturesEnabled) {
  31324. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31325. effect.setTexture("diffuseSampler", this._diffuseTexture);
  31326. }
  31327. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31328. effect.setTexture("ambientSampler", this._ambientTexture);
  31329. }
  31330. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31331. effect.setTexture("opacitySampler", this._opacityTexture);
  31332. }
  31333. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31334. if (this._reflectionTexture.isCube) {
  31335. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  31336. }
  31337. else {
  31338. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  31339. }
  31340. }
  31341. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31342. effect.setTexture("emissiveSampler", this._emissiveTexture);
  31343. }
  31344. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31345. effect.setTexture("lightmapSampler", this._lightmapTexture);
  31346. }
  31347. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31348. effect.setTexture("specularSampler", this._specularTexture);
  31349. }
  31350. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31351. effect.setTexture("bumpSampler", this._bumpTexture);
  31352. }
  31353. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31354. var depth = 1.0;
  31355. if (this._refractionTexture.isCube) {
  31356. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  31357. }
  31358. else {
  31359. effect.setTexture("refraction2DSampler", this._refractionTexture);
  31360. }
  31361. }
  31362. }
  31363. // Clip plane
  31364. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  31365. // Colors
  31366. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  31367. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  31368. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  31369. }
  31370. if (mustRebind || !this.isFrozen) {
  31371. // Lights
  31372. if (scene.lightsEnabled && !this._disableLighting) {
  31373. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  31374. }
  31375. // View
  31376. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  31377. this.bindView(effect);
  31378. }
  31379. // Fog
  31380. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  31381. // Morph targets
  31382. if (defines.NUM_MORPH_INFLUENCERS) {
  31383. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  31384. }
  31385. // Log. depth
  31386. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  31387. // image processing
  31388. this._imageProcessingConfiguration.bind(this._activeEffect);
  31389. }
  31390. this._uniformBuffer.update();
  31391. this._afterBind(mesh, this._activeEffect);
  31392. };
  31393. StandardMaterial.prototype.getAnimatables = function () {
  31394. var results = [];
  31395. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  31396. results.push(this._diffuseTexture);
  31397. }
  31398. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  31399. results.push(this._ambientTexture);
  31400. }
  31401. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  31402. results.push(this._opacityTexture);
  31403. }
  31404. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  31405. results.push(this._reflectionTexture);
  31406. }
  31407. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  31408. results.push(this._emissiveTexture);
  31409. }
  31410. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  31411. results.push(this._specularTexture);
  31412. }
  31413. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  31414. results.push(this._bumpTexture);
  31415. }
  31416. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  31417. results.push(this._lightmapTexture);
  31418. }
  31419. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  31420. results.push(this._refractionTexture);
  31421. }
  31422. return results;
  31423. };
  31424. StandardMaterial.prototype.getActiveTextures = function () {
  31425. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31426. if (this._diffuseTexture) {
  31427. activeTextures.push(this._diffuseTexture);
  31428. }
  31429. if (this._ambientTexture) {
  31430. activeTextures.push(this._ambientTexture);
  31431. }
  31432. if (this._opacityTexture) {
  31433. activeTextures.push(this._opacityTexture);
  31434. }
  31435. if (this._reflectionTexture) {
  31436. activeTextures.push(this._reflectionTexture);
  31437. }
  31438. if (this._emissiveTexture) {
  31439. activeTextures.push(this._emissiveTexture);
  31440. }
  31441. if (this._specularTexture) {
  31442. activeTextures.push(this._specularTexture);
  31443. }
  31444. if (this._bumpTexture) {
  31445. activeTextures.push(this._bumpTexture);
  31446. }
  31447. if (this._lightmapTexture) {
  31448. activeTextures.push(this._lightmapTexture);
  31449. }
  31450. if (this._refractionTexture) {
  31451. activeTextures.push(this._refractionTexture);
  31452. }
  31453. return activeTextures;
  31454. };
  31455. StandardMaterial.prototype.hasTexture = function (texture) {
  31456. if (_super.prototype.hasTexture.call(this, texture)) {
  31457. return true;
  31458. }
  31459. if (this._diffuseTexture === texture) {
  31460. return true;
  31461. }
  31462. if (this._ambientTexture === texture) {
  31463. return true;
  31464. }
  31465. if (this._opacityTexture === texture) {
  31466. return true;
  31467. }
  31468. if (this._reflectionTexture === texture) {
  31469. return true;
  31470. }
  31471. if (this._emissiveTexture === texture) {
  31472. return true;
  31473. }
  31474. if (this._specularTexture === texture) {
  31475. return true;
  31476. }
  31477. if (this._bumpTexture === texture) {
  31478. return true;
  31479. }
  31480. if (this._lightmapTexture === texture) {
  31481. return true;
  31482. }
  31483. if (this._refractionTexture === texture) {
  31484. return true;
  31485. }
  31486. return false;
  31487. };
  31488. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31489. if (forceDisposeTextures) {
  31490. if (this._diffuseTexture) {
  31491. this._diffuseTexture.dispose();
  31492. }
  31493. if (this._ambientTexture) {
  31494. this._ambientTexture.dispose();
  31495. }
  31496. if (this._opacityTexture) {
  31497. this._opacityTexture.dispose();
  31498. }
  31499. if (this._reflectionTexture) {
  31500. this._reflectionTexture.dispose();
  31501. }
  31502. if (this._emissiveTexture) {
  31503. this._emissiveTexture.dispose();
  31504. }
  31505. if (this._specularTexture) {
  31506. this._specularTexture.dispose();
  31507. }
  31508. if (this._bumpTexture) {
  31509. this._bumpTexture.dispose();
  31510. }
  31511. if (this._lightmapTexture) {
  31512. this._lightmapTexture.dispose();
  31513. }
  31514. if (this._refractionTexture) {
  31515. this._refractionTexture.dispose();
  31516. }
  31517. }
  31518. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31519. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31520. }
  31521. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31522. };
  31523. StandardMaterial.prototype.clone = function (name) {
  31524. var _this = this;
  31525. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  31526. result.name = name;
  31527. result.id = name;
  31528. return result;
  31529. };
  31530. StandardMaterial.prototype.serialize = function () {
  31531. return BABYLON.SerializationHelper.Serialize(this);
  31532. };
  31533. // Statics
  31534. StandardMaterial.Parse = function (source, scene, rootUrl) {
  31535. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  31536. };
  31537. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  31538. get: function () {
  31539. return StandardMaterial._DiffuseTextureEnabled;
  31540. },
  31541. set: function (value) {
  31542. if (StandardMaterial._DiffuseTextureEnabled === value) {
  31543. return;
  31544. }
  31545. StandardMaterial._DiffuseTextureEnabled = value;
  31546. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31547. },
  31548. enumerable: true,
  31549. configurable: true
  31550. });
  31551. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  31552. get: function () {
  31553. return StandardMaterial._AmbientTextureEnabled;
  31554. },
  31555. set: function (value) {
  31556. if (StandardMaterial._AmbientTextureEnabled === value) {
  31557. return;
  31558. }
  31559. StandardMaterial._AmbientTextureEnabled = value;
  31560. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31561. },
  31562. enumerable: true,
  31563. configurable: true
  31564. });
  31565. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  31566. get: function () {
  31567. return StandardMaterial._OpacityTextureEnabled;
  31568. },
  31569. set: function (value) {
  31570. if (StandardMaterial._OpacityTextureEnabled === value) {
  31571. return;
  31572. }
  31573. StandardMaterial._OpacityTextureEnabled = value;
  31574. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31575. },
  31576. enumerable: true,
  31577. configurable: true
  31578. });
  31579. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  31580. get: function () {
  31581. return StandardMaterial._ReflectionTextureEnabled;
  31582. },
  31583. set: function (value) {
  31584. if (StandardMaterial._ReflectionTextureEnabled === value) {
  31585. return;
  31586. }
  31587. StandardMaterial._ReflectionTextureEnabled = value;
  31588. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31589. },
  31590. enumerable: true,
  31591. configurable: true
  31592. });
  31593. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  31594. get: function () {
  31595. return StandardMaterial._EmissiveTextureEnabled;
  31596. },
  31597. set: function (value) {
  31598. if (StandardMaterial._EmissiveTextureEnabled === value) {
  31599. return;
  31600. }
  31601. StandardMaterial._EmissiveTextureEnabled = value;
  31602. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31603. },
  31604. enumerable: true,
  31605. configurable: true
  31606. });
  31607. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  31608. get: function () {
  31609. return StandardMaterial._SpecularTextureEnabled;
  31610. },
  31611. set: function (value) {
  31612. if (StandardMaterial._SpecularTextureEnabled === value) {
  31613. return;
  31614. }
  31615. StandardMaterial._SpecularTextureEnabled = value;
  31616. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31617. },
  31618. enumerable: true,
  31619. configurable: true
  31620. });
  31621. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  31622. get: function () {
  31623. return StandardMaterial._BumpTextureEnabled;
  31624. },
  31625. set: function (value) {
  31626. if (StandardMaterial._BumpTextureEnabled === value) {
  31627. return;
  31628. }
  31629. StandardMaterial._BumpTextureEnabled = value;
  31630. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31631. },
  31632. enumerable: true,
  31633. configurable: true
  31634. });
  31635. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  31636. get: function () {
  31637. return StandardMaterial._LightmapTextureEnabled;
  31638. },
  31639. set: function (value) {
  31640. if (StandardMaterial._LightmapTextureEnabled === value) {
  31641. return;
  31642. }
  31643. StandardMaterial._LightmapTextureEnabled = value;
  31644. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31645. },
  31646. enumerable: true,
  31647. configurable: true
  31648. });
  31649. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  31650. get: function () {
  31651. return StandardMaterial._RefractionTextureEnabled;
  31652. },
  31653. set: function (value) {
  31654. if (StandardMaterial._RefractionTextureEnabled === value) {
  31655. return;
  31656. }
  31657. StandardMaterial._RefractionTextureEnabled = value;
  31658. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31659. },
  31660. enumerable: true,
  31661. configurable: true
  31662. });
  31663. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  31664. get: function () {
  31665. return StandardMaterial._ColorGradingTextureEnabled;
  31666. },
  31667. set: function (value) {
  31668. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  31669. return;
  31670. }
  31671. StandardMaterial._ColorGradingTextureEnabled = value;
  31672. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31673. },
  31674. enumerable: true,
  31675. configurable: true
  31676. });
  31677. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  31678. get: function () {
  31679. return StandardMaterial._FresnelEnabled;
  31680. },
  31681. set: function (value) {
  31682. if (StandardMaterial._FresnelEnabled === value) {
  31683. return;
  31684. }
  31685. StandardMaterial._FresnelEnabled = value;
  31686. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  31687. },
  31688. enumerable: true,
  31689. configurable: true
  31690. });
  31691. // Flags used to enable or disable a type of texture for all Standard Materials
  31692. StandardMaterial._DiffuseTextureEnabled = true;
  31693. StandardMaterial._AmbientTextureEnabled = true;
  31694. StandardMaterial._OpacityTextureEnabled = true;
  31695. StandardMaterial._ReflectionTextureEnabled = true;
  31696. StandardMaterial._EmissiveTextureEnabled = true;
  31697. StandardMaterial._SpecularTextureEnabled = true;
  31698. StandardMaterial._BumpTextureEnabled = true;
  31699. StandardMaterial._LightmapTextureEnabled = true;
  31700. StandardMaterial._RefractionTextureEnabled = true;
  31701. StandardMaterial._ColorGradingTextureEnabled = true;
  31702. StandardMaterial._FresnelEnabled = true;
  31703. __decorate([
  31704. BABYLON.serializeAsTexture("diffuseTexture")
  31705. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  31706. __decorate([
  31707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31708. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  31709. __decorate([
  31710. BABYLON.serializeAsTexture("ambientTexture")
  31711. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  31712. __decorate([
  31713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31714. ], StandardMaterial.prototype, "ambientTexture", void 0);
  31715. __decorate([
  31716. BABYLON.serializeAsTexture("opacityTexture")
  31717. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  31718. __decorate([
  31719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31720. ], StandardMaterial.prototype, "opacityTexture", void 0);
  31721. __decorate([
  31722. BABYLON.serializeAsTexture("reflectionTexture")
  31723. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  31724. __decorate([
  31725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31726. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  31727. __decorate([
  31728. BABYLON.serializeAsTexture("emissiveTexture")
  31729. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  31730. __decorate([
  31731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31732. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  31733. __decorate([
  31734. BABYLON.serializeAsTexture("specularTexture")
  31735. ], StandardMaterial.prototype, "_specularTexture", void 0);
  31736. __decorate([
  31737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31738. ], StandardMaterial.prototype, "specularTexture", void 0);
  31739. __decorate([
  31740. BABYLON.serializeAsTexture("bumpTexture")
  31741. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  31742. __decorate([
  31743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31744. ], StandardMaterial.prototype, "bumpTexture", void 0);
  31745. __decorate([
  31746. BABYLON.serializeAsTexture("lightmapTexture")
  31747. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  31748. __decorate([
  31749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31750. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  31751. __decorate([
  31752. BABYLON.serializeAsTexture("refractionTexture")
  31753. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  31754. __decorate([
  31755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31756. ], StandardMaterial.prototype, "refractionTexture", void 0);
  31757. __decorate([
  31758. BABYLON.serializeAsColor3("ambient")
  31759. ], StandardMaterial.prototype, "ambientColor", void 0);
  31760. __decorate([
  31761. BABYLON.serializeAsColor3("diffuse")
  31762. ], StandardMaterial.prototype, "diffuseColor", void 0);
  31763. __decorate([
  31764. BABYLON.serializeAsColor3("specular")
  31765. ], StandardMaterial.prototype, "specularColor", void 0);
  31766. __decorate([
  31767. BABYLON.serializeAsColor3("emissive")
  31768. ], StandardMaterial.prototype, "emissiveColor", void 0);
  31769. __decorate([
  31770. BABYLON.serialize()
  31771. ], StandardMaterial.prototype, "specularPower", void 0);
  31772. __decorate([
  31773. BABYLON.serialize("useAlphaFromDiffuseTexture")
  31774. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  31775. __decorate([
  31776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31777. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  31778. __decorate([
  31779. BABYLON.serialize("useEmissiveAsIllumination")
  31780. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  31781. __decorate([
  31782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31783. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31784. __decorate([
  31785. BABYLON.serialize("linkEmissiveWithDiffuse")
  31786. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  31787. __decorate([
  31788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31789. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  31790. __decorate([
  31791. BABYLON.serialize("useSpecularOverAlpha")
  31792. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  31793. __decorate([
  31794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31795. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  31796. __decorate([
  31797. BABYLON.serialize("useReflectionOverAlpha")
  31798. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  31799. __decorate([
  31800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31801. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  31802. __decorate([
  31803. BABYLON.serialize("disableLighting")
  31804. ], StandardMaterial.prototype, "_disableLighting", void 0);
  31805. __decorate([
  31806. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31807. ], StandardMaterial.prototype, "disableLighting", void 0);
  31808. __decorate([
  31809. BABYLON.serialize("useParallax")
  31810. ], StandardMaterial.prototype, "_useParallax", void 0);
  31811. __decorate([
  31812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31813. ], StandardMaterial.prototype, "useParallax", void 0);
  31814. __decorate([
  31815. BABYLON.serialize("useParallaxOcclusion")
  31816. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  31817. __decorate([
  31818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31819. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  31820. __decorate([
  31821. BABYLON.serialize()
  31822. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  31823. __decorate([
  31824. BABYLON.serialize("roughness")
  31825. ], StandardMaterial.prototype, "_roughness", void 0);
  31826. __decorate([
  31827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31828. ], StandardMaterial.prototype, "roughness", void 0);
  31829. __decorate([
  31830. BABYLON.serialize()
  31831. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  31832. __decorate([
  31833. BABYLON.serialize()
  31834. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  31835. __decorate([
  31836. BABYLON.serialize("useLightmapAsShadowmap")
  31837. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  31838. __decorate([
  31839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31840. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31841. __decorate([
  31842. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  31843. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  31844. __decorate([
  31845. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31846. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  31847. __decorate([
  31848. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  31849. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  31850. __decorate([
  31851. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31852. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  31853. __decorate([
  31854. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  31855. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  31856. __decorate([
  31857. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31858. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  31859. __decorate([
  31860. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  31861. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  31862. __decorate([
  31863. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31864. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  31865. __decorate([
  31866. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  31867. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  31868. __decorate([
  31869. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31870. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  31871. __decorate([
  31872. BABYLON.serialize("useReflectionFresnelFromSpecular")
  31873. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  31874. __decorate([
  31875. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31876. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  31877. __decorate([
  31878. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  31879. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  31880. __decorate([
  31881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31882. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  31883. __decorate([
  31884. BABYLON.serialize("maxSimultaneousLights")
  31885. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  31886. __decorate([
  31887. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31888. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  31889. __decorate([
  31890. BABYLON.serialize("invertNormalMapX")
  31891. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  31892. __decorate([
  31893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31894. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  31895. __decorate([
  31896. BABYLON.serialize("invertNormalMapY")
  31897. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  31898. __decorate([
  31899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31900. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  31901. __decorate([
  31902. BABYLON.serialize("twoSidedLighting")
  31903. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  31904. __decorate([
  31905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31906. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  31907. __decorate([
  31908. BABYLON.serialize()
  31909. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  31910. return StandardMaterial;
  31911. }(BABYLON.PushMaterial));
  31912. BABYLON.StandardMaterial = StandardMaterial;
  31913. })(BABYLON || (BABYLON = {}));
  31914. //# sourceMappingURL=babylon.standardMaterial.js.map
  31915. var BABYLON;
  31916. (function (BABYLON) {
  31917. var PBRMaterialDefines = (function (_super) {
  31918. __extends(PBRMaterialDefines, _super);
  31919. function PBRMaterialDefines() {
  31920. var _this = _super.call(this) || this;
  31921. _this.PBR = true;
  31922. _this.MAINUV1 = false;
  31923. _this.MAINUV2 = false;
  31924. _this.UV1 = false;
  31925. _this.UV2 = false;
  31926. _this.ALBEDO = false;
  31927. _this.ALBEDODIRECTUV = 0;
  31928. _this.VERTEXCOLOR = false;
  31929. _this.AMBIENT = false;
  31930. _this.AMBIENTDIRECTUV = 0;
  31931. _this.AMBIENTINGRAYSCALE = false;
  31932. _this.OPACITY = false;
  31933. _this.VERTEXALPHA = false;
  31934. _this.OPACITYDIRECTUV = 0;
  31935. _this.OPACITYRGB = false;
  31936. _this.ALPHATEST = false;
  31937. _this.DEPTHPREPASS = false;
  31938. _this.ALPHABLEND = false;
  31939. _this.ALPHAFROMALBEDO = false;
  31940. _this.ALPHATESTVALUE = 0.5;
  31941. _this.SPECULAROVERALPHA = false;
  31942. _this.RADIANCEOVERALPHA = false;
  31943. _this.ALPHAFRESNEL = false;
  31944. _this.PREMULTIPLYALPHA = false;
  31945. _this.EMISSIVE = false;
  31946. _this.EMISSIVEDIRECTUV = 0;
  31947. _this.REFLECTIVITY = false;
  31948. _this.REFLECTIVITYDIRECTUV = 0;
  31949. _this.SPECULARTERM = false;
  31950. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  31951. _this.MICROSURFACEAUTOMATIC = false;
  31952. _this.LODBASEDMICROSFURACE = false;
  31953. _this.MICROSURFACEMAP = false;
  31954. _this.MICROSURFACEMAPDIRECTUV = 0;
  31955. _this.METALLICWORKFLOW = false;
  31956. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  31957. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  31958. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  31959. _this.AOSTOREINMETALMAPRED = false;
  31960. _this.ENVIRONMENTBRDF = false;
  31961. _this.NORMAL = false;
  31962. _this.TANGENT = false;
  31963. _this.BUMP = false;
  31964. _this.BUMPDIRECTUV = 0;
  31965. _this.PARALLAX = false;
  31966. _this.PARALLAXOCCLUSION = false;
  31967. _this.NORMALXYSCALE = true;
  31968. _this.LIGHTMAP = false;
  31969. _this.LIGHTMAPDIRECTUV = 0;
  31970. _this.USELIGHTMAPASSHADOWMAP = false;
  31971. _this.REFLECTION = false;
  31972. _this.REFLECTIONMAP_3D = false;
  31973. _this.REFLECTIONMAP_SPHERICAL = false;
  31974. _this.REFLECTIONMAP_PLANAR = false;
  31975. _this.REFLECTIONMAP_CUBIC = false;
  31976. _this.REFLECTIONMAP_PROJECTION = false;
  31977. _this.REFLECTIONMAP_SKYBOX = false;
  31978. _this.REFLECTIONMAP_EXPLICIT = false;
  31979. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31980. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31981. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31982. _this.INVERTCUBICMAP = false;
  31983. _this.USESPHERICALFROMREFLECTIONMAP = false;
  31984. _this.USESPHERICALINFRAGMENT = false;
  31985. _this.REFLECTIONMAP_OPPOSITEZ = false;
  31986. _this.LODINREFLECTIONALPHA = false;
  31987. _this.GAMMAREFLECTION = false;
  31988. _this.REFRACTION = false;
  31989. _this.REFRACTIONMAP_3D = false;
  31990. _this.REFRACTIONMAP_OPPOSITEZ = false;
  31991. _this.LODINREFRACTIONALPHA = false;
  31992. _this.GAMMAREFRACTION = false;
  31993. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  31994. _this.INSTANCES = false;
  31995. _this.NUM_BONE_INFLUENCERS = 0;
  31996. _this.BonesPerMesh = 0;
  31997. _this.MORPHTARGETS = false;
  31998. _this.MORPHTARGETS_NORMAL = false;
  31999. _this.MORPHTARGETS_TANGENT = false;
  32000. _this.NUM_MORPH_INFLUENCERS = 0;
  32001. _this.IMAGEPROCESSING = false;
  32002. _this.VIGNETTE = false;
  32003. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  32004. _this.VIGNETTEBLENDMODEOPAQUE = false;
  32005. _this.TONEMAPPING = false;
  32006. _this.CONTRAST = false;
  32007. _this.COLORCURVES = false;
  32008. _this.COLORGRADING = false;
  32009. _this.SAMPLER3DGREENDEPTH = false;
  32010. _this.SAMPLER3DBGRMAP = false;
  32011. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  32012. _this.EXPOSURE = false;
  32013. _this.USEPHYSICALLIGHTFALLOFF = false;
  32014. _this.TWOSIDEDLIGHTING = false;
  32015. _this.SHADOWFLOAT = false;
  32016. _this.USERIGHTHANDEDSYSTEM = false;
  32017. _this.CLIPPLANE = false;
  32018. _this.POINTSIZE = false;
  32019. _this.FOG = false;
  32020. _this.LOGARITHMICDEPTH = false;
  32021. _this.FORCENORMALFORWARD = false;
  32022. _this.rebuild();
  32023. return _this;
  32024. }
  32025. PBRMaterialDefines.prototype.reset = function () {
  32026. _super.prototype.reset.call(this);
  32027. this.ALPHATESTVALUE = 0.5;
  32028. this.PBR = true;
  32029. };
  32030. return PBRMaterialDefines;
  32031. }(BABYLON.MaterialDefines));
  32032. /**
  32033. * The Physically based material base class of BJS.
  32034. *
  32035. * This offers the main features of a standard PBR material.
  32036. * For more information, please refer to the documentation :
  32037. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  32038. */
  32039. var PBRBaseMaterial = (function (_super) {
  32040. __extends(PBRBaseMaterial, _super);
  32041. /**
  32042. * Instantiates a new PBRMaterial instance.
  32043. *
  32044. * @param name The material name
  32045. * @param scene The scene the material will be use in.
  32046. */
  32047. function PBRBaseMaterial(name, scene) {
  32048. var _this = _super.call(this, name, scene) || this;
  32049. /**
  32050. * Intensity of the direct lights e.g. the four lights available in your scene.
  32051. * This impacts both the direct diffuse and specular highlights.
  32052. */
  32053. _this._directIntensity = 1.0;
  32054. /**
  32055. * Intensity of the emissive part of the material.
  32056. * This helps controlling the emissive effect without modifying the emissive color.
  32057. */
  32058. _this._emissiveIntensity = 1.0;
  32059. /**
  32060. * Intensity of the environment e.g. how much the environment will light the object
  32061. * either through harmonics for rough material or through the refelction for shiny ones.
  32062. */
  32063. _this._environmentIntensity = 1.0;
  32064. /**
  32065. * This is a special control allowing the reduction of the specular highlights coming from the
  32066. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  32067. */
  32068. _this._specularIntensity = 1.0;
  32069. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  32070. /**
  32071. * Debug Control allowing disabling the bump map on this material.
  32072. */
  32073. _this._disableBumpMap = false;
  32074. /**
  32075. * AKA Occlusion Texture Intensity in other nomenclature.
  32076. */
  32077. _this._ambientTextureStrength = 1.0;
  32078. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  32079. /**
  32080. * AKA Diffuse Color in other nomenclature.
  32081. */
  32082. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  32083. /**
  32084. * AKA Specular Color in other nomenclature.
  32085. */
  32086. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  32087. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  32088. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  32089. /**
  32090. * AKA Glossiness in other nomenclature.
  32091. */
  32092. _this._microSurface = 0.9;
  32093. /**
  32094. * source material index of refraction (IOR)' / 'destination material IOR.
  32095. */
  32096. _this._indexOfRefraction = 0.66;
  32097. /**
  32098. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  32099. */
  32100. _this._invertRefractionY = false;
  32101. /**
  32102. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  32103. * Materials half opaque for instance using refraction could benefit from this control.
  32104. */
  32105. _this._linkRefractionWithTransparency = false;
  32106. _this._useLightmapAsShadowmap = false;
  32107. /**
  32108. * Specifies that the alpha is coming form the albedo channel alpha channel.
  32109. */
  32110. _this._useAlphaFromAlbedoTexture = false;
  32111. /**
  32112. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  32113. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  32114. */
  32115. _this._useSpecularOverAlpha = true;
  32116. /**
  32117. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  32118. */
  32119. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  32120. /**
  32121. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  32122. */
  32123. _this._useRoughnessFromMetallicTextureAlpha = true;
  32124. /**
  32125. * Specifies if the metallic texture contains the roughness information in its green channel.
  32126. */
  32127. _this._useRoughnessFromMetallicTextureGreen = false;
  32128. /**
  32129. * Specifies if the metallic texture contains the metallness information in its blue channel.
  32130. */
  32131. _this._useMetallnessFromMetallicTextureBlue = false;
  32132. /**
  32133. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  32134. */
  32135. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  32136. /**
  32137. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  32138. */
  32139. _this._useAmbientInGrayScale = false;
  32140. /**
  32141. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  32142. * The material will try to infer what glossiness each pixel should be.
  32143. */
  32144. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  32145. /**
  32146. * BJS is using an harcoded light falloff based on a manually sets up range.
  32147. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  32148. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  32149. */
  32150. _this._usePhysicalLightFalloff = true;
  32151. /**
  32152. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  32153. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  32154. */
  32155. _this._useRadianceOverAlpha = true;
  32156. /**
  32157. * Allows using the bump map in parallax mode.
  32158. */
  32159. _this._useParallax = false;
  32160. /**
  32161. * Allows using the bump map in parallax occlusion mode.
  32162. */
  32163. _this._useParallaxOcclusion = false;
  32164. /**
  32165. * Controls the scale bias of the parallax mode.
  32166. */
  32167. _this._parallaxScaleBias = 0.05;
  32168. /**
  32169. * If sets to true, disables all the lights affecting the material.
  32170. */
  32171. _this._disableLighting = false;
  32172. /**
  32173. * Number of Simultaneous lights allowed on the material.
  32174. */
  32175. _this._maxSimultaneousLights = 4;
  32176. /**
  32177. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  32178. */
  32179. _this._invertNormalMapX = false;
  32180. /**
  32181. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  32182. */
  32183. _this._invertNormalMapY = false;
  32184. /**
  32185. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32186. */
  32187. _this._twoSidedLighting = false;
  32188. /**
  32189. * Defines the alpha limits in alpha test mode.
  32190. */
  32191. _this._alphaCutOff = 0.4;
  32192. /**
  32193. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32194. */
  32195. _this._forceAlphaTest = false;
  32196. /**
  32197. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32198. * in your scene composition.
  32199. */
  32200. _this._preMultiplyAlpha = false;
  32201. /**
  32202. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32203. * And/Or occlude the blended part.
  32204. */
  32205. _this._useAlphaFresnel = false;
  32206. /**
  32207. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  32208. * from cos thetav and roughness:
  32209. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  32210. */
  32211. _this._environmentBRDFTexture = null;
  32212. /**
  32213. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32214. */
  32215. _this._forceIrradianceInFragment = false;
  32216. /**
  32217. * Force normal to face away from face.
  32218. * (Temporary internal fix to remove before 3.1)
  32219. */
  32220. _this._forceNormalForward = false;
  32221. _this._renderTargets = new BABYLON.SmartArray(16);
  32222. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  32223. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  32224. _this._tempColor = new BABYLON.Color3();
  32225. // Setup the default processing configuration to the scene.
  32226. _this._attachImageProcessingConfiguration(null);
  32227. _this.getRenderTargetTextures = function () {
  32228. _this._renderTargets.reset();
  32229. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  32230. _this._renderTargets.push(_this._reflectionTexture);
  32231. }
  32232. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  32233. _this._renderTargets.push(_this._refractionTexture);
  32234. }
  32235. return _this._renderTargets;
  32236. };
  32237. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32238. return _this;
  32239. }
  32240. /**
  32241. * Attaches a new image processing configuration to the PBR Material.
  32242. * @param configuration
  32243. */
  32244. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  32245. var _this = this;
  32246. if (configuration === this._imageProcessingConfiguration) {
  32247. return;
  32248. }
  32249. // Detaches observer.
  32250. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32251. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32252. }
  32253. // Pick the scene configuration if needed.
  32254. if (!configuration) {
  32255. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  32256. }
  32257. else {
  32258. this._imageProcessingConfiguration = configuration;
  32259. }
  32260. // Attaches observer.
  32261. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  32262. _this._markAllSubMeshesAsImageProcessingDirty();
  32263. });
  32264. };
  32265. PBRBaseMaterial.prototype.getClassName = function () {
  32266. return "PBRBaseMaterial";
  32267. };
  32268. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  32269. get: function () {
  32270. return this._useLogarithmicDepth;
  32271. },
  32272. set: function (value) {
  32273. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  32274. },
  32275. enumerable: true,
  32276. configurable: true
  32277. });
  32278. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  32279. if (this._linkRefractionWithTransparency) {
  32280. return false;
  32281. }
  32282. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  32283. };
  32284. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  32285. if (this._forceAlphaTest) {
  32286. return true;
  32287. }
  32288. if (this._linkRefractionWithTransparency) {
  32289. return false;
  32290. }
  32291. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  32292. };
  32293. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32294. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  32295. };
  32296. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  32297. return this._albedoTexture;
  32298. };
  32299. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32300. if (this.isFrozen) {
  32301. if (this._wasPreviouslyReady) {
  32302. return true;
  32303. }
  32304. }
  32305. if (!subMesh._materialDefines) {
  32306. subMesh._materialDefines = new PBRMaterialDefines();
  32307. }
  32308. var scene = this.getScene();
  32309. var defines = subMesh._materialDefines;
  32310. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  32311. if (defines._renderId === scene.getRenderId()) {
  32312. return true;
  32313. }
  32314. }
  32315. var engine = scene.getEngine();
  32316. // Lights
  32317. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  32318. defines._needNormals = true;
  32319. // Textures
  32320. if (defines._areTexturesDirty) {
  32321. defines._needUVs = false;
  32322. if (scene.texturesEnabled) {
  32323. if (scene.getEngine().getCaps().textureLOD) {
  32324. defines.LODBASEDMICROSFURACE = true;
  32325. }
  32326. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32327. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  32328. return false;
  32329. }
  32330. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  32331. }
  32332. else {
  32333. defines.ALBEDO = false;
  32334. }
  32335. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32336. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  32337. return false;
  32338. }
  32339. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  32340. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  32341. }
  32342. else {
  32343. defines.AMBIENT = false;
  32344. }
  32345. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32346. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  32347. return false;
  32348. }
  32349. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  32350. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  32351. }
  32352. else {
  32353. defines.OPACITY = false;
  32354. }
  32355. var reflectionTexture = this._getReflectionTexture();
  32356. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32357. if (!reflectionTexture.isReadyOrNotBlocking()) {
  32358. return false;
  32359. }
  32360. defines.REFLECTION = true;
  32361. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  32362. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  32363. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32364. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  32365. defines.INVERTCUBICMAP = true;
  32366. }
  32367. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  32368. switch (reflectionTexture.coordinatesMode) {
  32369. case BABYLON.Texture.CUBIC_MODE:
  32370. case BABYLON.Texture.INVCUBIC_MODE:
  32371. defines.REFLECTIONMAP_CUBIC = true;
  32372. break;
  32373. case BABYLON.Texture.EXPLICIT_MODE:
  32374. defines.REFLECTIONMAP_EXPLICIT = true;
  32375. break;
  32376. case BABYLON.Texture.PLANAR_MODE:
  32377. defines.REFLECTIONMAP_PLANAR = true;
  32378. break;
  32379. case BABYLON.Texture.PROJECTION_MODE:
  32380. defines.REFLECTIONMAP_PROJECTION = true;
  32381. break;
  32382. case BABYLON.Texture.SKYBOX_MODE:
  32383. defines.REFLECTIONMAP_SKYBOX = true;
  32384. break;
  32385. case BABYLON.Texture.SPHERICAL_MODE:
  32386. defines.REFLECTIONMAP_SPHERICAL = true;
  32387. break;
  32388. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  32389. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  32390. break;
  32391. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  32392. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  32393. break;
  32394. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  32395. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  32396. break;
  32397. }
  32398. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  32399. if (reflectionTexture.sphericalPolynomial) {
  32400. defines.USESPHERICALFROMREFLECTIONMAP = true;
  32401. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  32402. defines.USESPHERICALINFRAGMENT = true;
  32403. }
  32404. }
  32405. }
  32406. }
  32407. else {
  32408. defines.REFLECTION = false;
  32409. defines.REFLECTIONMAP_3D = false;
  32410. defines.REFLECTIONMAP_SPHERICAL = false;
  32411. defines.REFLECTIONMAP_PLANAR = false;
  32412. defines.REFLECTIONMAP_CUBIC = false;
  32413. defines.REFLECTIONMAP_PROJECTION = false;
  32414. defines.REFLECTIONMAP_SKYBOX = false;
  32415. defines.REFLECTIONMAP_EXPLICIT = false;
  32416. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32417. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32418. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32419. defines.INVERTCUBICMAP = false;
  32420. defines.USESPHERICALFROMREFLECTIONMAP = false;
  32421. defines.USESPHERICALINFRAGMENT = false;
  32422. defines.REFLECTIONMAP_OPPOSITEZ = false;
  32423. defines.LODINREFLECTIONALPHA = false;
  32424. defines.GAMMAREFLECTION = false;
  32425. }
  32426. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32427. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  32428. return false;
  32429. }
  32430. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  32431. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  32432. }
  32433. else {
  32434. defines.LIGHTMAP = false;
  32435. }
  32436. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32437. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  32438. return false;
  32439. }
  32440. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  32441. }
  32442. else {
  32443. defines.EMISSIVE = false;
  32444. }
  32445. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32446. if (this._metallicTexture) {
  32447. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  32448. return false;
  32449. }
  32450. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  32451. defines.METALLICWORKFLOW = true;
  32452. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  32453. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  32454. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  32455. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  32456. }
  32457. else if (this._reflectivityTexture) {
  32458. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  32459. return false;
  32460. }
  32461. defines.METALLICWORKFLOW = false;
  32462. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  32463. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  32464. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  32465. }
  32466. else {
  32467. defines.METALLICWORKFLOW = false;
  32468. defines.REFLECTIVITY = false;
  32469. }
  32470. if (this._microSurfaceTexture) {
  32471. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  32472. return false;
  32473. }
  32474. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  32475. }
  32476. else {
  32477. defines.MICROSURFACEMAP = false;
  32478. }
  32479. }
  32480. else {
  32481. defines.REFLECTIVITY = false;
  32482. defines.MICROSURFACEMAP = false;
  32483. }
  32484. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32485. // Bump texure can not be none blocking.
  32486. if (!this._bumpTexture.isReady()) {
  32487. return false;
  32488. }
  32489. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  32490. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32491. defines.PARALLAX = true;
  32492. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  32493. }
  32494. else {
  32495. defines.PARALLAX = false;
  32496. }
  32497. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  32498. }
  32499. else {
  32500. defines.BUMP = false;
  32501. }
  32502. var refractionTexture = this._getRefractionTexture();
  32503. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32504. if (!refractionTexture.isReadyOrNotBlocking()) {
  32505. return false;
  32506. }
  32507. defines.REFRACTION = true;
  32508. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  32509. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  32510. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  32511. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32512. if (this._linkRefractionWithTransparency) {
  32513. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  32514. }
  32515. }
  32516. else {
  32517. defines.REFRACTION = false;
  32518. }
  32519. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32520. // This is blocking.
  32521. if (!this._environmentBRDFTexture.isReady()) {
  32522. return false;
  32523. }
  32524. defines.ENVIRONMENTBRDF = true;
  32525. }
  32526. if (this._shouldUseAlphaFromAlbedoTexture()) {
  32527. defines.ALPHAFROMALBEDO = true;
  32528. }
  32529. }
  32530. if (this._useSpecularOverAlpha) {
  32531. defines.SPECULAROVERALPHA = true;
  32532. }
  32533. if (this._usePhysicalLightFalloff) {
  32534. defines.USEPHYSICALLIGHTFALLOFF = true;
  32535. }
  32536. if (this._useRadianceOverAlpha) {
  32537. defines.RADIANCEOVERALPHA = true;
  32538. }
  32539. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  32540. defines.METALLICWORKFLOW = true;
  32541. }
  32542. if (!this.backFaceCulling && this._twoSidedLighting) {
  32543. defines.TWOSIDEDLIGHTING = true;
  32544. }
  32545. defines.ALPHATESTVALUE = this._alphaCutOff;
  32546. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  32547. defines.ALPHABLEND = this.needAlphaBlending();
  32548. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  32549. }
  32550. if (defines._areImageProcessingDirty) {
  32551. if (!this._imageProcessingConfiguration.isReady()) {
  32552. return false;
  32553. }
  32554. this._imageProcessingConfiguration.prepareDefines(defines);
  32555. }
  32556. defines.FORCENORMALFORWARD = this._forceNormalForward;
  32557. // Misc.
  32558. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32559. // Values that need to be evaluated on every frame
  32560. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  32561. // Attribs
  32562. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  32563. if (mesh) {
  32564. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32565. mesh.createNormals(true);
  32566. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  32567. }
  32568. }
  32569. }
  32570. // Get correct effect
  32571. if (defines.isDirty) {
  32572. defines.markAsProcessed();
  32573. scene.resetCachedMaterial();
  32574. // Fallbacks
  32575. var fallbacks = new BABYLON.EffectFallbacks();
  32576. if (defines.ENVIRONMENTBRDF) {
  32577. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  32578. }
  32579. if (defines.REFLECTION) {
  32580. fallbacks.addFallback(0, "REFLECTION");
  32581. }
  32582. if (defines.REFRACTION) {
  32583. fallbacks.addFallback(0, "REFRACTION");
  32584. }
  32585. if (defines.REFLECTIVITY) {
  32586. fallbacks.addFallback(0, "REFLECTIVITY");
  32587. }
  32588. if (defines.BUMP) {
  32589. fallbacks.addFallback(0, "BUMP");
  32590. }
  32591. if (defines.PARALLAX) {
  32592. fallbacks.addFallback(1, "PARALLAX");
  32593. }
  32594. if (defines.PARALLAXOCCLUSION) {
  32595. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32596. }
  32597. if (defines.SPECULAROVERALPHA) {
  32598. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32599. }
  32600. if (defines.FOG) {
  32601. fallbacks.addFallback(1, "FOG");
  32602. }
  32603. if (defines.POINTSIZE) {
  32604. fallbacks.addFallback(0, "POINTSIZE");
  32605. }
  32606. if (defines.LOGARITHMICDEPTH) {
  32607. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32608. }
  32609. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32610. if (defines.SPECULARTERM) {
  32611. fallbacks.addFallback(0, "SPECULARTERM");
  32612. }
  32613. if (defines.NUM_BONE_INFLUENCERS > 0) {
  32614. fallbacks.addCPUSkinningFallback(0, mesh);
  32615. }
  32616. //Attributes
  32617. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32618. if (defines.NORMAL) {
  32619. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32620. }
  32621. if (defines.TANGENT) {
  32622. attribs.push(BABYLON.VertexBuffer.TangentKind);
  32623. }
  32624. if (defines.UV1) {
  32625. attribs.push(BABYLON.VertexBuffer.UVKind);
  32626. }
  32627. if (defines.UV2) {
  32628. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32629. }
  32630. if (defines.VERTEXCOLOR) {
  32631. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32632. }
  32633. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32634. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32635. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32636. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  32637. "vFogInfos", "vFogColor", "pointSize",
  32638. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32639. "mBones",
  32640. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32641. "vLightingIntensity",
  32642. "logarithmicDepthConstant",
  32643. "vSphericalX", "vSphericalY", "vSphericalZ",
  32644. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  32645. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  32646. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  32647. "vNormalReoderParams"
  32648. ];
  32649. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  32650. "bumpSampler", "lightmapSampler", "opacitySampler",
  32651. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  32652. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  32653. "microSurfaceSampler", "environmentBrdfSampler"];
  32654. var uniformBuffers = ["Material", "Scene"];
  32655. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32656. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32657. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32658. uniformsNames: uniforms,
  32659. uniformBuffersNames: uniformBuffers,
  32660. samplers: samplers,
  32661. defines: defines,
  32662. maxSimultaneousLights: this._maxSimultaneousLights
  32663. });
  32664. var onCompiled = function (effect) {
  32665. if (this.onCompiled) {
  32666. this.onCompiled(effect);
  32667. }
  32668. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  32669. }.bind(this);
  32670. var join = defines.toString();
  32671. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  32672. attributes: attribs,
  32673. uniformsNames: uniforms,
  32674. uniformBuffersNames: uniformBuffers,
  32675. samplers: samplers,
  32676. defines: join,
  32677. fallbacks: fallbacks,
  32678. onCompiled: onCompiled,
  32679. onError: this.onError,
  32680. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32681. }, engine), defines);
  32682. this.buildUniformLayout();
  32683. }
  32684. if (!subMesh.effect.isReady()) {
  32685. return false;
  32686. }
  32687. defines._renderId = scene.getRenderId();
  32688. this._wasPreviouslyReady = true;
  32689. return true;
  32690. };
  32691. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  32692. // Order is important !
  32693. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  32694. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  32695. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32696. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32697. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32698. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  32699. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  32700. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32701. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32702. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32703. this._uniformBuffer.addUniform("albedoMatrix", 16);
  32704. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32705. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32706. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32707. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32708. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  32709. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  32710. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32711. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  32712. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32713. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32714. this._uniformBuffer.addUniform("vReflectionColor", 3);
  32715. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  32716. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  32717. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  32718. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  32719. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  32720. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32721. this._uniformBuffer.addUniform("pointSize", 1);
  32722. this._uniformBuffer.create();
  32723. };
  32724. PBRBaseMaterial.prototype.unbind = function () {
  32725. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32726. this._uniformBuffer.setTexture("reflectionSampler", null);
  32727. }
  32728. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32729. this._uniformBuffer.setTexture("refractionSampler", null);
  32730. }
  32731. _super.prototype.unbind.call(this);
  32732. };
  32733. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32734. this._activeEffect.setMatrix("world", world);
  32735. };
  32736. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32737. var scene = this.getScene();
  32738. var defines = subMesh._materialDefines;
  32739. if (!defines) {
  32740. return;
  32741. }
  32742. var effect = subMesh.effect;
  32743. this._activeEffect = effect;
  32744. // Matrices
  32745. this.bindOnlyWorldMatrix(world);
  32746. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32747. // Bones
  32748. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  32749. if (mustRebind) {
  32750. this._uniformBuffer.bindToEffect(effect, "Material");
  32751. this.bindViewProjection(effect);
  32752. var reflectionTexture = this._getReflectionTexture();
  32753. var refractionTexture = this._getRefractionTexture();
  32754. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32755. // Texture uniforms
  32756. if (scene.texturesEnabled) {
  32757. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32758. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  32759. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  32760. }
  32761. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32762. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  32763. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32764. }
  32765. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32766. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32767. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32768. }
  32769. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32770. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  32771. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  32772. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  32773. var polynomials = reflectionTexture.sphericalPolynomial;
  32774. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  32775. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  32776. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  32777. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  32778. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  32779. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  32780. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  32781. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  32782. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  32783. }
  32784. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  32785. }
  32786. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32787. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32788. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32789. }
  32790. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32791. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32792. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32793. }
  32794. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32795. if (this._metallicTexture) {
  32796. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  32797. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  32798. }
  32799. else if (this._reflectivityTexture) {
  32800. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  32801. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  32802. }
  32803. if (this._microSurfaceTexture) {
  32804. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  32805. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  32806. }
  32807. }
  32808. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32809. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  32810. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32811. if (scene._mirroredCameraPosition) {
  32812. 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);
  32813. }
  32814. else {
  32815. 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);
  32816. }
  32817. }
  32818. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32819. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  32820. var depth = 1.0;
  32821. if (!refractionTexture.isCube) {
  32822. if (refractionTexture.depth) {
  32823. depth = refractionTexture.depth;
  32824. }
  32825. }
  32826. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  32827. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  32828. }
  32829. }
  32830. // Point size
  32831. if (this.pointsCloud) {
  32832. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32833. }
  32834. // Colors
  32835. if (defines.METALLICWORKFLOW) {
  32836. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  32837. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  32838. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  32839. }
  32840. else {
  32841. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  32842. }
  32843. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  32844. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  32845. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  32846. // Misc
  32847. this._lightingInfos.x = this._directIntensity;
  32848. this._lightingInfos.y = this._emissiveIntensity;
  32849. this._lightingInfos.z = this._environmentIntensity;
  32850. this._lightingInfos.w = this._specularIntensity;
  32851. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  32852. }
  32853. // Textures
  32854. if (scene.texturesEnabled) {
  32855. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32856. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  32857. }
  32858. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32859. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  32860. }
  32861. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32862. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  32863. }
  32864. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32865. if (defines.LODBASEDMICROSFURACE) {
  32866. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  32867. }
  32868. else {
  32869. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  32870. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  32871. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  32872. }
  32873. }
  32874. if (defines.ENVIRONMENTBRDF) {
  32875. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  32876. }
  32877. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32878. if (defines.LODBASEDMICROSFURACE) {
  32879. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  32880. }
  32881. else {
  32882. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  32883. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  32884. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  32885. }
  32886. }
  32887. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32888. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  32889. }
  32890. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32891. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  32892. }
  32893. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32894. if (this._metallicTexture) {
  32895. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  32896. }
  32897. else if (this._reflectivityTexture) {
  32898. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  32899. }
  32900. if (this._microSurfaceTexture) {
  32901. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  32902. }
  32903. }
  32904. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32905. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  32906. }
  32907. }
  32908. // Clip plane
  32909. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  32910. // Colors
  32911. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  32912. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  32913. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  32914. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  32915. }
  32916. if (mustRebind || !this.isFrozen) {
  32917. // Lights
  32918. if (scene.lightsEnabled && !this._disableLighting) {
  32919. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  32920. }
  32921. // View
  32922. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  32923. this.bindView(effect);
  32924. }
  32925. // Fog
  32926. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  32927. // Morph targets
  32928. if (defines.NUM_MORPH_INFLUENCERS) {
  32929. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  32930. }
  32931. // image processing
  32932. this._imageProcessingConfiguration.bind(this._activeEffect);
  32933. // Log. depth
  32934. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  32935. }
  32936. this._uniformBuffer.update();
  32937. this._afterBind(mesh);
  32938. scene = null;
  32939. };
  32940. PBRBaseMaterial.prototype.getAnimatables = function () {
  32941. var results = [];
  32942. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  32943. results.push(this._albedoTexture);
  32944. }
  32945. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  32946. results.push(this._ambientTexture);
  32947. }
  32948. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  32949. results.push(this._opacityTexture);
  32950. }
  32951. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  32952. results.push(this._reflectionTexture);
  32953. }
  32954. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  32955. results.push(this._emissiveTexture);
  32956. }
  32957. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  32958. results.push(this._metallicTexture);
  32959. }
  32960. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  32961. results.push(this._reflectivityTexture);
  32962. }
  32963. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  32964. results.push(this._bumpTexture);
  32965. }
  32966. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  32967. results.push(this._lightmapTexture);
  32968. }
  32969. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  32970. results.push(this._refractionTexture);
  32971. }
  32972. return results;
  32973. };
  32974. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  32975. if (this._reflectionTexture) {
  32976. return this._reflectionTexture;
  32977. }
  32978. return this.getScene().environmentTexture;
  32979. };
  32980. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  32981. if (this._refractionTexture) {
  32982. return this._refractionTexture;
  32983. }
  32984. if (this._linkRefractionWithTransparency) {
  32985. return this.getScene().environmentTexture;
  32986. }
  32987. return null;
  32988. };
  32989. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32990. if (forceDisposeTextures) {
  32991. if (this._albedoTexture) {
  32992. this._albedoTexture.dispose();
  32993. }
  32994. if (this._ambientTexture) {
  32995. this._ambientTexture.dispose();
  32996. }
  32997. if (this._opacityTexture) {
  32998. this._opacityTexture.dispose();
  32999. }
  33000. if (this._reflectionTexture) {
  33001. this._reflectionTexture.dispose();
  33002. }
  33003. if (this._environmentBRDFTexture) {
  33004. this._environmentBRDFTexture.dispose();
  33005. }
  33006. if (this._emissiveTexture) {
  33007. this._emissiveTexture.dispose();
  33008. }
  33009. if (this._metallicTexture) {
  33010. this._metallicTexture.dispose();
  33011. }
  33012. if (this._reflectivityTexture) {
  33013. this._reflectivityTexture.dispose();
  33014. }
  33015. if (this._bumpTexture) {
  33016. this._bumpTexture.dispose();
  33017. }
  33018. if (this._lightmapTexture) {
  33019. this._lightmapTexture.dispose();
  33020. }
  33021. if (this._refractionTexture) {
  33022. this._refractionTexture.dispose();
  33023. }
  33024. }
  33025. this._renderTargets.dispose();
  33026. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33027. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33028. }
  33029. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  33030. };
  33031. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  33032. __decorate([
  33033. BABYLON.serializeAsImageProcessingConfiguration()
  33034. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  33035. __decorate([
  33036. BABYLON.serialize()
  33037. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  33038. return PBRBaseMaterial;
  33039. }(BABYLON.PushMaterial));
  33040. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  33041. })(BABYLON || (BABYLON = {}));
  33042. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  33043. var BABYLON;
  33044. (function (BABYLON) {
  33045. var Internals;
  33046. (function (Internals) {
  33047. /**
  33048. * The Physically based simple base material of BJS.
  33049. *
  33050. * This enables better naming and convention enforcements on top of the pbrMaterial.
  33051. * It is used as the base class for both the specGloss and metalRough conventions.
  33052. */
  33053. var PBRBaseSimpleMaterial = (function (_super) {
  33054. __extends(PBRBaseSimpleMaterial, _super);
  33055. /**
  33056. * Instantiates a new PBRMaterial instance.
  33057. *
  33058. * @param name The material name
  33059. * @param scene The scene the material will be use in.
  33060. */
  33061. function PBRBaseSimpleMaterial(name, scene) {
  33062. var _this = _super.call(this, name, scene) || this;
  33063. /**
  33064. * Number of Simultaneous lights allowed on the material.
  33065. */
  33066. _this.maxSimultaneousLights = 4;
  33067. /**
  33068. * If sets to true, disables all the lights affecting the material.
  33069. */
  33070. _this.disableLighting = false;
  33071. /**
  33072. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33073. */
  33074. _this.invertNormalMapX = false;
  33075. /**
  33076. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33077. */
  33078. _this.invertNormalMapY = false;
  33079. /**
  33080. * Emissivie color used to self-illuminate the model.
  33081. */
  33082. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33083. /**
  33084. * Occlusion Channel Strenght.
  33085. */
  33086. _this.occlusionStrength = 1.0;
  33087. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  33088. _this._useAmbientInGrayScale = true;
  33089. return _this;
  33090. }
  33091. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  33092. /**
  33093. * Gets the current transparency mode.
  33094. */
  33095. get: function () {
  33096. return this._transparencyMode;
  33097. },
  33098. /**
  33099. * Sets the transparency mode of the material.
  33100. */
  33101. set: function (value) {
  33102. if (this._transparencyMode === value) {
  33103. return;
  33104. }
  33105. this._transparencyMode = value;
  33106. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  33107. this._forceAlphaTest = true;
  33108. }
  33109. else {
  33110. this._forceAlphaTest = false;
  33111. }
  33112. this._markAllSubMeshesAsTexturesDirty();
  33113. },
  33114. enumerable: true,
  33115. configurable: true
  33116. });
  33117. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  33118. /**
  33119. * Gets the current double sided mode.
  33120. */
  33121. get: function () {
  33122. return this._twoSidedLighting;
  33123. },
  33124. /**
  33125. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33126. */
  33127. set: function (value) {
  33128. if (this._twoSidedLighting === value) {
  33129. return;
  33130. }
  33131. this._twoSidedLighting = value;
  33132. this.backFaceCulling = !value;
  33133. this._markAllSubMeshesAsTexturesDirty();
  33134. },
  33135. enumerable: true,
  33136. configurable: true
  33137. });
  33138. /**
  33139. * Specifies wether or not the alpha value of the albedo texture should be used.
  33140. */
  33141. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  33142. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  33143. };
  33144. /**
  33145. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  33146. */
  33147. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  33148. if (this._linkRefractionWithTransparency) {
  33149. return false;
  33150. }
  33151. return (this.alpha < 1.0) ||
  33152. (this._shouldUseAlphaFromAlbedoTexture() &&
  33153. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  33154. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  33155. };
  33156. /**
  33157. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  33158. */
  33159. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  33160. if (this._linkRefractionWithTransparency) {
  33161. return false;
  33162. }
  33163. return this._shouldUseAlphaFromAlbedoTexture() &&
  33164. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  33165. };
  33166. /**
  33167. * Return the active textures of the material.
  33168. */
  33169. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  33170. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33171. if (this.environmentTexture) {
  33172. activeTextures.push(this.environmentTexture);
  33173. }
  33174. if (this.normalTexture) {
  33175. activeTextures.push(this.normalTexture);
  33176. }
  33177. if (this.emissiveTexture) {
  33178. activeTextures.push(this.emissiveTexture);
  33179. }
  33180. if (this.occlusionTexture) {
  33181. activeTextures.push(this.occlusionTexture);
  33182. }
  33183. return activeTextures;
  33184. };
  33185. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  33186. return "PBRBaseSimpleMaterial";
  33187. };
  33188. __decorate([
  33189. BABYLON.serialize(),
  33190. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33191. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  33192. __decorate([
  33193. BABYLON.serialize(),
  33194. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33195. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  33196. __decorate([
  33197. BABYLON.serializeAsTexture(),
  33198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  33199. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  33200. __decorate([
  33201. BABYLON.serialize(),
  33202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33203. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  33204. __decorate([
  33205. BABYLON.serialize(),
  33206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33207. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  33208. __decorate([
  33209. BABYLON.serializeAsTexture(),
  33210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  33211. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  33212. __decorate([
  33213. BABYLON.serializeAsColor3("emissive"),
  33214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33215. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  33216. __decorate([
  33217. BABYLON.serializeAsTexture(),
  33218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33219. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  33220. __decorate([
  33221. BABYLON.serialize(),
  33222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  33223. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  33224. __decorate([
  33225. BABYLON.serializeAsTexture(),
  33226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  33227. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  33228. __decorate([
  33229. BABYLON.serialize(),
  33230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  33231. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  33232. __decorate([
  33233. BABYLON.serialize()
  33234. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  33235. __decorate([
  33236. BABYLON.serialize()
  33237. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  33238. return PBRBaseSimpleMaterial;
  33239. }(BABYLON.PBRBaseMaterial));
  33240. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  33241. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33242. })(BABYLON || (BABYLON = {}));
  33243. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  33244. var BABYLON;
  33245. (function (BABYLON) {
  33246. /**
  33247. * The Physically based material of BJS.
  33248. *
  33249. * This offers the main features of a standard PBR material.
  33250. * For more information, please refer to the documentation :
  33251. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  33252. */
  33253. var PBRMaterial = (function (_super) {
  33254. __extends(PBRMaterial, _super);
  33255. /**
  33256. * Instantiates a new PBRMaterial instance.
  33257. *
  33258. * @param name The material name
  33259. * @param scene The scene the material will be use in.
  33260. */
  33261. function PBRMaterial(name, scene) {
  33262. var _this = _super.call(this, name, scene) || this;
  33263. /**
  33264. * Intensity of the direct lights e.g. the four lights available in your scene.
  33265. * This impacts both the direct diffuse and specular highlights.
  33266. */
  33267. _this.directIntensity = 1.0;
  33268. /**
  33269. * Intensity of the emissive part of the material.
  33270. * This helps controlling the emissive effect without modifying the emissive color.
  33271. */
  33272. _this.emissiveIntensity = 1.0;
  33273. /**
  33274. * Intensity of the environment e.g. how much the environment will light the object
  33275. * either through harmonics for rough material or through the refelction for shiny ones.
  33276. */
  33277. _this.environmentIntensity = 1.0;
  33278. /**
  33279. * This is a special control allowing the reduction of the specular highlights coming from the
  33280. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  33281. */
  33282. _this.specularIntensity = 1.0;
  33283. /**
  33284. * Debug Control allowing disabling the bump map on this material.
  33285. */
  33286. _this.disableBumpMap = false;
  33287. /**
  33288. * AKA Occlusion Texture Intensity in other nomenclature.
  33289. */
  33290. _this.ambientTextureStrength = 1.0;
  33291. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33292. /**
  33293. * AKA Diffuse Color in other nomenclature.
  33294. */
  33295. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  33296. /**
  33297. * AKA Specular Color in other nomenclature.
  33298. */
  33299. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  33300. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  33301. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33302. /**
  33303. * AKA Glossiness in other nomenclature.
  33304. */
  33305. _this.microSurface = 1.0;
  33306. /**
  33307. * source material index of refraction (IOR)' / 'destination material IOR.
  33308. */
  33309. _this.indexOfRefraction = 0.66;
  33310. /**
  33311. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  33312. */
  33313. _this.invertRefractionY = false;
  33314. /**
  33315. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  33316. * Materials half opaque for instance using refraction could benefit from this control.
  33317. */
  33318. _this.linkRefractionWithTransparency = false;
  33319. _this.useLightmapAsShadowmap = false;
  33320. /**
  33321. * Specifies that the alpha is coming form the albedo channel alpha channel.
  33322. */
  33323. _this.useAlphaFromAlbedoTexture = false;
  33324. /**
  33325. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  33326. */
  33327. _this.forceAlphaTest = false;
  33328. /**
  33329. * Defines the alpha limits in alpha test mode.
  33330. */
  33331. _this.alphaCutOff = 0.4;
  33332. /**
  33333. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  33334. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  33335. */
  33336. _this.useSpecularOverAlpha = true;
  33337. /**
  33338. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  33339. */
  33340. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  33341. /**
  33342. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  33343. */
  33344. _this.useRoughnessFromMetallicTextureAlpha = true;
  33345. /**
  33346. * Specifies if the metallic texture contains the roughness information in its green channel.
  33347. */
  33348. _this.useRoughnessFromMetallicTextureGreen = false;
  33349. /**
  33350. * Specifies if the metallic texture contains the metallness information in its blue channel.
  33351. */
  33352. _this.useMetallnessFromMetallicTextureBlue = false;
  33353. /**
  33354. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  33355. */
  33356. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  33357. /**
  33358. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  33359. */
  33360. _this.useAmbientInGrayScale = false;
  33361. /**
  33362. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  33363. * The material will try to infer what glossiness each pixel should be.
  33364. */
  33365. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  33366. /**
  33367. * BJS is using an harcoded light falloff based on a manually sets up range.
  33368. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  33369. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  33370. */
  33371. _this.usePhysicalLightFalloff = true;
  33372. /**
  33373. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  33374. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  33375. */
  33376. _this.useRadianceOverAlpha = true;
  33377. /**
  33378. * Allows using the bump map in parallax mode.
  33379. */
  33380. _this.useParallax = false;
  33381. /**
  33382. * Allows using the bump map in parallax occlusion mode.
  33383. */
  33384. _this.useParallaxOcclusion = false;
  33385. /**
  33386. * Controls the scale bias of the parallax mode.
  33387. */
  33388. _this.parallaxScaleBias = 0.05;
  33389. /**
  33390. * If sets to true, disables all the lights affecting the material.
  33391. */
  33392. _this.disableLighting = false;
  33393. /**
  33394. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  33395. */
  33396. _this.forceIrradianceInFragment = false;
  33397. /**
  33398. * Number of Simultaneous lights allowed on the material.
  33399. */
  33400. _this.maxSimultaneousLights = 4;
  33401. /**
  33402. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33403. */
  33404. _this.invertNormalMapX = false;
  33405. /**
  33406. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33407. */
  33408. _this.invertNormalMapY = false;
  33409. /**
  33410. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33411. */
  33412. _this.twoSidedLighting = false;
  33413. /**
  33414. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  33415. * in your scene composition.
  33416. */
  33417. _this.preMultiplyAlpha = false;
  33418. /**
  33419. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33420. * And/Or occlude the blended part.
  33421. */
  33422. _this.useAlphaFresnel = false;
  33423. /**
  33424. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33425. * And/Or occlude the blended part.
  33426. */
  33427. _this.environmentBRDFTexture = null;
  33428. /**
  33429. * Force normal to face away from face.
  33430. * (Temporary internal fix to remove before 3.1)
  33431. */
  33432. _this.forceNormalForward = false;
  33433. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  33434. return _this;
  33435. }
  33436. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  33437. /**
  33438. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  33439. */
  33440. get: function () {
  33441. return this._PBRMATERIAL_OPAQUE;
  33442. },
  33443. enumerable: true,
  33444. configurable: true
  33445. });
  33446. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  33447. /**
  33448. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  33449. */
  33450. get: function () {
  33451. return this._PBRMATERIAL_ALPHATEST;
  33452. },
  33453. enumerable: true,
  33454. configurable: true
  33455. });
  33456. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  33457. /**
  33458. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33459. */
  33460. get: function () {
  33461. return this._PBRMATERIAL_ALPHABLEND;
  33462. },
  33463. enumerable: true,
  33464. configurable: true
  33465. });
  33466. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  33467. /**
  33468. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33469. * They are also discarded below the alpha cutoff threshold to improve performances.
  33470. */
  33471. get: function () {
  33472. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  33473. },
  33474. enumerable: true,
  33475. configurable: true
  33476. });
  33477. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  33478. /**
  33479. * Gets the image processing configuration used either in this material.
  33480. */
  33481. get: function () {
  33482. return this._imageProcessingConfiguration;
  33483. },
  33484. /**
  33485. * Sets the Default image processing configuration used either in the this material.
  33486. *
  33487. * If sets to null, the scene one is in use.
  33488. */
  33489. set: function (value) {
  33490. this._attachImageProcessingConfiguration(value);
  33491. // Ensure the effect will be rebuilt.
  33492. this._markAllSubMeshesAsTexturesDirty();
  33493. },
  33494. enumerable: true,
  33495. configurable: true
  33496. });
  33497. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  33498. /**
  33499. * Gets wether the color curves effect is enabled.
  33500. */
  33501. get: function () {
  33502. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33503. },
  33504. /**
  33505. * Sets wether the color curves effect is enabled.
  33506. */
  33507. set: function (value) {
  33508. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33509. },
  33510. enumerable: true,
  33511. configurable: true
  33512. });
  33513. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  33514. /**
  33515. * Gets wether the color grading effect is enabled.
  33516. */
  33517. get: function () {
  33518. return this.imageProcessingConfiguration.colorGradingEnabled;
  33519. },
  33520. /**
  33521. * Gets wether the color grading effect is enabled.
  33522. */
  33523. set: function (value) {
  33524. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33525. },
  33526. enumerable: true,
  33527. configurable: true
  33528. });
  33529. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  33530. /**
  33531. * Gets wether tonemapping is enabled or not.
  33532. */
  33533. get: function () {
  33534. return this._imageProcessingConfiguration.toneMappingEnabled;
  33535. },
  33536. /**
  33537. * Sets wether tonemapping is enabled or not
  33538. */
  33539. set: function (value) {
  33540. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33541. },
  33542. enumerable: true,
  33543. configurable: true
  33544. });
  33545. ;
  33546. ;
  33547. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  33548. /**
  33549. * The camera exposure used on this material.
  33550. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33551. * This corresponds to a photographic exposure.
  33552. */
  33553. get: function () {
  33554. return this._imageProcessingConfiguration.exposure;
  33555. },
  33556. /**
  33557. * The camera exposure used on this material.
  33558. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33559. * This corresponds to a photographic exposure.
  33560. */
  33561. set: function (value) {
  33562. this._imageProcessingConfiguration.exposure = value;
  33563. },
  33564. enumerable: true,
  33565. configurable: true
  33566. });
  33567. ;
  33568. ;
  33569. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  33570. /**
  33571. * Gets The camera contrast used on this material.
  33572. */
  33573. get: function () {
  33574. return this._imageProcessingConfiguration.contrast;
  33575. },
  33576. /**
  33577. * Sets The camera contrast used on this material.
  33578. */
  33579. set: function (value) {
  33580. this._imageProcessingConfiguration.contrast = value;
  33581. },
  33582. enumerable: true,
  33583. configurable: true
  33584. });
  33585. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  33586. /**
  33587. * Gets the Color Grading 2D Lookup Texture.
  33588. */
  33589. get: function () {
  33590. return this._imageProcessingConfiguration.colorGradingTexture;
  33591. },
  33592. /**
  33593. * Sets the Color Grading 2D Lookup Texture.
  33594. */
  33595. set: function (value) {
  33596. this._imageProcessingConfiguration.colorGradingTexture = value;
  33597. },
  33598. enumerable: true,
  33599. configurable: true
  33600. });
  33601. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  33602. /**
  33603. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33604. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33605. * 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;
  33606. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33607. */
  33608. get: function () {
  33609. return this._imageProcessingConfiguration.colorCurves;
  33610. },
  33611. /**
  33612. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33613. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33614. * 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;
  33615. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33616. */
  33617. set: function (value) {
  33618. this._imageProcessingConfiguration.colorCurves = value;
  33619. },
  33620. enumerable: true,
  33621. configurable: true
  33622. });
  33623. PBRMaterial.prototype.getClassName = function () {
  33624. return "PBRMaterial";
  33625. };
  33626. PBRMaterial.prototype.getActiveTextures = function () {
  33627. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33628. if (this._albedoTexture) {
  33629. activeTextures.push(this._albedoTexture);
  33630. }
  33631. if (this._ambientTexture) {
  33632. activeTextures.push(this._ambientTexture);
  33633. }
  33634. if (this._opacityTexture) {
  33635. activeTextures.push(this._opacityTexture);
  33636. }
  33637. if (this._reflectionTexture) {
  33638. activeTextures.push(this._reflectionTexture);
  33639. }
  33640. if (this._emissiveTexture) {
  33641. activeTextures.push(this._emissiveTexture);
  33642. }
  33643. if (this._reflectivityTexture) {
  33644. activeTextures.push(this._reflectivityTexture);
  33645. }
  33646. if (this._metallicTexture) {
  33647. activeTextures.push(this._metallicTexture);
  33648. }
  33649. if (this._microSurfaceTexture) {
  33650. activeTextures.push(this._microSurfaceTexture);
  33651. }
  33652. if (this._bumpTexture) {
  33653. activeTextures.push(this._bumpTexture);
  33654. }
  33655. if (this._lightmapTexture) {
  33656. activeTextures.push(this._lightmapTexture);
  33657. }
  33658. if (this._refractionTexture) {
  33659. activeTextures.push(this._refractionTexture);
  33660. }
  33661. return activeTextures;
  33662. };
  33663. PBRMaterial.prototype.hasTexture = function (texture) {
  33664. if (_super.prototype.hasTexture.call(this, texture)) {
  33665. return true;
  33666. }
  33667. if (this._albedoTexture === texture) {
  33668. return true;
  33669. }
  33670. if (this._ambientTexture === texture) {
  33671. return true;
  33672. }
  33673. if (this._opacityTexture === texture) {
  33674. return true;
  33675. }
  33676. if (this._reflectionTexture === texture) {
  33677. return true;
  33678. }
  33679. if (this._reflectivityTexture === texture) {
  33680. return true;
  33681. }
  33682. if (this._metallicTexture === texture) {
  33683. return true;
  33684. }
  33685. if (this._microSurfaceTexture === texture) {
  33686. return true;
  33687. }
  33688. if (this._bumpTexture === texture) {
  33689. return true;
  33690. }
  33691. if (this._lightmapTexture === texture) {
  33692. return true;
  33693. }
  33694. if (this._refractionTexture === texture) {
  33695. return true;
  33696. }
  33697. return false;
  33698. };
  33699. PBRMaterial.prototype.clone = function (name) {
  33700. var _this = this;
  33701. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  33702. };
  33703. PBRMaterial.prototype.serialize = function () {
  33704. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33705. serializationObject.customType = "BABYLON.PBRMaterial";
  33706. return serializationObject;
  33707. };
  33708. // Statics
  33709. PBRMaterial.Parse = function (source, scene, rootUrl) {
  33710. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  33711. };
  33712. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  33713. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  33714. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  33715. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  33716. __decorate([
  33717. BABYLON.serialize(),
  33718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33719. ], PBRMaterial.prototype, "directIntensity", void 0);
  33720. __decorate([
  33721. BABYLON.serialize(),
  33722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33723. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  33724. __decorate([
  33725. BABYLON.serialize(),
  33726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33727. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  33728. __decorate([
  33729. BABYLON.serialize(),
  33730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33731. ], PBRMaterial.prototype, "specularIntensity", void 0);
  33732. __decorate([
  33733. BABYLON.serialize(),
  33734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33735. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  33736. __decorate([
  33737. BABYLON.serializeAsTexture(),
  33738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33739. ], PBRMaterial.prototype, "albedoTexture", void 0);
  33740. __decorate([
  33741. BABYLON.serializeAsTexture(),
  33742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33743. ], PBRMaterial.prototype, "ambientTexture", void 0);
  33744. __decorate([
  33745. BABYLON.serialize(),
  33746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33747. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  33748. __decorate([
  33749. BABYLON.serializeAsTexture(),
  33750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33751. ], PBRMaterial.prototype, "opacityTexture", void 0);
  33752. __decorate([
  33753. BABYLON.serializeAsTexture(),
  33754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33755. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  33756. __decorate([
  33757. BABYLON.serializeAsTexture(),
  33758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33759. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  33760. __decorate([
  33761. BABYLON.serializeAsTexture(),
  33762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33763. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  33764. __decorate([
  33765. BABYLON.serializeAsTexture(),
  33766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33767. ], PBRMaterial.prototype, "metallicTexture", void 0);
  33768. __decorate([
  33769. BABYLON.serialize(),
  33770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33771. ], PBRMaterial.prototype, "metallic", void 0);
  33772. __decorate([
  33773. BABYLON.serialize(),
  33774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33775. ], PBRMaterial.prototype, "roughness", void 0);
  33776. __decorate([
  33777. BABYLON.serializeAsTexture(),
  33778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33779. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  33780. __decorate([
  33781. BABYLON.serializeAsTexture(),
  33782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33783. ], PBRMaterial.prototype, "bumpTexture", void 0);
  33784. __decorate([
  33785. BABYLON.serializeAsTexture(),
  33786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  33787. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  33788. __decorate([
  33789. BABYLON.serializeAsTexture(),
  33790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33791. ], PBRMaterial.prototype, "refractionTexture", void 0);
  33792. __decorate([
  33793. BABYLON.serializeAsColor3("ambient"),
  33794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33795. ], PBRMaterial.prototype, "ambientColor", void 0);
  33796. __decorate([
  33797. BABYLON.serializeAsColor3("albedo"),
  33798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33799. ], PBRMaterial.prototype, "albedoColor", void 0);
  33800. __decorate([
  33801. BABYLON.serializeAsColor3("reflectivity"),
  33802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33803. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  33804. __decorate([
  33805. BABYLON.serializeAsColor3("reflection"),
  33806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33807. ], PBRMaterial.prototype, "reflectionColor", void 0);
  33808. __decorate([
  33809. BABYLON.serializeAsColor3("emissive"),
  33810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33811. ], PBRMaterial.prototype, "emissiveColor", void 0);
  33812. __decorate([
  33813. BABYLON.serialize(),
  33814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33815. ], PBRMaterial.prototype, "microSurface", void 0);
  33816. __decorate([
  33817. BABYLON.serialize(),
  33818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33819. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  33820. __decorate([
  33821. BABYLON.serialize(),
  33822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33823. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  33824. __decorate([
  33825. BABYLON.serialize(),
  33826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33827. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  33828. __decorate([
  33829. BABYLON.serialize(),
  33830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33831. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33832. __decorate([
  33833. BABYLON.serialize(),
  33834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33835. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  33836. __decorate([
  33837. BABYLON.serialize(),
  33838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33839. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  33840. __decorate([
  33841. BABYLON.serialize(),
  33842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33843. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  33844. __decorate([
  33845. BABYLON.serialize(),
  33846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33847. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  33848. __decorate([
  33849. BABYLON.serialize(),
  33850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33851. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  33852. __decorate([
  33853. BABYLON.serialize(),
  33854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33855. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  33856. __decorate([
  33857. BABYLON.serialize(),
  33858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33859. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  33860. __decorate([
  33861. BABYLON.serialize(),
  33862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33863. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  33864. __decorate([
  33865. BABYLON.serialize(),
  33866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33867. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  33868. __decorate([
  33869. BABYLON.serialize(),
  33870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33871. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  33872. __decorate([
  33873. BABYLON.serialize(),
  33874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33875. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  33876. __decorate([
  33877. BABYLON.serialize(),
  33878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33879. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  33880. __decorate([
  33881. BABYLON.serialize(),
  33882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33883. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  33884. __decorate([
  33885. BABYLON.serialize(),
  33886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33887. ], PBRMaterial.prototype, "useParallax", void 0);
  33888. __decorate([
  33889. BABYLON.serialize(),
  33890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33891. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  33892. __decorate([
  33893. BABYLON.serialize(),
  33894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33895. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  33896. __decorate([
  33897. BABYLON.serialize(),
  33898. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33899. ], PBRMaterial.prototype, "disableLighting", void 0);
  33900. __decorate([
  33901. BABYLON.serialize(),
  33902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33903. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  33904. __decorate([
  33905. BABYLON.serialize(),
  33906. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33907. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  33908. __decorate([
  33909. BABYLON.serialize(),
  33910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33911. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  33912. __decorate([
  33913. BABYLON.serialize(),
  33914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33915. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  33916. __decorate([
  33917. BABYLON.serialize(),
  33918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33919. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  33920. __decorate([
  33921. BABYLON.serialize(),
  33922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33923. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  33924. __decorate([
  33925. BABYLON.serialize(),
  33926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33927. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  33928. __decorate([
  33929. BABYLON.serializeAsTexture(),
  33930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33931. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  33932. __decorate([
  33933. BABYLON.serialize(),
  33934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33935. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  33936. return PBRMaterial;
  33937. }(BABYLON.PBRBaseMaterial));
  33938. BABYLON.PBRMaterial = PBRMaterial;
  33939. })(BABYLON || (BABYLON = {}));
  33940. //# sourceMappingURL=babylon.pbrMaterial.js.map
  33941. var BABYLON;
  33942. (function (BABYLON) {
  33943. /**
  33944. * The PBR material of BJS following the metal roughness convention.
  33945. *
  33946. * This fits to the PBR convention in the GLTF definition:
  33947. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  33948. */
  33949. var PBRMetallicRoughnessMaterial = (function (_super) {
  33950. __extends(PBRMetallicRoughnessMaterial, _super);
  33951. /**
  33952. * Instantiates a new PBRMetalRoughnessMaterial instance.
  33953. *
  33954. * @param name The material name
  33955. * @param scene The scene the material will be use in.
  33956. */
  33957. function PBRMetallicRoughnessMaterial(name, scene) {
  33958. var _this = _super.call(this, name, scene) || this;
  33959. _this._useRoughnessFromMetallicTextureAlpha = false;
  33960. _this._useRoughnessFromMetallicTextureGreen = true;
  33961. _this._useMetallnessFromMetallicTextureBlue = true;
  33962. return _this;
  33963. }
  33964. /**
  33965. * Return the currrent class name of the material.
  33966. */
  33967. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  33968. return "PBRMetallicRoughnessMaterial";
  33969. };
  33970. /**
  33971. * Return the active textures of the material.
  33972. */
  33973. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  33974. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33975. if (this.baseTexture) {
  33976. activeTextures.push(this.baseTexture);
  33977. }
  33978. if (this.metallicRoughnessTexture) {
  33979. activeTextures.push(this.metallicRoughnessTexture);
  33980. }
  33981. return activeTextures;
  33982. };
  33983. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  33984. if (_super.prototype.hasTexture.call(this, texture)) {
  33985. return true;
  33986. }
  33987. if (this.baseTexture === texture) {
  33988. return true;
  33989. }
  33990. if (this.metallicRoughnessTexture === texture) {
  33991. return true;
  33992. }
  33993. return false;
  33994. };
  33995. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  33996. var _this = this;
  33997. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  33998. };
  33999. /**
  34000. * Serialize the material to a parsable JSON object.
  34001. */
  34002. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  34003. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34004. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  34005. return serializationObject;
  34006. };
  34007. /**
  34008. * Parses a JSON object correponding to the serialize function.
  34009. */
  34010. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  34011. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  34012. };
  34013. __decorate([
  34014. BABYLON.serializeAsColor3(),
  34015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  34016. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  34017. __decorate([
  34018. BABYLON.serializeAsTexture(),
  34019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  34020. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  34021. __decorate([
  34022. BABYLON.serialize(),
  34023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34024. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  34025. __decorate([
  34026. BABYLON.serialize(),
  34027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34028. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  34029. __decorate([
  34030. BABYLON.serializeAsTexture(),
  34031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  34032. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  34033. return PBRMetallicRoughnessMaterial;
  34034. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  34035. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  34036. })(BABYLON || (BABYLON = {}));
  34037. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  34038. var BABYLON;
  34039. (function (BABYLON) {
  34040. /**
  34041. * The PBR material of BJS following the specular glossiness convention.
  34042. *
  34043. * This fits to the PBR convention in the GLTF definition:
  34044. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  34045. */
  34046. var PBRSpecularGlossinessMaterial = (function (_super) {
  34047. __extends(PBRSpecularGlossinessMaterial, _super);
  34048. /**
  34049. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  34050. *
  34051. * @param name The material name
  34052. * @param scene The scene the material will be use in.
  34053. */
  34054. function PBRSpecularGlossinessMaterial(name, scene) {
  34055. var _this = _super.call(this, name, scene) || this;
  34056. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  34057. return _this;
  34058. }
  34059. /**
  34060. * Return the currrent class name of the material.
  34061. */
  34062. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  34063. return "PBRSpecularGlossinessMaterial";
  34064. };
  34065. /**
  34066. * Return the active textures of the material.
  34067. */
  34068. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  34069. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34070. if (this.diffuseTexture) {
  34071. activeTextures.push(this.diffuseTexture);
  34072. }
  34073. if (this.specularGlossinessTexture) {
  34074. activeTextures.push(this.specularGlossinessTexture);
  34075. }
  34076. return activeTextures;
  34077. };
  34078. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  34079. if (_super.prototype.hasTexture.call(this, texture)) {
  34080. return true;
  34081. }
  34082. if (this.diffuseTexture === texture) {
  34083. return true;
  34084. }
  34085. if (this.specularGlossinessTexture === texture) {
  34086. return true;
  34087. }
  34088. return false;
  34089. };
  34090. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  34091. var _this = this;
  34092. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  34093. };
  34094. /**
  34095. * Serialize the material to a parsable JSON object.
  34096. */
  34097. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  34098. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34099. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  34100. return serializationObject;
  34101. };
  34102. /**
  34103. * Parses a JSON object correponding to the serialize function.
  34104. */
  34105. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  34106. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  34107. };
  34108. __decorate([
  34109. BABYLON.serializeAsColor3("diffuse"),
  34110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  34111. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  34112. __decorate([
  34113. BABYLON.serializeAsTexture(),
  34114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  34115. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  34116. __decorate([
  34117. BABYLON.serializeAsColor3("specular"),
  34118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  34119. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  34120. __decorate([
  34121. BABYLON.serialize(),
  34122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  34123. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  34124. __decorate([
  34125. BABYLON.serializeAsTexture(),
  34126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  34127. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  34128. return PBRSpecularGlossinessMaterial;
  34129. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  34130. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  34131. })(BABYLON || (BABYLON = {}));
  34132. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  34133. var BABYLON;
  34134. (function (BABYLON) {
  34135. BABYLON.CameraInputTypes = {};
  34136. var CameraInputsManager = (function () {
  34137. function CameraInputsManager(camera) {
  34138. this.attached = {};
  34139. this.camera = camera;
  34140. this.checkInputs = function () { };
  34141. }
  34142. CameraInputsManager.prototype.add = function (input) {
  34143. var type = input.getSimpleName();
  34144. if (this.attached[type]) {
  34145. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  34146. return;
  34147. }
  34148. this.attached[type] = input;
  34149. input.camera = this.camera;
  34150. //for checkInputs, we are dynamically creating a function
  34151. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  34152. if (input.checkInputs) {
  34153. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34154. }
  34155. if (this.attachedElement) {
  34156. input.attachControl(this.attachedElement);
  34157. }
  34158. };
  34159. CameraInputsManager.prototype.remove = function (inputToRemove) {
  34160. for (var cam in this.attached) {
  34161. var input = this.attached[cam];
  34162. if (input === inputToRemove) {
  34163. input.detachControl(this.attachedElement);
  34164. input.camera = null;
  34165. delete this.attached[cam];
  34166. this.rebuildInputCheck();
  34167. }
  34168. }
  34169. };
  34170. CameraInputsManager.prototype.removeByType = function (inputType) {
  34171. for (var cam in this.attached) {
  34172. var input = this.attached[cam];
  34173. if (input.getClassName() === inputType) {
  34174. input.detachControl(this.attachedElement);
  34175. input.camera = null;
  34176. delete this.attached[cam];
  34177. this.rebuildInputCheck();
  34178. }
  34179. }
  34180. };
  34181. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  34182. var current = this.checkInputs;
  34183. return function () {
  34184. current();
  34185. fn();
  34186. };
  34187. };
  34188. CameraInputsManager.prototype.attachInput = function (input) {
  34189. input.attachControl(this.attachedElement, this.noPreventDefault);
  34190. };
  34191. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  34192. if (this.attachedElement) {
  34193. return;
  34194. }
  34195. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  34196. this.attachedElement = element;
  34197. this.noPreventDefault = noPreventDefault;
  34198. for (var cam in this.attached) {
  34199. var input = this.attached[cam];
  34200. this.attached[cam].attachControl(element, noPreventDefault);
  34201. }
  34202. };
  34203. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  34204. if (disconnect === void 0) { disconnect = false; }
  34205. if (this.attachedElement !== element) {
  34206. return;
  34207. }
  34208. for (var cam in this.attached) {
  34209. var input = this.attached[cam];
  34210. this.attached[cam].detachControl(element);
  34211. if (disconnect) {
  34212. this.attached[cam].camera = null;
  34213. }
  34214. }
  34215. this.attachedElement = null;
  34216. };
  34217. CameraInputsManager.prototype.rebuildInputCheck = function () {
  34218. this.checkInputs = function () { };
  34219. for (var cam in this.attached) {
  34220. var input = this.attached[cam];
  34221. if (input.checkInputs) {
  34222. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34223. }
  34224. }
  34225. };
  34226. CameraInputsManager.prototype.clear = function () {
  34227. if (this.attachedElement) {
  34228. this.detachElement(this.attachedElement, true);
  34229. }
  34230. this.attached = {};
  34231. this.attachedElement = null;
  34232. this.checkInputs = function () { };
  34233. };
  34234. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  34235. var inputs = {};
  34236. for (var cam in this.attached) {
  34237. var input = this.attached[cam];
  34238. var res = BABYLON.SerializationHelper.Serialize(input);
  34239. inputs[input.getClassName()] = res;
  34240. }
  34241. serializedCamera.inputsmgr = inputs;
  34242. };
  34243. CameraInputsManager.prototype.parse = function (parsedCamera) {
  34244. var parsedInputs = parsedCamera.inputsmgr;
  34245. if (parsedInputs) {
  34246. this.clear();
  34247. for (var n in parsedInputs) {
  34248. var construct = BABYLON.CameraInputTypes[n];
  34249. if (construct) {
  34250. var parsedinput = parsedInputs[n];
  34251. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  34252. this.add(input);
  34253. }
  34254. }
  34255. }
  34256. else {
  34257. //2016-03-08 this part is for managing backward compatibility
  34258. for (var n in this.attached) {
  34259. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  34260. if (construct) {
  34261. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  34262. this.remove(this.attached[n]);
  34263. this.add(input);
  34264. }
  34265. }
  34266. }
  34267. };
  34268. return CameraInputsManager;
  34269. }());
  34270. BABYLON.CameraInputsManager = CameraInputsManager;
  34271. })(BABYLON || (BABYLON = {}));
  34272. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  34273. var BABYLON;
  34274. (function (BABYLON) {
  34275. var FreeCameraMouseInput = (function () {
  34276. function FreeCameraMouseInput(touchEnabled) {
  34277. if (touchEnabled === void 0) { touchEnabled = true; }
  34278. this.touchEnabled = touchEnabled;
  34279. this.buttons = [0, 1, 2];
  34280. this.angularSensibility = 2000.0;
  34281. }
  34282. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  34283. var _this = this;
  34284. var engine = this.camera.getEngine();
  34285. if (!this._pointerInput) {
  34286. this._pointerInput = function (p, s) {
  34287. var evt = p.event;
  34288. if (engine.isInVRExclusivePointerMode) {
  34289. return;
  34290. }
  34291. if (!_this.touchEnabled && evt.pointerType === "touch") {
  34292. return;
  34293. }
  34294. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34295. return;
  34296. }
  34297. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34298. try {
  34299. evt.srcElement.setPointerCapture(evt.pointerId);
  34300. }
  34301. catch (e) {
  34302. //Nothing to do with the error. Execution will continue.
  34303. }
  34304. _this.previousPosition = {
  34305. x: evt.clientX,
  34306. y: evt.clientY
  34307. };
  34308. if (!noPreventDefault) {
  34309. evt.preventDefault();
  34310. element.focus();
  34311. }
  34312. }
  34313. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34314. try {
  34315. evt.srcElement.releasePointerCapture(evt.pointerId);
  34316. }
  34317. catch (e) {
  34318. //Nothing to do with the error.
  34319. }
  34320. _this.previousPosition = null;
  34321. if (!noPreventDefault) {
  34322. evt.preventDefault();
  34323. }
  34324. }
  34325. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34326. if (!_this.previousPosition || engine.isPointerLock) {
  34327. return;
  34328. }
  34329. var offsetX = evt.clientX - _this.previousPosition.x;
  34330. var offsetY = evt.clientY - _this.previousPosition.y;
  34331. if (_this.camera.getScene().useRightHandedSystem) {
  34332. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34333. }
  34334. else {
  34335. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34336. }
  34337. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34338. _this.previousPosition = {
  34339. x: evt.clientX,
  34340. y: evt.clientY
  34341. };
  34342. if (!noPreventDefault) {
  34343. evt.preventDefault();
  34344. }
  34345. }
  34346. };
  34347. }
  34348. this._onMouseMove = function (evt) {
  34349. if (!engine.isPointerLock) {
  34350. return;
  34351. }
  34352. if (engine.isInVRExclusivePointerMode) {
  34353. return;
  34354. }
  34355. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34356. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34357. if (_this.camera.getScene().useRightHandedSystem) {
  34358. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34359. }
  34360. else {
  34361. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34362. }
  34363. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34364. _this.previousPosition = null;
  34365. if (!noPreventDefault) {
  34366. evt.preventDefault();
  34367. }
  34368. };
  34369. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  34370. element.addEventListener("mousemove", this._onMouseMove, false);
  34371. };
  34372. FreeCameraMouseInput.prototype.detachControl = function (element) {
  34373. if (this._observer && element) {
  34374. this.camera.getScene().onPointerObservable.remove(this._observer);
  34375. element.removeEventListener("mousemove", this._onMouseMove);
  34376. this._observer = null;
  34377. this._onMouseMove = null;
  34378. this.previousPosition = null;
  34379. }
  34380. };
  34381. FreeCameraMouseInput.prototype.getClassName = function () {
  34382. return "FreeCameraMouseInput";
  34383. };
  34384. FreeCameraMouseInput.prototype.getSimpleName = function () {
  34385. return "mouse";
  34386. };
  34387. __decorate([
  34388. BABYLON.serialize()
  34389. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  34390. __decorate([
  34391. BABYLON.serialize()
  34392. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  34393. return FreeCameraMouseInput;
  34394. }());
  34395. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  34396. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  34397. })(BABYLON || (BABYLON = {}));
  34398. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  34399. var BABYLON;
  34400. (function (BABYLON) {
  34401. var FreeCameraKeyboardMoveInput = (function () {
  34402. function FreeCameraKeyboardMoveInput() {
  34403. this._keys = [];
  34404. this.keysUp = [38];
  34405. this.keysDown = [40];
  34406. this.keysLeft = [37];
  34407. this.keysRight = [39];
  34408. }
  34409. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34410. var _this = this;
  34411. if (this._onCanvasBlurObserver) {
  34412. return;
  34413. }
  34414. this._scene = this.camera.getScene();
  34415. this._engine = this._scene.getEngine();
  34416. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  34417. _this._keys = [];
  34418. });
  34419. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  34420. var evt = info.event;
  34421. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  34422. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34423. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34424. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34425. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34426. var index = _this._keys.indexOf(evt.keyCode);
  34427. if (index === -1) {
  34428. _this._keys.push(evt.keyCode);
  34429. }
  34430. if (!noPreventDefault) {
  34431. evt.preventDefault();
  34432. }
  34433. }
  34434. }
  34435. else {
  34436. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34437. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34438. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34439. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34440. var index = _this._keys.indexOf(evt.keyCode);
  34441. if (index >= 0) {
  34442. _this._keys.splice(index, 1);
  34443. }
  34444. if (!noPreventDefault) {
  34445. evt.preventDefault();
  34446. }
  34447. }
  34448. }
  34449. });
  34450. };
  34451. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34452. if (this._scene) {
  34453. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  34454. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  34455. this._onKeyboardObserver = null;
  34456. this._onCanvasBlurObserver = null;
  34457. }
  34458. this._keys = [];
  34459. };
  34460. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34461. if (this._onKeyboardObserver) {
  34462. var camera = this.camera;
  34463. // Keyboard
  34464. for (var index = 0; index < this._keys.length; index++) {
  34465. var keyCode = this._keys[index];
  34466. var speed = camera._computeLocalCameraSpeed();
  34467. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34468. camera._localDirection.copyFromFloats(-speed, 0, 0);
  34469. }
  34470. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34471. camera._localDirection.copyFromFloats(0, 0, speed);
  34472. }
  34473. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34474. camera._localDirection.copyFromFloats(speed, 0, 0);
  34475. }
  34476. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34477. camera._localDirection.copyFromFloats(0, 0, -speed);
  34478. }
  34479. if (camera.getScene().useRightHandedSystem) {
  34480. camera._localDirection.z *= -1;
  34481. }
  34482. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  34483. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  34484. camera.cameraDirection.addInPlace(camera._transformedDirection);
  34485. }
  34486. }
  34487. };
  34488. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  34489. return "FreeCameraKeyboardMoveInput";
  34490. };
  34491. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  34492. this._keys = [];
  34493. };
  34494. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34495. return "keyboard";
  34496. };
  34497. __decorate([
  34498. BABYLON.serialize()
  34499. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34500. __decorate([
  34501. BABYLON.serialize()
  34502. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34503. __decorate([
  34504. BABYLON.serialize()
  34505. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34506. __decorate([
  34507. BABYLON.serialize()
  34508. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34509. return FreeCameraKeyboardMoveInput;
  34510. }());
  34511. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  34512. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  34513. })(BABYLON || (BABYLON = {}));
  34514. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  34515. var BABYLON;
  34516. (function (BABYLON) {
  34517. var FreeCameraInputsManager = (function (_super) {
  34518. __extends(FreeCameraInputsManager, _super);
  34519. function FreeCameraInputsManager(camera) {
  34520. return _super.call(this, camera) || this;
  34521. }
  34522. FreeCameraInputsManager.prototype.addKeyboard = function () {
  34523. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  34524. return this;
  34525. };
  34526. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  34527. if (touchEnabled === void 0) { touchEnabled = true; }
  34528. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  34529. return this;
  34530. };
  34531. FreeCameraInputsManager.prototype.addGamepad = function () {
  34532. this.add(new BABYLON.FreeCameraGamepadInput());
  34533. return this;
  34534. };
  34535. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  34536. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  34537. return this;
  34538. };
  34539. FreeCameraInputsManager.prototype.addTouch = function () {
  34540. this.add(new BABYLON.FreeCameraTouchInput());
  34541. return this;
  34542. };
  34543. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  34544. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  34545. return this;
  34546. };
  34547. return FreeCameraInputsManager;
  34548. }(BABYLON.CameraInputsManager));
  34549. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  34550. })(BABYLON || (BABYLON = {}));
  34551. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  34552. /// <reference path="babylon.camera.ts" />
  34553. var BABYLON;
  34554. (function (BABYLON) {
  34555. var TargetCamera = (function (_super) {
  34556. __extends(TargetCamera, _super);
  34557. function TargetCamera(name, position, scene) {
  34558. var _this = _super.call(this, name, position, scene) || this;
  34559. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34560. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  34561. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  34562. _this.speed = 2.0;
  34563. _this.noRotationConstraint = false;
  34564. _this.lockedTarget = null;
  34565. _this._currentTarget = BABYLON.Vector3.Zero();
  34566. _this._viewMatrix = BABYLON.Matrix.Zero();
  34567. _this._camMatrix = BABYLON.Matrix.Zero();
  34568. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  34569. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  34570. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  34571. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  34572. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  34573. _this._lookAtTemp = BABYLON.Matrix.Zero();
  34574. _this._tempMatrix = BABYLON.Matrix.Zero();
  34575. return _this;
  34576. }
  34577. TargetCamera.prototype.getFrontPosition = function (distance) {
  34578. var direction = this.getTarget().subtract(this.position);
  34579. direction.normalize();
  34580. direction.scaleInPlace(distance);
  34581. return this.globalPosition.add(direction);
  34582. };
  34583. TargetCamera.prototype._getLockedTargetPosition = function () {
  34584. if (!this.lockedTarget) {
  34585. return null;
  34586. }
  34587. if (this.lockedTarget.absolutePosition) {
  34588. this.lockedTarget.computeWorldMatrix();
  34589. }
  34590. return this.lockedTarget.absolutePosition || this.lockedTarget;
  34591. };
  34592. TargetCamera.prototype.storeState = function () {
  34593. this._storedPosition = this.position.clone();
  34594. this._storedRotation = this.rotation.clone();
  34595. if (this.rotationQuaternion) {
  34596. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  34597. }
  34598. return _super.prototype.storeState.call(this);
  34599. };
  34600. /**
  34601. * Restored camera state. You must call storeState() first
  34602. */
  34603. TargetCamera.prototype._restoreStateValues = function () {
  34604. if (!_super.prototype._restoreStateValues.call(this)) {
  34605. return false;
  34606. }
  34607. this.position = this._storedPosition.clone();
  34608. this.rotation = this._storedRotation.clone();
  34609. if (this.rotationQuaternion) {
  34610. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  34611. }
  34612. this.cameraDirection.copyFromFloats(0, 0, 0);
  34613. this.cameraRotation.copyFromFloats(0, 0);
  34614. return true;
  34615. };
  34616. // Cache
  34617. TargetCamera.prototype._initCache = function () {
  34618. _super.prototype._initCache.call(this);
  34619. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34620. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34621. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34622. };
  34623. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  34624. if (!ignoreParentClass) {
  34625. _super.prototype._updateCache.call(this);
  34626. }
  34627. var lockedTargetPosition = this._getLockedTargetPosition();
  34628. if (!lockedTargetPosition) {
  34629. this._cache.lockedTarget = null;
  34630. }
  34631. else {
  34632. if (!this._cache.lockedTarget) {
  34633. this._cache.lockedTarget = lockedTargetPosition.clone();
  34634. }
  34635. else {
  34636. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  34637. }
  34638. }
  34639. this._cache.rotation.copyFrom(this.rotation);
  34640. if (this.rotationQuaternion)
  34641. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34642. };
  34643. // Synchronized
  34644. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  34645. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  34646. return false;
  34647. }
  34648. var lockedTargetPosition = this._getLockedTargetPosition();
  34649. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  34650. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  34651. };
  34652. // Methods
  34653. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  34654. var engine = this.getEngine();
  34655. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  34656. };
  34657. // Target
  34658. TargetCamera.prototype.setTarget = function (target) {
  34659. this.upVector.normalize();
  34660. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  34661. this._camMatrix.invert();
  34662. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  34663. var vDir = target.subtract(this.position);
  34664. if (vDir.x >= 0.0) {
  34665. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  34666. }
  34667. else {
  34668. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  34669. }
  34670. this.rotation.z = 0;
  34671. if (isNaN(this.rotation.x)) {
  34672. this.rotation.x = 0;
  34673. }
  34674. if (isNaN(this.rotation.y)) {
  34675. this.rotation.y = 0;
  34676. }
  34677. if (isNaN(this.rotation.z)) {
  34678. this.rotation.z = 0;
  34679. }
  34680. if (this.rotationQuaternion) {
  34681. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34682. }
  34683. };
  34684. /**
  34685. * Return the current target position of the camera. This value is expressed in local space.
  34686. */
  34687. TargetCamera.prototype.getTarget = function () {
  34688. return this._currentTarget;
  34689. };
  34690. TargetCamera.prototype._decideIfNeedsToMove = function () {
  34691. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34692. };
  34693. TargetCamera.prototype._updatePosition = function () {
  34694. if (this.parent) {
  34695. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  34696. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  34697. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  34698. return;
  34699. }
  34700. this.position.addInPlace(this.cameraDirection);
  34701. };
  34702. TargetCamera.prototype._checkInputs = function () {
  34703. var needToMove = this._decideIfNeedsToMove();
  34704. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  34705. // Move
  34706. if (needToMove) {
  34707. this._updatePosition();
  34708. }
  34709. // Rotate
  34710. if (needToRotate) {
  34711. this.rotation.x += this.cameraRotation.x;
  34712. this.rotation.y += this.cameraRotation.y;
  34713. //rotate, if quaternion is set and rotation was used
  34714. if (this.rotationQuaternion) {
  34715. var len = this.rotation.lengthSquared();
  34716. if (len) {
  34717. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34718. }
  34719. }
  34720. if (!this.noRotationConstraint) {
  34721. var limit = (Math.PI / 2) * 0.95;
  34722. if (this.rotation.x > limit)
  34723. this.rotation.x = limit;
  34724. if (this.rotation.x < -limit)
  34725. this.rotation.x = -limit;
  34726. }
  34727. }
  34728. // Inertia
  34729. if (needToMove) {
  34730. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  34731. this.cameraDirection.x = 0;
  34732. }
  34733. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  34734. this.cameraDirection.y = 0;
  34735. }
  34736. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  34737. this.cameraDirection.z = 0;
  34738. }
  34739. this.cameraDirection.scaleInPlace(this.inertia);
  34740. }
  34741. if (needToRotate) {
  34742. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  34743. this.cameraRotation.x = 0;
  34744. }
  34745. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  34746. this.cameraRotation.y = 0;
  34747. }
  34748. this.cameraRotation.scaleInPlace(this.inertia);
  34749. }
  34750. _super.prototype._checkInputs.call(this);
  34751. };
  34752. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  34753. if (this.rotationQuaternion) {
  34754. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  34755. //update the up vector!
  34756. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  34757. }
  34758. else {
  34759. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  34760. }
  34761. };
  34762. TargetCamera.prototype._getViewMatrix = function () {
  34763. if (!this.lockedTarget) {
  34764. // Compute
  34765. this._updateCameraRotationMatrix();
  34766. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  34767. // Computing target and final matrix
  34768. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  34769. }
  34770. else {
  34771. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  34772. }
  34773. if (this.getScene().useRightHandedSystem) {
  34774. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34775. }
  34776. else {
  34777. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34778. }
  34779. return this._viewMatrix;
  34780. };
  34781. /**
  34782. * @override
  34783. * Override Camera.createRigCamera
  34784. */
  34785. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34786. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  34787. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  34788. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  34789. if (!this.rotationQuaternion) {
  34790. this.rotationQuaternion = new BABYLON.Quaternion();
  34791. }
  34792. rigCamera._cameraRigParams = {};
  34793. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  34794. }
  34795. return rigCamera;
  34796. }
  34797. return null;
  34798. };
  34799. /**
  34800. * @override
  34801. * Override Camera._updateRigCameras
  34802. */
  34803. TargetCamera.prototype._updateRigCameras = function () {
  34804. var camLeft = this._rigCameras[0];
  34805. var camRight = this._rigCameras[1];
  34806. switch (this.cameraRigMode) {
  34807. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34808. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34809. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34810. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34811. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  34812. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  34813. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  34814. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  34815. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  34816. camLeft.setTarget(this.getTarget());
  34817. camRight.setTarget(this.getTarget());
  34818. break;
  34819. case BABYLON.Camera.RIG_MODE_VR:
  34820. if (camLeft.rotationQuaternion) {
  34821. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34822. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34823. }
  34824. else {
  34825. camLeft.rotation.copyFrom(this.rotation);
  34826. camRight.rotation.copyFrom(this.rotation);
  34827. }
  34828. camLeft.position.copyFrom(this.position);
  34829. camRight.position.copyFrom(this.position);
  34830. break;
  34831. }
  34832. _super.prototype._updateRigCameras.call(this);
  34833. };
  34834. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  34835. if (!this._rigCamTransformMatrix) {
  34836. this._rigCamTransformMatrix = new BABYLON.Matrix();
  34837. }
  34838. var target = this.getTarget();
  34839. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  34840. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  34841. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  34842. };
  34843. TargetCamera.prototype.getClassName = function () {
  34844. return "TargetCamera";
  34845. };
  34846. __decorate([
  34847. BABYLON.serializeAsVector3()
  34848. ], TargetCamera.prototype, "rotation", void 0);
  34849. __decorate([
  34850. BABYLON.serialize()
  34851. ], TargetCamera.prototype, "speed", void 0);
  34852. __decorate([
  34853. BABYLON.serializeAsMeshReference("lockedTargetId")
  34854. ], TargetCamera.prototype, "lockedTarget", void 0);
  34855. return TargetCamera;
  34856. }(BABYLON.Camera));
  34857. BABYLON.TargetCamera = TargetCamera;
  34858. })(BABYLON || (BABYLON = {}));
  34859. //# sourceMappingURL=babylon.targetCamera.js.map
  34860. var BABYLON;
  34861. (function (BABYLON) {
  34862. var FreeCamera = (function (_super) {
  34863. __extends(FreeCamera, _super);
  34864. function FreeCamera(name, position, scene) {
  34865. var _this = _super.call(this, name, position, scene) || this;
  34866. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  34867. _this.checkCollisions = false;
  34868. _this.applyGravity = false;
  34869. _this._needMoveForGravity = false;
  34870. _this._oldPosition = BABYLON.Vector3.Zero();
  34871. _this._diffPosition = BABYLON.Vector3.Zero();
  34872. _this._newPosition = BABYLON.Vector3.Zero();
  34873. // Collisions
  34874. _this._collisionMask = -1;
  34875. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34876. if (collidedMesh === void 0) { collidedMesh = null; }
  34877. //TODO move this to the collision coordinator!
  34878. if (_this.getScene().workerCollisions)
  34879. newPosition.multiplyInPlace(_this._collider.radius);
  34880. var updatePosition = function (newPos) {
  34881. _this._newPosition.copyFrom(newPos);
  34882. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  34883. var oldPosition = _this.position.clone();
  34884. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  34885. _this.position.addInPlace(_this._diffPosition);
  34886. if (_this.onCollide && collidedMesh) {
  34887. _this.onCollide(collidedMesh);
  34888. }
  34889. }
  34890. };
  34891. updatePosition(newPosition);
  34892. };
  34893. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  34894. _this.inputs.addKeyboard().addMouse();
  34895. return _this;
  34896. }
  34897. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  34898. //-- begin properties for backward compatibility for inputs
  34899. get: function () {
  34900. var mouse = this.inputs.attached["mouse"];
  34901. if (mouse)
  34902. return mouse.angularSensibility;
  34903. },
  34904. set: function (value) {
  34905. var mouse = this.inputs.attached["mouse"];
  34906. if (mouse)
  34907. mouse.angularSensibility = value;
  34908. },
  34909. enumerable: true,
  34910. configurable: true
  34911. });
  34912. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  34913. get: function () {
  34914. var keyboard = this.inputs.attached["keyboard"];
  34915. if (keyboard)
  34916. return keyboard.keysUp;
  34917. },
  34918. set: function (value) {
  34919. var keyboard = this.inputs.attached["keyboard"];
  34920. if (keyboard)
  34921. keyboard.keysUp = value;
  34922. },
  34923. enumerable: true,
  34924. configurable: true
  34925. });
  34926. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  34927. get: function () {
  34928. var keyboard = this.inputs.attached["keyboard"];
  34929. if (keyboard)
  34930. return keyboard.keysDown;
  34931. },
  34932. set: function (value) {
  34933. var keyboard = this.inputs.attached["keyboard"];
  34934. if (keyboard)
  34935. keyboard.keysDown = value;
  34936. },
  34937. enumerable: true,
  34938. configurable: true
  34939. });
  34940. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  34941. get: function () {
  34942. var keyboard = this.inputs.attached["keyboard"];
  34943. if (keyboard)
  34944. return keyboard.keysLeft;
  34945. },
  34946. set: function (value) {
  34947. var keyboard = this.inputs.attached["keyboard"];
  34948. if (keyboard)
  34949. keyboard.keysLeft = value;
  34950. },
  34951. enumerable: true,
  34952. configurable: true
  34953. });
  34954. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  34955. get: function () {
  34956. var keyboard = this.inputs.attached["keyboard"];
  34957. if (keyboard)
  34958. return keyboard.keysRight;
  34959. },
  34960. set: function (value) {
  34961. var keyboard = this.inputs.attached["keyboard"];
  34962. if (keyboard)
  34963. keyboard.keysRight = value;
  34964. },
  34965. enumerable: true,
  34966. configurable: true
  34967. });
  34968. // Controls
  34969. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  34970. this.inputs.attachElement(element, noPreventDefault);
  34971. };
  34972. FreeCamera.prototype.detachControl = function (element) {
  34973. this.inputs.detachElement(element);
  34974. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34975. this.cameraRotation = new BABYLON.Vector2(0, 0);
  34976. };
  34977. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  34978. get: function () {
  34979. return this._collisionMask;
  34980. },
  34981. set: function (mask) {
  34982. this._collisionMask = !isNaN(mask) ? mask : -1;
  34983. },
  34984. enumerable: true,
  34985. configurable: true
  34986. });
  34987. FreeCamera.prototype._collideWithWorld = function (displacement) {
  34988. var globalPosition;
  34989. if (this.parent) {
  34990. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  34991. }
  34992. else {
  34993. globalPosition = this.position;
  34994. }
  34995. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  34996. if (!this._collider) {
  34997. this._collider = new BABYLON.Collider();
  34998. }
  34999. this._collider.radius = this.ellipsoid;
  35000. this._collider.collisionMask = this._collisionMask;
  35001. //no need for clone, as long as gravity is not on.
  35002. var actualDisplacement = displacement;
  35003. //add gravity to the direction to prevent the dual-collision checking
  35004. if (this.applyGravity) {
  35005. //this prevents mending with cameraDirection, a global variable of the free camera class.
  35006. actualDisplacement = displacement.add(this.getScene().gravity);
  35007. }
  35008. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  35009. };
  35010. FreeCamera.prototype._checkInputs = function () {
  35011. if (!this._localDirection) {
  35012. this._localDirection = BABYLON.Vector3.Zero();
  35013. this._transformedDirection = BABYLON.Vector3.Zero();
  35014. }
  35015. this.inputs.checkInputs();
  35016. _super.prototype._checkInputs.call(this);
  35017. };
  35018. FreeCamera.prototype._decideIfNeedsToMove = function () {
  35019. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  35020. };
  35021. FreeCamera.prototype._updatePosition = function () {
  35022. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  35023. this._collideWithWorld(this.cameraDirection);
  35024. }
  35025. else {
  35026. _super.prototype._updatePosition.call(this);
  35027. }
  35028. };
  35029. FreeCamera.prototype.dispose = function () {
  35030. this.inputs.clear();
  35031. _super.prototype.dispose.call(this);
  35032. };
  35033. FreeCamera.prototype.getClassName = function () {
  35034. return "FreeCamera";
  35035. };
  35036. __decorate([
  35037. BABYLON.serializeAsVector3()
  35038. ], FreeCamera.prototype, "ellipsoid", void 0);
  35039. __decorate([
  35040. BABYLON.serialize()
  35041. ], FreeCamera.prototype, "checkCollisions", void 0);
  35042. __decorate([
  35043. BABYLON.serialize()
  35044. ], FreeCamera.prototype, "applyGravity", void 0);
  35045. return FreeCamera;
  35046. }(BABYLON.TargetCamera));
  35047. BABYLON.FreeCamera = FreeCamera;
  35048. })(BABYLON || (BABYLON = {}));
  35049. //# sourceMappingURL=babylon.freeCamera.js.map
  35050. var BABYLON;
  35051. (function (BABYLON) {
  35052. var ArcRotateCameraKeyboardMoveInput = (function () {
  35053. function ArcRotateCameraKeyboardMoveInput() {
  35054. this._keys = [];
  35055. this.keysUp = [38];
  35056. this.keysDown = [40];
  35057. this.keysLeft = [37];
  35058. this.keysRight = [39];
  35059. this.keysReset = [111];
  35060. this.panningSensibility = 50.0;
  35061. }
  35062. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  35063. var _this = this;
  35064. if (this._onCanvasBlurObserver) {
  35065. return;
  35066. }
  35067. this._scene = this.camera.getScene();
  35068. this._engine = this._scene.getEngine();
  35069. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  35070. _this._keys = [];
  35071. });
  35072. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  35073. var evt = info.event;
  35074. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  35075. _this._ctrlPressed = evt.ctrlKey;
  35076. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35077. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35078. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35079. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  35080. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  35081. var index = _this._keys.indexOf(evt.keyCode);
  35082. if (index === -1) {
  35083. _this._keys.push(evt.keyCode);
  35084. }
  35085. if (evt.preventDefault) {
  35086. if (!noPreventDefault) {
  35087. evt.preventDefault();
  35088. }
  35089. }
  35090. }
  35091. }
  35092. else {
  35093. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35094. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35095. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35096. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  35097. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  35098. var index = _this._keys.indexOf(evt.keyCode);
  35099. if (index >= 0) {
  35100. _this._keys.splice(index, 1);
  35101. }
  35102. if (evt.preventDefault) {
  35103. if (!noPreventDefault) {
  35104. evt.preventDefault();
  35105. }
  35106. }
  35107. }
  35108. }
  35109. });
  35110. };
  35111. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  35112. if (this._scene) {
  35113. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  35114. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  35115. this._onKeyboardObserver = null;
  35116. this._onCanvasBlurObserver = null;
  35117. }
  35118. this._keys = [];
  35119. };
  35120. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  35121. if (this._onKeyboardObserver) {
  35122. var camera = this.camera;
  35123. for (var index = 0; index < this._keys.length; index++) {
  35124. var keyCode = this._keys[index];
  35125. if (this.keysLeft.indexOf(keyCode) !== -1) {
  35126. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35127. camera.inertialPanningX -= 1 / this.panningSensibility;
  35128. }
  35129. else {
  35130. camera.inertialAlphaOffset -= 0.01;
  35131. }
  35132. }
  35133. else if (this.keysUp.indexOf(keyCode) !== -1) {
  35134. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35135. camera.inertialPanningY += 1 / this.panningSensibility;
  35136. }
  35137. else {
  35138. camera.inertialBetaOffset -= 0.01;
  35139. }
  35140. }
  35141. else if (this.keysRight.indexOf(keyCode) !== -1) {
  35142. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35143. camera.inertialPanningX += 1 / this.panningSensibility;
  35144. }
  35145. else {
  35146. camera.inertialAlphaOffset += 0.01;
  35147. }
  35148. }
  35149. else if (this.keysDown.indexOf(keyCode) !== -1) {
  35150. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35151. camera.inertialPanningY -= 1 / this.panningSensibility;
  35152. }
  35153. else {
  35154. camera.inertialBetaOffset += 0.01;
  35155. }
  35156. }
  35157. else if (this.keysReset.indexOf(keyCode) !== -1) {
  35158. camera.restoreState();
  35159. }
  35160. }
  35161. }
  35162. };
  35163. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  35164. return "ArcRotateCameraKeyboardMoveInput";
  35165. };
  35166. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  35167. return "keyboard";
  35168. };
  35169. __decorate([
  35170. BABYLON.serialize()
  35171. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  35172. __decorate([
  35173. BABYLON.serialize()
  35174. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  35175. __decorate([
  35176. BABYLON.serialize()
  35177. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  35178. __decorate([
  35179. BABYLON.serialize()
  35180. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  35181. __decorate([
  35182. BABYLON.serialize()
  35183. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  35184. __decorate([
  35185. BABYLON.serialize()
  35186. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  35187. return ArcRotateCameraKeyboardMoveInput;
  35188. }());
  35189. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  35190. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  35191. })(BABYLON || (BABYLON = {}));
  35192. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  35193. var BABYLON;
  35194. (function (BABYLON) {
  35195. var ArcRotateCameraMouseWheelInput = (function () {
  35196. function ArcRotateCameraMouseWheelInput() {
  35197. this.wheelPrecision = 3.0;
  35198. }
  35199. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  35200. var _this = this;
  35201. this._wheel = function (p, s) {
  35202. //sanity check - this should be a PointerWheel event.
  35203. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  35204. return;
  35205. var event = p.event;
  35206. var delta = 0;
  35207. if (event.wheelDelta) {
  35208. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  35209. }
  35210. else if (event.detail) {
  35211. delta = -event.detail / _this.wheelPrecision;
  35212. }
  35213. if (delta)
  35214. _this.camera.inertialRadiusOffset += delta;
  35215. if (event.preventDefault) {
  35216. if (!noPreventDefault) {
  35217. event.preventDefault();
  35218. }
  35219. }
  35220. };
  35221. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  35222. };
  35223. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  35224. if (this._observer && element) {
  35225. this.camera.getScene().onPointerObservable.remove(this._observer);
  35226. this._observer = null;
  35227. this._wheel = null;
  35228. }
  35229. };
  35230. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  35231. return "ArcRotateCameraMouseWheelInput";
  35232. };
  35233. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  35234. return "mousewheel";
  35235. };
  35236. __decorate([
  35237. BABYLON.serialize()
  35238. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  35239. return ArcRotateCameraMouseWheelInput;
  35240. }());
  35241. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  35242. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  35243. })(BABYLON || (BABYLON = {}));
  35244. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  35245. var BABYLON;
  35246. (function (BABYLON) {
  35247. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  35248. var ArcRotateCameraPointersInput = (function () {
  35249. function ArcRotateCameraPointersInput() {
  35250. this.buttons = [0, 1, 2];
  35251. this.angularSensibilityX = 1000.0;
  35252. this.angularSensibilityY = 1000.0;
  35253. this.pinchPrecision = 6.0;
  35254. this.panningSensibility = 50.0;
  35255. this.multiTouchPanning = true;
  35256. this._isPanClick = false;
  35257. this.pinchInwards = true;
  35258. }
  35259. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  35260. var _this = this;
  35261. var engine = this.camera.getEngine();
  35262. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  35263. var pointA, pointB;
  35264. var previousPinchSquaredDistance = 0;
  35265. var previousPinchDistance = 0;
  35266. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false };
  35267. this._pointerInput = function (p, s) {
  35268. var evt = p.event;
  35269. if (engine.isInVRExclusivePointerMode) {
  35270. return;
  35271. }
  35272. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  35273. return;
  35274. }
  35275. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  35276. try {
  35277. evt.srcElement.setPointerCapture(evt.pointerId);
  35278. }
  35279. catch (e) {
  35280. //Nothing to do with the error. Execution will continue.
  35281. }
  35282. // Manage panning with pan button click
  35283. _this._isPanClick = evt.button === _this.camera._panningMouseButton && evt.pointerType !== "mouse";
  35284. // manage pointers
  35285. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  35286. if (pointA === undefined) {
  35287. pointA = cacheSoloPointer;
  35288. }
  35289. else if (pointB === undefined) {
  35290. pointB = cacheSoloPointer;
  35291. }
  35292. if (!noPreventDefault) {
  35293. evt.preventDefault();
  35294. element.focus();
  35295. }
  35296. }
  35297. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  35298. _this.camera.restoreState();
  35299. }
  35300. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  35301. try {
  35302. evt.srcElement.releasePointerCapture(evt.pointerId);
  35303. }
  35304. catch (e) {
  35305. //Nothing to do with the error.
  35306. }
  35307. cacheSoloPointer = null;
  35308. previousPinchSquaredDistance = 0;
  35309. previousPinchDistance = 0;
  35310. previousMultiTouchPanPosition.isPaning = false;
  35311. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  35312. //but emptying completly pointers collection is required to fix a bug on iPhone :
  35313. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  35314. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  35315. pointA = pointB = undefined;
  35316. if (!noPreventDefault) {
  35317. evt.preventDefault();
  35318. }
  35319. }
  35320. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  35321. if (!noPreventDefault) {
  35322. evt.preventDefault();
  35323. }
  35324. // One button down
  35325. if (pointA && pointB === undefined) {
  35326. if (_this.panningSensibility !== 0 &&
  35327. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  35328. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  35329. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  35330. }
  35331. else {
  35332. var offsetX = evt.clientX - cacheSoloPointer.x;
  35333. var offsetY = evt.clientY - cacheSoloPointer.y;
  35334. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35335. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35336. }
  35337. cacheSoloPointer.x = evt.clientX;
  35338. cacheSoloPointer.y = evt.clientY;
  35339. }
  35340. else if (pointA && pointB) {
  35341. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  35342. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  35343. ed.x = evt.clientX;
  35344. ed.y = evt.clientY;
  35345. var direction = _this.pinchInwards ? 1 : -1;
  35346. var distX = pointA.x - pointB.x;
  35347. var distY = pointA.y - pointB.y;
  35348. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  35349. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  35350. if (previousPinchSquaredDistance === 0) {
  35351. previousPinchSquaredDistance = pinchSquaredDistance;
  35352. previousPinchDistance = pinchDistance;
  35353. return;
  35354. }
  35355. if (pinchDistance > _this.camera.panMaxFingersDistance || Math.abs(pinchDistance - previousPinchDistance) > _this.camera.pinchToPanMaxDistance) {
  35356. _this.camera
  35357. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  35358. (_this.pinchPrecision *
  35359. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  35360. direction);
  35361. previousMultiTouchPanPosition.isPaning = false;
  35362. }
  35363. else {
  35364. if (cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  35365. if (!previousMultiTouchPanPosition.isPaning) {
  35366. previousMultiTouchPanPosition.isPaning = true;
  35367. previousMultiTouchPanPosition.x = ed.x;
  35368. previousMultiTouchPanPosition.y = ed.y;
  35369. return;
  35370. }
  35371. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / _this.panningSensibility;
  35372. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / _this.panningSensibility;
  35373. }
  35374. }
  35375. if (cacheSoloPointer.pointerId === evt.pointerId) {
  35376. previousMultiTouchPanPosition.x = ed.x;
  35377. previousMultiTouchPanPosition.y = ed.y;
  35378. }
  35379. previousPinchSquaredDistance = pinchSquaredDistance;
  35380. previousPinchDistance = pinchDistance;
  35381. }
  35382. }
  35383. };
  35384. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  35385. this._onContextMenu = function (evt) {
  35386. evt.preventDefault();
  35387. };
  35388. if (!this.camera._useCtrlForPanning) {
  35389. element.addEventListener("contextmenu", this._onContextMenu, false);
  35390. }
  35391. this._onLostFocus = function () {
  35392. //this._keys = [];
  35393. pointA = pointB = undefined;
  35394. previousPinchSquaredDistance = 0;
  35395. previousPinchDistance = 0;
  35396. previousMultiTouchPanPosition.isPaning = false;
  35397. cacheSoloPointer = null;
  35398. };
  35399. this._onMouseMove = function (evt) {
  35400. if (!engine.isPointerLock) {
  35401. return;
  35402. }
  35403. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  35404. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  35405. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35406. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35407. if (!noPreventDefault) {
  35408. evt.preventDefault();
  35409. }
  35410. };
  35411. this._onGestureStart = function (e) {
  35412. if (window.MSGesture === undefined) {
  35413. return;
  35414. }
  35415. if (!_this._MSGestureHandler) {
  35416. _this._MSGestureHandler = new MSGesture();
  35417. _this._MSGestureHandler.target = element;
  35418. }
  35419. _this._MSGestureHandler.addPointer(e.pointerId);
  35420. };
  35421. this._onGesture = function (e) {
  35422. _this.camera.radius *= e.scale;
  35423. if (e.preventDefault) {
  35424. if (!noPreventDefault) {
  35425. e.stopPropagation();
  35426. e.preventDefault();
  35427. }
  35428. }
  35429. };
  35430. element.addEventListener("mousemove", this._onMouseMove, false);
  35431. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  35432. element.addEventListener("MSGestureChange", this._onGesture, false);
  35433. BABYLON.Tools.RegisterTopRootEvents([
  35434. { name: "blur", handler: this._onLostFocus }
  35435. ]);
  35436. };
  35437. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  35438. BABYLON.Tools.UnregisterTopRootEvents([
  35439. { name: "blur", handler: this._onLostFocus }
  35440. ]);
  35441. if (element && this._observer) {
  35442. this.camera.getScene().onPointerObservable.remove(this._observer);
  35443. this._observer = null;
  35444. element.removeEventListener("contextmenu", this._onContextMenu);
  35445. element.removeEventListener("mousemove", this._onMouseMove);
  35446. element.removeEventListener("MSPointerDown", this._onGestureStart);
  35447. element.removeEventListener("MSGestureChange", this._onGesture);
  35448. this._isPanClick = false;
  35449. this.pinchInwards = true;
  35450. this._onMouseMove = null;
  35451. this._onGestureStart = null;
  35452. this._onGesture = null;
  35453. this._MSGestureHandler = null;
  35454. this._onLostFocus = null;
  35455. this._onContextMenu = null;
  35456. }
  35457. };
  35458. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  35459. return "ArcRotateCameraPointersInput";
  35460. };
  35461. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  35462. return "pointers";
  35463. };
  35464. __decorate([
  35465. BABYLON.serialize()
  35466. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  35467. __decorate([
  35468. BABYLON.serialize()
  35469. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  35470. __decorate([
  35471. BABYLON.serialize()
  35472. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  35473. __decorate([
  35474. BABYLON.serialize()
  35475. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  35476. __decorate([
  35477. BABYLON.serialize()
  35478. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  35479. __decorate([
  35480. BABYLON.serialize()
  35481. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  35482. return ArcRotateCameraPointersInput;
  35483. }());
  35484. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  35485. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  35486. })(BABYLON || (BABYLON = {}));
  35487. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  35488. /// <reference path="babylon.targetCamera.ts" />
  35489. /// <reference path="..\Tools\babylon.tools.ts" />
  35490. var BABYLON;
  35491. (function (BABYLON) {
  35492. var ArcRotateCamera = (function (_super) {
  35493. __extends(ArcRotateCamera, _super);
  35494. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  35495. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  35496. _this.inertialAlphaOffset = 0;
  35497. _this.inertialBetaOffset = 0;
  35498. _this.inertialRadiusOffset = 0;
  35499. _this.lowerAlphaLimit = null;
  35500. _this.upperAlphaLimit = null;
  35501. _this.lowerBetaLimit = 0.01;
  35502. _this.upperBetaLimit = Math.PI;
  35503. _this.lowerRadiusLimit = null;
  35504. _this.upperRadiusLimit = null;
  35505. _this.inertialPanningX = 0;
  35506. _this.inertialPanningY = 0;
  35507. _this.pinchToPanMaxDistance = 3;
  35508. _this.panMaxFingersDistance = 100;
  35509. _this.panningDistanceLimit = null;
  35510. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  35511. _this.panningInertia = 0.9;
  35512. //-- end properties for backward compatibility for inputs
  35513. _this.zoomOnFactor = 1;
  35514. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  35515. _this.allowUpsideDown = true;
  35516. _this._viewMatrix = new BABYLON.Matrix();
  35517. // Panning
  35518. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  35519. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  35520. _this.checkCollisions = false;
  35521. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  35522. _this._previousPosition = BABYLON.Vector3.Zero();
  35523. _this._collisionVelocity = BABYLON.Vector3.Zero();
  35524. _this._newPosition = BABYLON.Vector3.Zero();
  35525. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  35526. if (collidedMesh === void 0) { collidedMesh = null; }
  35527. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  35528. newPosition.multiplyInPlace(_this._collider.radius);
  35529. }
  35530. if (!collidedMesh) {
  35531. _this._previousPosition.copyFrom(_this.position);
  35532. }
  35533. else {
  35534. _this.setPosition(newPosition);
  35535. if (_this.onCollide) {
  35536. _this.onCollide(collidedMesh);
  35537. }
  35538. }
  35539. // Recompute because of constraints
  35540. var cosa = Math.cos(_this.alpha);
  35541. var sina = Math.sin(_this.alpha);
  35542. var cosb = Math.cos(_this.beta);
  35543. var sinb = Math.sin(_this.beta);
  35544. if (sinb === 0) {
  35545. sinb = 0.0001;
  35546. }
  35547. var target = _this._getTargetPosition();
  35548. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  35549. _this.position.copyFrom(_this._newPosition);
  35550. var up = _this.upVector;
  35551. if (_this.allowUpsideDown && _this.beta < 0) {
  35552. up = up.clone();
  35553. up = up.negate();
  35554. }
  35555. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  35556. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  35557. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  35558. _this._collisionTriggered = false;
  35559. };
  35560. _this._target = BABYLON.Vector3.Zero();
  35561. if (target) {
  35562. _this.setTarget(target);
  35563. }
  35564. _this.alpha = alpha;
  35565. _this.beta = beta;
  35566. _this.radius = radius;
  35567. _this.getViewMatrix();
  35568. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  35569. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  35570. return _this;
  35571. }
  35572. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  35573. get: function () {
  35574. return this._target;
  35575. },
  35576. set: function (value) {
  35577. this.setTarget(value);
  35578. },
  35579. enumerable: true,
  35580. configurable: true
  35581. });
  35582. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  35583. //-- begin properties for backward compatibility for inputs
  35584. get: function () {
  35585. var pointers = this.inputs.attached["pointers"];
  35586. if (pointers)
  35587. return pointers.angularSensibilityX;
  35588. },
  35589. set: function (value) {
  35590. var pointers = this.inputs.attached["pointers"];
  35591. if (pointers) {
  35592. pointers.angularSensibilityX = value;
  35593. }
  35594. },
  35595. enumerable: true,
  35596. configurable: true
  35597. });
  35598. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  35599. get: function () {
  35600. var pointers = this.inputs.attached["pointers"];
  35601. if (pointers)
  35602. return pointers.angularSensibilityY;
  35603. },
  35604. set: function (value) {
  35605. var pointers = this.inputs.attached["pointers"];
  35606. if (pointers) {
  35607. pointers.angularSensibilityY = value;
  35608. }
  35609. },
  35610. enumerable: true,
  35611. configurable: true
  35612. });
  35613. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  35614. get: function () {
  35615. var pointers = this.inputs.attached["pointers"];
  35616. if (pointers)
  35617. return pointers.pinchPrecision;
  35618. },
  35619. set: function (value) {
  35620. var pointers = this.inputs.attached["pointers"];
  35621. if (pointers) {
  35622. pointers.pinchPrecision = value;
  35623. }
  35624. },
  35625. enumerable: true,
  35626. configurable: true
  35627. });
  35628. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  35629. get: function () {
  35630. var pointers = this.inputs.attached["pointers"];
  35631. if (pointers)
  35632. return pointers.panningSensibility;
  35633. },
  35634. set: function (value) {
  35635. var pointers = this.inputs.attached["pointers"];
  35636. if (pointers) {
  35637. pointers.panningSensibility = value;
  35638. }
  35639. },
  35640. enumerable: true,
  35641. configurable: true
  35642. });
  35643. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  35644. get: function () {
  35645. var keyboard = this.inputs.attached["keyboard"];
  35646. if (keyboard)
  35647. return keyboard.keysUp;
  35648. },
  35649. set: function (value) {
  35650. var keyboard = this.inputs.attached["keyboard"];
  35651. if (keyboard)
  35652. keyboard.keysUp = value;
  35653. },
  35654. enumerable: true,
  35655. configurable: true
  35656. });
  35657. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  35658. get: function () {
  35659. var keyboard = this.inputs.attached["keyboard"];
  35660. if (keyboard)
  35661. return keyboard.keysDown;
  35662. },
  35663. set: function (value) {
  35664. var keyboard = this.inputs.attached["keyboard"];
  35665. if (keyboard)
  35666. keyboard.keysDown = value;
  35667. },
  35668. enumerable: true,
  35669. configurable: true
  35670. });
  35671. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  35672. get: function () {
  35673. var keyboard = this.inputs.attached["keyboard"];
  35674. if (keyboard)
  35675. return keyboard.keysLeft;
  35676. },
  35677. set: function (value) {
  35678. var keyboard = this.inputs.attached["keyboard"];
  35679. if (keyboard)
  35680. keyboard.keysLeft = value;
  35681. },
  35682. enumerable: true,
  35683. configurable: true
  35684. });
  35685. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  35686. get: function () {
  35687. var keyboard = this.inputs.attached["keyboard"];
  35688. if (keyboard)
  35689. return keyboard.keysRight;
  35690. },
  35691. set: function (value) {
  35692. var keyboard = this.inputs.attached["keyboard"];
  35693. if (keyboard)
  35694. keyboard.keysRight = value;
  35695. },
  35696. enumerable: true,
  35697. configurable: true
  35698. });
  35699. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  35700. get: function () {
  35701. var mousewheel = this.inputs.attached["mousewheel"];
  35702. if (mousewheel)
  35703. return mousewheel.wheelPrecision;
  35704. },
  35705. set: function (value) {
  35706. var mousewheel = this.inputs.attached["mousewheel"];
  35707. if (mousewheel)
  35708. mousewheel.wheelPrecision = value;
  35709. },
  35710. enumerable: true,
  35711. configurable: true
  35712. });
  35713. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  35714. get: function () {
  35715. return this._bouncingBehavior;
  35716. },
  35717. enumerable: true,
  35718. configurable: true
  35719. });
  35720. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  35721. get: function () {
  35722. return this._bouncingBehavior != null;
  35723. },
  35724. set: function (value) {
  35725. if (value === this.useBouncingBehavior) {
  35726. return;
  35727. }
  35728. if (value) {
  35729. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  35730. this.addBehavior(this._bouncingBehavior);
  35731. }
  35732. else {
  35733. this.removeBehavior(this._bouncingBehavior);
  35734. this._bouncingBehavior = null;
  35735. }
  35736. },
  35737. enumerable: true,
  35738. configurable: true
  35739. });
  35740. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  35741. get: function () {
  35742. return this._framingBehavior;
  35743. },
  35744. enumerable: true,
  35745. configurable: true
  35746. });
  35747. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  35748. get: function () {
  35749. return this._framingBehavior != null;
  35750. },
  35751. set: function (value) {
  35752. if (value === this.useFramingBehavior) {
  35753. return;
  35754. }
  35755. if (value) {
  35756. this._framingBehavior = new BABYLON.FramingBehavior();
  35757. this.addBehavior(this._framingBehavior);
  35758. }
  35759. else {
  35760. this.removeBehavior(this._framingBehavior);
  35761. this._framingBehavior = null;
  35762. }
  35763. },
  35764. enumerable: true,
  35765. configurable: true
  35766. });
  35767. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  35768. get: function () {
  35769. return this._autoRotationBehavior;
  35770. },
  35771. enumerable: true,
  35772. configurable: true
  35773. });
  35774. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  35775. get: function () {
  35776. return this._autoRotationBehavior != null;
  35777. },
  35778. set: function (value) {
  35779. if (value === this.useAutoRotationBehavior) {
  35780. return;
  35781. }
  35782. if (value) {
  35783. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  35784. this.addBehavior(this._autoRotationBehavior);
  35785. }
  35786. else {
  35787. this.removeBehavior(this._autoRotationBehavior);
  35788. this._autoRotationBehavior = null;
  35789. }
  35790. },
  35791. enumerable: true,
  35792. configurable: true
  35793. });
  35794. // Cache
  35795. ArcRotateCamera.prototype._initCache = function () {
  35796. _super.prototype._initCache.call(this);
  35797. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  35798. this._cache.alpha = undefined;
  35799. this._cache.beta = undefined;
  35800. this._cache.radius = undefined;
  35801. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  35802. };
  35803. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  35804. if (!ignoreParentClass) {
  35805. _super.prototype._updateCache.call(this);
  35806. }
  35807. this._cache._target.copyFrom(this._getTargetPosition());
  35808. this._cache.alpha = this.alpha;
  35809. this._cache.beta = this.beta;
  35810. this._cache.radius = this.radius;
  35811. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  35812. };
  35813. ArcRotateCamera.prototype._getTargetPosition = function () {
  35814. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  35815. var pos = this._targetHost.getAbsolutePosition();
  35816. if (this._targetBoundingCenter) {
  35817. pos.addToRef(this._targetBoundingCenter, this._target);
  35818. }
  35819. else {
  35820. this._target.copyFrom(pos);
  35821. }
  35822. }
  35823. var lockedTargetPosition = this._getLockedTargetPosition();
  35824. if (lockedTargetPosition) {
  35825. return lockedTargetPosition;
  35826. }
  35827. return this._target;
  35828. };
  35829. ArcRotateCamera.prototype.storeState = function () {
  35830. this._storedAlpha = this.alpha;
  35831. this._storedBeta = this.beta;
  35832. this._storedRadius = this.radius;
  35833. this._storedTarget = this._getTargetPosition().clone();
  35834. return _super.prototype.storeState.call(this);
  35835. };
  35836. /**
  35837. * Restored camera state. You must call storeState() first
  35838. */
  35839. ArcRotateCamera.prototype._restoreStateValues = function () {
  35840. if (!_super.prototype._restoreStateValues.call(this)) {
  35841. return false;
  35842. }
  35843. this.alpha = this._storedAlpha;
  35844. this.beta = this._storedBeta;
  35845. this.radius = this._storedRadius;
  35846. this.setTarget(this._storedTarget.clone());
  35847. this.inertialAlphaOffset = 0;
  35848. this.inertialBetaOffset = 0;
  35849. this.inertialRadiusOffset = 0;
  35850. this.inertialPanningX = 0;
  35851. this.inertialPanningY = 0;
  35852. return true;
  35853. };
  35854. // Synchronized
  35855. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  35856. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  35857. return false;
  35858. return this._cache._target.equals(this._getTargetPosition())
  35859. && this._cache.alpha === this.alpha
  35860. && this._cache.beta === this.beta
  35861. && this._cache.radius === this.radius
  35862. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  35863. };
  35864. // Methods
  35865. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  35866. var _this = this;
  35867. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  35868. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  35869. this._useCtrlForPanning = useCtrlForPanning;
  35870. this._panningMouseButton = panningMouseButton;
  35871. this.inputs.attachElement(element, noPreventDefault);
  35872. this._reset = function () {
  35873. _this.inertialAlphaOffset = 0;
  35874. _this.inertialBetaOffset = 0;
  35875. _this.inertialRadiusOffset = 0;
  35876. _this.inertialPanningX = 0;
  35877. _this.inertialPanningY = 0;
  35878. };
  35879. };
  35880. ArcRotateCamera.prototype.detachControl = function (element) {
  35881. this.inputs.detachElement(element);
  35882. if (this._reset) {
  35883. this._reset();
  35884. }
  35885. };
  35886. ArcRotateCamera.prototype._checkInputs = function () {
  35887. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  35888. if (this._collisionTriggered) {
  35889. return;
  35890. }
  35891. this.inputs.checkInputs();
  35892. // Inertia
  35893. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  35894. if (this.getScene().useRightHandedSystem) {
  35895. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35896. }
  35897. else {
  35898. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35899. }
  35900. this.beta += this.inertialBetaOffset;
  35901. this.radius -= this.inertialRadiusOffset;
  35902. this.inertialAlphaOffset *= this.inertia;
  35903. this.inertialBetaOffset *= this.inertia;
  35904. this.inertialRadiusOffset *= this.inertia;
  35905. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  35906. this.inertialAlphaOffset = 0;
  35907. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  35908. this.inertialBetaOffset = 0;
  35909. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  35910. this.inertialRadiusOffset = 0;
  35911. }
  35912. // Panning inertia
  35913. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  35914. if (!this._localDirection) {
  35915. this._localDirection = BABYLON.Vector3.Zero();
  35916. this._transformedDirection = BABYLON.Vector3.Zero();
  35917. }
  35918. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  35919. this._localDirection.multiplyInPlace(this.panningAxis);
  35920. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  35921. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  35922. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  35923. if (!this.panningAxis.y) {
  35924. this._transformedDirection.y = 0;
  35925. }
  35926. if (!this._targetHost) {
  35927. if (this.panningDistanceLimit) {
  35928. this._transformedDirection.addInPlace(this._target);
  35929. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  35930. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  35931. this._target.copyFrom(this._transformedDirection);
  35932. }
  35933. }
  35934. else {
  35935. this._target.addInPlace(this._transformedDirection);
  35936. }
  35937. }
  35938. this.inertialPanningX *= this.panningInertia;
  35939. this.inertialPanningY *= this.panningInertia;
  35940. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  35941. this.inertialPanningX = 0;
  35942. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  35943. this.inertialPanningY = 0;
  35944. }
  35945. // Limits
  35946. this._checkLimits();
  35947. _super.prototype._checkInputs.call(this);
  35948. };
  35949. ArcRotateCamera.prototype._checkLimits = function () {
  35950. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  35951. if (this.allowUpsideDown && this.beta > Math.PI) {
  35952. this.beta = this.beta - (2 * Math.PI);
  35953. }
  35954. }
  35955. else {
  35956. if (this.beta < this.lowerBetaLimit) {
  35957. this.beta = this.lowerBetaLimit;
  35958. }
  35959. }
  35960. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  35961. if (this.allowUpsideDown && this.beta < -Math.PI) {
  35962. this.beta = this.beta + (2 * Math.PI);
  35963. }
  35964. }
  35965. else {
  35966. if (this.beta > this.upperBetaLimit) {
  35967. this.beta = this.upperBetaLimit;
  35968. }
  35969. }
  35970. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  35971. this.alpha = this.lowerAlphaLimit;
  35972. }
  35973. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  35974. this.alpha = this.upperAlphaLimit;
  35975. }
  35976. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  35977. this.radius = this.lowerRadiusLimit;
  35978. }
  35979. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  35980. this.radius = this.upperRadiusLimit;
  35981. }
  35982. };
  35983. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  35984. var radiusv3 = this.position.subtract(this._getTargetPosition());
  35985. this.radius = radiusv3.length();
  35986. if (this.radius === 0) {
  35987. this.radius = 0.0001; // Just to avoid division by zero
  35988. }
  35989. // Alpha
  35990. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  35991. if (radiusv3.z < 0) {
  35992. this.alpha = 2 * Math.PI - this.alpha;
  35993. }
  35994. // Beta
  35995. this.beta = Math.acos(radiusv3.y / this.radius);
  35996. this._checkLimits();
  35997. };
  35998. ArcRotateCamera.prototype.setPosition = function (position) {
  35999. if (this.position.equals(position)) {
  36000. return;
  36001. }
  36002. this.position.copyFrom(position);
  36003. this.rebuildAnglesAndRadius();
  36004. };
  36005. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  36006. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  36007. if (allowSamePosition === void 0) { allowSamePosition = false; }
  36008. if (target.getBoundingInfo) {
  36009. if (toBoundingCenter) {
  36010. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  36011. }
  36012. else {
  36013. this._targetBoundingCenter = null;
  36014. }
  36015. this._targetHost = target;
  36016. this._target = this._getTargetPosition();
  36017. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  36018. }
  36019. else {
  36020. var newTarget = target;
  36021. var currentTarget = this._getTargetPosition();
  36022. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  36023. return;
  36024. }
  36025. this._targetHost = null;
  36026. this._target = newTarget;
  36027. this._targetBoundingCenter = null;
  36028. this.onMeshTargetChangedObservable.notifyObservers(null);
  36029. }
  36030. this.rebuildAnglesAndRadius();
  36031. };
  36032. ArcRotateCamera.prototype._getViewMatrix = function () {
  36033. // Compute
  36034. var cosa = Math.cos(this.alpha);
  36035. var sina = Math.sin(this.alpha);
  36036. var cosb = Math.cos(this.beta);
  36037. var sinb = Math.sin(this.beta);
  36038. if (sinb === 0) {
  36039. sinb = 0.0001;
  36040. }
  36041. var target = this._getTargetPosition();
  36042. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  36043. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  36044. if (!this._collider) {
  36045. this._collider = new BABYLON.Collider();
  36046. }
  36047. this._collider.radius = this.collisionRadius;
  36048. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  36049. this._collisionTriggered = true;
  36050. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  36051. }
  36052. else {
  36053. this.position.copyFrom(this._newPosition);
  36054. var up = this.upVector;
  36055. if (this.allowUpsideDown && sinb < 0) {
  36056. up = up.clone();
  36057. up = up.negate();
  36058. }
  36059. if (this.getScene().useRightHandedSystem) {
  36060. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  36061. }
  36062. else {
  36063. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  36064. }
  36065. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  36066. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  36067. }
  36068. this._currentTarget = target;
  36069. return this._viewMatrix;
  36070. };
  36071. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  36072. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  36073. meshes = meshes || this.getScene().meshes;
  36074. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  36075. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  36076. this.radius = distance * this.zoomOnFactor;
  36077. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  36078. };
  36079. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  36080. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  36081. var meshesOrMinMaxVector;
  36082. var distance;
  36083. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  36084. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  36085. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  36086. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  36087. }
  36088. else {
  36089. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  36090. distance = meshesOrMinMaxVectorAndDistance.distance;
  36091. }
  36092. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  36093. if (!doNotUpdateMaxZ) {
  36094. this.maxZ = distance * 2;
  36095. }
  36096. };
  36097. /**
  36098. * @override
  36099. * Override Camera.createRigCamera
  36100. */
  36101. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  36102. var alphaShift;
  36103. switch (this.cameraRigMode) {
  36104. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36105. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36106. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36107. case BABYLON.Camera.RIG_MODE_VR:
  36108. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  36109. break;
  36110. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36111. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  36112. break;
  36113. }
  36114. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  36115. rigCam._cameraRigParams = {};
  36116. return rigCam;
  36117. };
  36118. /**
  36119. * @override
  36120. * Override Camera._updateRigCameras
  36121. */
  36122. ArcRotateCamera.prototype._updateRigCameras = function () {
  36123. var camLeft = this._rigCameras[0];
  36124. var camRight = this._rigCameras[1];
  36125. camLeft.beta = camRight.beta = this.beta;
  36126. camLeft.radius = camRight.radius = this.radius;
  36127. switch (this.cameraRigMode) {
  36128. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36130. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36131. case BABYLON.Camera.RIG_MODE_VR:
  36132. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  36133. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  36134. break;
  36135. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36136. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  36137. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  36138. break;
  36139. }
  36140. _super.prototype._updateRigCameras.call(this);
  36141. };
  36142. ArcRotateCamera.prototype.dispose = function () {
  36143. this.inputs.clear();
  36144. _super.prototype.dispose.call(this);
  36145. };
  36146. ArcRotateCamera.prototype.getClassName = function () {
  36147. return "ArcRotateCamera";
  36148. };
  36149. __decorate([
  36150. BABYLON.serialize()
  36151. ], ArcRotateCamera.prototype, "alpha", void 0);
  36152. __decorate([
  36153. BABYLON.serialize()
  36154. ], ArcRotateCamera.prototype, "beta", void 0);
  36155. __decorate([
  36156. BABYLON.serialize()
  36157. ], ArcRotateCamera.prototype, "radius", void 0);
  36158. __decorate([
  36159. BABYLON.serializeAsVector3("target")
  36160. ], ArcRotateCamera.prototype, "_target", void 0);
  36161. __decorate([
  36162. BABYLON.serialize()
  36163. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  36164. __decorate([
  36165. BABYLON.serialize()
  36166. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  36167. __decorate([
  36168. BABYLON.serialize()
  36169. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  36170. __decorate([
  36171. BABYLON.serialize()
  36172. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  36173. __decorate([
  36174. BABYLON.serialize()
  36175. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  36176. __decorate([
  36177. BABYLON.serialize()
  36178. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  36179. __decorate([
  36180. BABYLON.serialize()
  36181. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  36182. __decorate([
  36183. BABYLON.serialize()
  36184. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  36185. __decorate([
  36186. BABYLON.serialize()
  36187. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  36188. __decorate([
  36189. BABYLON.serialize()
  36190. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  36191. __decorate([
  36192. BABYLON.serialize()
  36193. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  36194. __decorate([
  36195. BABYLON.serialize()
  36196. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  36197. __decorate([
  36198. BABYLON.serialize()
  36199. ], ArcRotateCamera.prototype, "panMaxFingersDistance", void 0);
  36200. __decorate([
  36201. BABYLON.serialize()
  36202. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  36203. __decorate([
  36204. BABYLON.serializeAsVector3()
  36205. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  36206. __decorate([
  36207. BABYLON.serialize()
  36208. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  36209. __decorate([
  36210. BABYLON.serialize()
  36211. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  36212. __decorate([
  36213. BABYLON.serialize()
  36214. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  36215. return ArcRotateCamera;
  36216. }(BABYLON.TargetCamera));
  36217. BABYLON.ArcRotateCamera = ArcRotateCamera;
  36218. })(BABYLON || (BABYLON = {}));
  36219. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  36220. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  36221. var BABYLON;
  36222. (function (BABYLON) {
  36223. var ArcRotateCameraInputsManager = (function (_super) {
  36224. __extends(ArcRotateCameraInputsManager, _super);
  36225. function ArcRotateCameraInputsManager(camera) {
  36226. return _super.call(this, camera) || this;
  36227. }
  36228. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  36229. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  36230. return this;
  36231. };
  36232. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  36233. this.add(new BABYLON.ArcRotateCameraPointersInput());
  36234. return this;
  36235. };
  36236. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  36237. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  36238. return this;
  36239. };
  36240. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  36241. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  36242. return this;
  36243. };
  36244. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  36245. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  36246. return this;
  36247. };
  36248. return ArcRotateCameraInputsManager;
  36249. }(BABYLON.CameraInputsManager));
  36250. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  36251. })(BABYLON || (BABYLON = {}));
  36252. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  36253. var BABYLON;
  36254. (function (BABYLON) {
  36255. var HemisphericLight = (function (_super) {
  36256. __extends(HemisphericLight, _super);
  36257. /**
  36258. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  36259. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  36260. * The HemisphericLight can't cast shadows.
  36261. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36262. */
  36263. function HemisphericLight(name, direction, scene) {
  36264. var _this = _super.call(this, name, scene) || this;
  36265. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  36266. _this.direction = direction || BABYLON.Vector3.Up();
  36267. return _this;
  36268. }
  36269. HemisphericLight.prototype._buildUniformLayout = function () {
  36270. this._uniformBuffer.addUniform("vLightData", 4);
  36271. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36272. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36273. this._uniformBuffer.addUniform("vLightGround", 3);
  36274. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36275. this._uniformBuffer.addUniform("depthValues", 2);
  36276. this._uniformBuffer.create();
  36277. };
  36278. /**
  36279. * Returns the string "HemisphericLight".
  36280. */
  36281. HemisphericLight.prototype.getClassName = function () {
  36282. return "HemisphericLight";
  36283. };
  36284. /**
  36285. * Sets the HemisphericLight direction towards the passed target (Vector3).
  36286. * Returns the updated direction.
  36287. */
  36288. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  36289. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  36290. return this.direction;
  36291. };
  36292. HemisphericLight.prototype.getShadowGenerator = function () {
  36293. return null;
  36294. };
  36295. /**
  36296. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  36297. * Returns the HemisphericLight.
  36298. */
  36299. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  36300. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36301. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  36302. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  36303. return this;
  36304. };
  36305. HemisphericLight.prototype._getWorldMatrix = function () {
  36306. if (!this._worldMatrix) {
  36307. this._worldMatrix = BABYLON.Matrix.Identity();
  36308. }
  36309. return this._worldMatrix;
  36310. };
  36311. /**
  36312. * Returns the integer 3.
  36313. */
  36314. HemisphericLight.prototype.getTypeID = function () {
  36315. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  36316. };
  36317. __decorate([
  36318. BABYLON.serializeAsColor3()
  36319. ], HemisphericLight.prototype, "groundColor", void 0);
  36320. __decorate([
  36321. BABYLON.serializeAsVector3()
  36322. ], HemisphericLight.prototype, "direction", void 0);
  36323. return HemisphericLight;
  36324. }(BABYLON.Light));
  36325. BABYLON.HemisphericLight = HemisphericLight;
  36326. })(BABYLON || (BABYLON = {}));
  36327. //# sourceMappingURL=babylon.hemisphericLight.js.map
  36328. var BABYLON;
  36329. (function (BABYLON) {
  36330. var ShadowLight = (function (_super) {
  36331. __extends(ShadowLight, _super);
  36332. function ShadowLight() {
  36333. var _this = _super !== null && _super.apply(this, arguments) || this;
  36334. _this._needProjectionMatrixCompute = true;
  36335. return _this;
  36336. }
  36337. Object.defineProperty(ShadowLight.prototype, "direction", {
  36338. get: function () {
  36339. return this._direction;
  36340. },
  36341. set: function (value) {
  36342. this._direction = value;
  36343. },
  36344. enumerable: true,
  36345. configurable: true
  36346. });
  36347. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  36348. get: function () {
  36349. return this._shadowMinZ;
  36350. },
  36351. set: function (value) {
  36352. this._shadowMinZ = value;
  36353. this.forceProjectionMatrixCompute();
  36354. },
  36355. enumerable: true,
  36356. configurable: true
  36357. });
  36358. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  36359. get: function () {
  36360. return this._shadowMaxZ;
  36361. },
  36362. set: function (value) {
  36363. this._shadowMaxZ = value;
  36364. this.forceProjectionMatrixCompute();
  36365. },
  36366. enumerable: true,
  36367. configurable: true
  36368. });
  36369. /**
  36370. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36371. */
  36372. ShadowLight.prototype.computeTransformedInformation = function () {
  36373. if (this.parent && this.parent.getWorldMatrix) {
  36374. if (!this.transformedPosition) {
  36375. this.transformedPosition = BABYLON.Vector3.Zero();
  36376. }
  36377. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36378. // In case the direction is present.
  36379. if (this.direction) {
  36380. if (!this.transformedDirection) {
  36381. this.transformedDirection = BABYLON.Vector3.Zero();
  36382. }
  36383. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36384. }
  36385. return true;
  36386. }
  36387. return false;
  36388. };
  36389. /**
  36390. * Return the depth scale used for the shadow map.
  36391. */
  36392. ShadowLight.prototype.getDepthScale = function () {
  36393. return 50.0;
  36394. };
  36395. /**
  36396. * Returns the light direction (Vector3) for any passed face index.
  36397. */
  36398. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36399. return this.transformedDirection ? this.transformedDirection : this.direction;
  36400. };
  36401. /**
  36402. * Returns the DirectionalLight absolute position in the World.
  36403. */
  36404. ShadowLight.prototype.getAbsolutePosition = function () {
  36405. return this.transformedPosition ? this.transformedPosition : this.position;
  36406. };
  36407. /**
  36408. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36409. * Returns the updated DirectionalLight direction (Vector3).
  36410. */
  36411. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36412. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36413. return this.direction;
  36414. };
  36415. /**
  36416. * Returns the light rotation (Vector3).
  36417. */
  36418. ShadowLight.prototype.getRotation = function () {
  36419. this.direction.normalize();
  36420. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36421. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36422. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36423. };
  36424. /**
  36425. * Boolean : false by default.
  36426. */
  36427. ShadowLight.prototype.needCube = function () {
  36428. return false;
  36429. };
  36430. /**
  36431. * Specifies wether or not the projection matrix should be recomputed this frame.
  36432. */
  36433. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36434. return this._needProjectionMatrixCompute;
  36435. };
  36436. /**
  36437. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36438. */
  36439. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36440. this._needProjectionMatrixCompute = true;
  36441. };
  36442. /**
  36443. * Get the world matrix of the sahdow lights.
  36444. */
  36445. ShadowLight.prototype._getWorldMatrix = function () {
  36446. if (!this._worldMatrix) {
  36447. this._worldMatrix = BABYLON.Matrix.Identity();
  36448. }
  36449. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36450. return this._worldMatrix;
  36451. };
  36452. /**
  36453. * Gets the minZ used for shadow according to both the scene and the light.
  36454. * @param activeCamera
  36455. */
  36456. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36457. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36458. };
  36459. /**
  36460. * Gets the maxZ used for shadow according to both the scene and the light.
  36461. * @param activeCamera
  36462. */
  36463. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36464. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36465. };
  36466. /**
  36467. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36468. * Returns the light.
  36469. */
  36470. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36471. if (this.customProjectionMatrixBuilder) {
  36472. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36473. }
  36474. else {
  36475. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36476. }
  36477. return this;
  36478. };
  36479. __decorate([
  36480. BABYLON.serializeAsVector3()
  36481. ], ShadowLight.prototype, "position", void 0);
  36482. __decorate([
  36483. BABYLON.serializeAsVector3()
  36484. ], ShadowLight.prototype, "direction", null);
  36485. __decorate([
  36486. BABYLON.serialize()
  36487. ], ShadowLight.prototype, "shadowMinZ", null);
  36488. __decorate([
  36489. BABYLON.serialize()
  36490. ], ShadowLight.prototype, "shadowMaxZ", null);
  36491. return ShadowLight;
  36492. }(BABYLON.Light));
  36493. BABYLON.ShadowLight = ShadowLight;
  36494. })(BABYLON || (BABYLON = {}));
  36495. //# sourceMappingURL=babylon.shadowLight.js.map
  36496. var BABYLON;
  36497. (function (BABYLON) {
  36498. var PointLight = (function (_super) {
  36499. __extends(PointLight, _super);
  36500. /**
  36501. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36502. * A PointLight emits the light in every direction.
  36503. * It can cast shadows.
  36504. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36505. * ```javascript
  36506. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36507. * ```
  36508. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36509. */
  36510. function PointLight(name, position, scene) {
  36511. var _this = _super.call(this, name, scene) || this;
  36512. _this._shadowAngle = Math.PI / 2;
  36513. _this.position = position;
  36514. return _this;
  36515. }
  36516. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36517. /**
  36518. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36519. * This specifies what angle the shadow will use to be created.
  36520. *
  36521. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36522. */
  36523. get: function () {
  36524. return this._shadowAngle;
  36525. },
  36526. /**
  36527. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36528. * This specifies what angle the shadow will use to be created.
  36529. *
  36530. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36531. */
  36532. set: function (value) {
  36533. this._shadowAngle = value;
  36534. this.forceProjectionMatrixCompute();
  36535. },
  36536. enumerable: true,
  36537. configurable: true
  36538. });
  36539. Object.defineProperty(PointLight.prototype, "direction", {
  36540. get: function () {
  36541. return this._direction;
  36542. },
  36543. /**
  36544. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36545. */
  36546. set: function (value) {
  36547. var previousNeedCube = this.needCube();
  36548. this._direction = value;
  36549. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36550. this._shadowGenerator.recreateShadowMap();
  36551. }
  36552. },
  36553. enumerable: true,
  36554. configurable: true
  36555. });
  36556. /**
  36557. * Returns the string "PointLight"
  36558. */
  36559. PointLight.prototype.getClassName = function () {
  36560. return "PointLight";
  36561. };
  36562. /**
  36563. * Returns the integer 0.
  36564. */
  36565. PointLight.prototype.getTypeID = function () {
  36566. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36567. };
  36568. /**
  36569. * Specifies wether or not the shadowmap should be a cube texture.
  36570. */
  36571. PointLight.prototype.needCube = function () {
  36572. return !this.direction;
  36573. };
  36574. /**
  36575. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36576. */
  36577. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36578. if (this.direction) {
  36579. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36580. }
  36581. else {
  36582. switch (faceIndex) {
  36583. case 0:
  36584. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36585. case 1:
  36586. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36587. case 2:
  36588. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36589. case 3:
  36590. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36591. case 4:
  36592. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36593. case 5:
  36594. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36595. }
  36596. }
  36597. return BABYLON.Vector3.Zero();
  36598. };
  36599. /**
  36600. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36601. * - fov = PI / 2
  36602. * - aspect ratio : 1.0
  36603. * - z-near and far equal to the active camera minZ and maxZ.
  36604. * Returns the PointLight.
  36605. */
  36606. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36607. var activeCamera = this.getScene().activeCamera;
  36608. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36609. };
  36610. PointLight.prototype._buildUniformLayout = function () {
  36611. this._uniformBuffer.addUniform("vLightData", 4);
  36612. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36613. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36614. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36615. this._uniformBuffer.addUniform("depthValues", 2);
  36616. this._uniformBuffer.create();
  36617. };
  36618. /**
  36619. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36620. * Returns the PointLight.
  36621. */
  36622. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36623. if (this.computeTransformedInformation()) {
  36624. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36625. return this;
  36626. }
  36627. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36628. return this;
  36629. };
  36630. __decorate([
  36631. BABYLON.serialize()
  36632. ], PointLight.prototype, "shadowAngle", null);
  36633. return PointLight;
  36634. }(BABYLON.ShadowLight));
  36635. BABYLON.PointLight = PointLight;
  36636. })(BABYLON || (BABYLON = {}));
  36637. //# sourceMappingURL=babylon.pointLight.js.map
  36638. /// <reference path="babylon.light.ts" />
  36639. var BABYLON;
  36640. (function (BABYLON) {
  36641. var DirectionalLight = (function (_super) {
  36642. __extends(DirectionalLight, _super);
  36643. /**
  36644. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36645. * The directional light is emitted from everywhere in the given direction.
  36646. * It can cast shawdows.
  36647. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36648. */
  36649. function DirectionalLight(name, direction, scene) {
  36650. var _this = _super.call(this, name, scene) || this;
  36651. _this._shadowFrustumSize = 0;
  36652. _this._shadowOrthoScale = 0.5;
  36653. _this.autoUpdateExtends = true;
  36654. // Cache
  36655. _this._orthoLeft = Number.MAX_VALUE;
  36656. _this._orthoRight = Number.MIN_VALUE;
  36657. _this._orthoTop = Number.MIN_VALUE;
  36658. _this._orthoBottom = Number.MAX_VALUE;
  36659. _this.position = direction.scale(-1.0);
  36660. _this.direction = direction;
  36661. return _this;
  36662. }
  36663. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36664. /**
  36665. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36666. */
  36667. get: function () {
  36668. return this._shadowFrustumSize;
  36669. },
  36670. /**
  36671. * Specifies a fix frustum size for the shadow generation.
  36672. */
  36673. set: function (value) {
  36674. this._shadowFrustumSize = value;
  36675. this.forceProjectionMatrixCompute();
  36676. },
  36677. enumerable: true,
  36678. configurable: true
  36679. });
  36680. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36681. get: function () {
  36682. return this._shadowOrthoScale;
  36683. },
  36684. set: function (value) {
  36685. this._shadowOrthoScale = value;
  36686. this.forceProjectionMatrixCompute();
  36687. },
  36688. enumerable: true,
  36689. configurable: true
  36690. });
  36691. /**
  36692. * Returns the string "DirectionalLight".
  36693. */
  36694. DirectionalLight.prototype.getClassName = function () {
  36695. return "DirectionalLight";
  36696. };
  36697. /**
  36698. * Returns the integer 1.
  36699. */
  36700. DirectionalLight.prototype.getTypeID = function () {
  36701. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36702. };
  36703. /**
  36704. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36705. * Returns the DirectionalLight Shadow projection matrix.
  36706. */
  36707. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36708. if (this.shadowFrustumSize > 0) {
  36709. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36710. }
  36711. else {
  36712. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36713. }
  36714. };
  36715. /**
  36716. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36717. * Returns the DirectionalLight Shadow projection matrix.
  36718. */
  36719. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36720. var activeCamera = this.getScene().activeCamera;
  36721. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36722. };
  36723. /**
  36724. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36725. * Returns the DirectionalLight Shadow projection matrix.
  36726. */
  36727. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36728. var activeCamera = this.getScene().activeCamera;
  36729. // Check extends
  36730. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36731. var tempVector3 = BABYLON.Vector3.Zero();
  36732. this._orthoLeft = Number.MAX_VALUE;
  36733. this._orthoRight = Number.MIN_VALUE;
  36734. this._orthoTop = Number.MIN_VALUE;
  36735. this._orthoBottom = Number.MAX_VALUE;
  36736. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36737. var mesh = renderList[meshIndex];
  36738. if (!mesh) {
  36739. continue;
  36740. }
  36741. var boundingInfo = mesh.getBoundingInfo();
  36742. if (!boundingInfo) {
  36743. continue;
  36744. }
  36745. var boundingBox = boundingInfo.boundingBox;
  36746. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36747. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36748. if (tempVector3.x < this._orthoLeft)
  36749. this._orthoLeft = tempVector3.x;
  36750. if (tempVector3.y < this._orthoBottom)
  36751. this._orthoBottom = tempVector3.y;
  36752. if (tempVector3.x > this._orthoRight)
  36753. this._orthoRight = tempVector3.x;
  36754. if (tempVector3.y > this._orthoTop)
  36755. this._orthoTop = tempVector3.y;
  36756. }
  36757. }
  36758. }
  36759. var xOffset = this._orthoRight - this._orthoLeft;
  36760. var yOffset = this._orthoTop - this._orthoBottom;
  36761. 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);
  36762. };
  36763. DirectionalLight.prototype._buildUniformLayout = function () {
  36764. this._uniformBuffer.addUniform("vLightData", 4);
  36765. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36766. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36767. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36768. this._uniformBuffer.addUniform("depthValues", 2);
  36769. this._uniformBuffer.create();
  36770. };
  36771. /**
  36772. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36773. * Returns the DirectionalLight.
  36774. */
  36775. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36776. if (this.computeTransformedInformation()) {
  36777. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36778. return this;
  36779. }
  36780. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36781. return this;
  36782. };
  36783. /**
  36784. * Gets the minZ used for shadow according to both the scene and the light.
  36785. *
  36786. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36787. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36788. * @param activeCamera
  36789. */
  36790. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36791. return 1;
  36792. };
  36793. /**
  36794. * Gets the maxZ used for shadow according to both the scene and the light.
  36795. *
  36796. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36797. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36798. * @param activeCamera
  36799. */
  36800. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36801. return 1;
  36802. };
  36803. __decorate([
  36804. BABYLON.serialize()
  36805. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36806. __decorate([
  36807. BABYLON.serialize()
  36808. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36809. __decorate([
  36810. BABYLON.serialize()
  36811. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36812. return DirectionalLight;
  36813. }(BABYLON.ShadowLight));
  36814. BABYLON.DirectionalLight = DirectionalLight;
  36815. })(BABYLON || (BABYLON = {}));
  36816. //# sourceMappingURL=babylon.directionalLight.js.map
  36817. var BABYLON;
  36818. (function (BABYLON) {
  36819. var SpotLight = (function (_super) {
  36820. __extends(SpotLight, _super);
  36821. /**
  36822. * Creates a SpotLight object in the scene with the passed parameters :
  36823. * - `position` (Vector3) is the initial SpotLight position,
  36824. * - `direction` (Vector3) is the initial SpotLight direction,
  36825. * - `angle` (float, in radians) is the spot light cone angle,
  36826. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36827. * A spot light is a simply light oriented cone.
  36828. * It can cast shadows.
  36829. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36830. */
  36831. function SpotLight(name, position, direction, angle, exponent, scene) {
  36832. var _this = _super.call(this, name, scene) || this;
  36833. _this.position = position;
  36834. _this.direction = direction;
  36835. _this.angle = angle;
  36836. _this.exponent = exponent;
  36837. return _this;
  36838. }
  36839. Object.defineProperty(SpotLight.prototype, "angle", {
  36840. get: function () {
  36841. return this._angle;
  36842. },
  36843. set: function (value) {
  36844. this._angle = value;
  36845. this.forceProjectionMatrixCompute();
  36846. },
  36847. enumerable: true,
  36848. configurable: true
  36849. });
  36850. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36851. get: function () {
  36852. return this._shadowAngleScale;
  36853. },
  36854. /**
  36855. * Allows scaling the angle of the light for shadow generation only.
  36856. */
  36857. set: function (value) {
  36858. this._shadowAngleScale = value;
  36859. this.forceProjectionMatrixCompute();
  36860. },
  36861. enumerable: true,
  36862. configurable: true
  36863. });
  36864. /**
  36865. * Returns the string "SpotLight".
  36866. */
  36867. SpotLight.prototype.getClassName = function () {
  36868. return "SpotLight";
  36869. };
  36870. /**
  36871. * Returns the integer 2.
  36872. */
  36873. SpotLight.prototype.getTypeID = function () {
  36874. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36875. };
  36876. /**
  36877. * 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.
  36878. * Returns the SpotLight.
  36879. */
  36880. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36881. var activeCamera = this.getScene().activeCamera;
  36882. this._shadowAngleScale = this._shadowAngleScale || 1;
  36883. var angle = this._shadowAngleScale * this._angle;
  36884. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36885. };
  36886. SpotLight.prototype._buildUniformLayout = function () {
  36887. this._uniformBuffer.addUniform("vLightData", 4);
  36888. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36889. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36890. this._uniformBuffer.addUniform("vLightDirection", 3);
  36891. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36892. this._uniformBuffer.addUniform("depthValues", 2);
  36893. this._uniformBuffer.create();
  36894. };
  36895. /**
  36896. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36897. * Return the SpotLight.
  36898. */
  36899. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36900. var normalizeDirection;
  36901. if (this.computeTransformedInformation()) {
  36902. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36903. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36904. }
  36905. else {
  36906. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36907. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36908. }
  36909. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36910. return this;
  36911. };
  36912. __decorate([
  36913. BABYLON.serialize()
  36914. ], SpotLight.prototype, "angle", null);
  36915. __decorate([
  36916. BABYLON.serialize()
  36917. /**
  36918. * Allows scaling the angle of the light for shadow generation only.
  36919. */
  36920. ], SpotLight.prototype, "shadowAngleScale", null);
  36921. __decorate([
  36922. BABYLON.serialize()
  36923. ], SpotLight.prototype, "exponent", void 0);
  36924. return SpotLight;
  36925. }(BABYLON.ShadowLight));
  36926. BABYLON.SpotLight = SpotLight;
  36927. })(BABYLON || (BABYLON = {}));
  36928. //# sourceMappingURL=babylon.spotLight.js.map
  36929. var BABYLON;
  36930. (function (BABYLON) {
  36931. var AnimationRange = (function () {
  36932. function AnimationRange(name, from, to) {
  36933. this.name = name;
  36934. this.from = from;
  36935. this.to = to;
  36936. }
  36937. AnimationRange.prototype.clone = function () {
  36938. return new AnimationRange(this.name, this.from, this.to);
  36939. };
  36940. return AnimationRange;
  36941. }());
  36942. BABYLON.AnimationRange = AnimationRange;
  36943. /**
  36944. * Composed of a frame, and an action function
  36945. */
  36946. var AnimationEvent = (function () {
  36947. function AnimationEvent(frame, action, onlyOnce) {
  36948. this.frame = frame;
  36949. this.action = action;
  36950. this.onlyOnce = onlyOnce;
  36951. this.isDone = false;
  36952. }
  36953. return AnimationEvent;
  36954. }());
  36955. BABYLON.AnimationEvent = AnimationEvent;
  36956. var PathCursor = (function () {
  36957. function PathCursor(path) {
  36958. this.path = path;
  36959. this._onchange = new Array();
  36960. this.value = 0;
  36961. this.animations = new Array();
  36962. }
  36963. PathCursor.prototype.getPoint = function () {
  36964. var point = this.path.getPointAtLengthPosition(this.value);
  36965. return new BABYLON.Vector3(point.x, 0, point.y);
  36966. };
  36967. PathCursor.prototype.moveAhead = function (step) {
  36968. if (step === void 0) { step = 0.002; }
  36969. this.move(step);
  36970. return this;
  36971. };
  36972. PathCursor.prototype.moveBack = function (step) {
  36973. if (step === void 0) { step = 0.002; }
  36974. this.move(-step);
  36975. return this;
  36976. };
  36977. PathCursor.prototype.move = function (step) {
  36978. if (Math.abs(step) > 1) {
  36979. throw "step size should be less than 1.";
  36980. }
  36981. this.value += step;
  36982. this.ensureLimits();
  36983. this.raiseOnChange();
  36984. return this;
  36985. };
  36986. PathCursor.prototype.ensureLimits = function () {
  36987. while (this.value > 1) {
  36988. this.value -= 1;
  36989. }
  36990. while (this.value < 0) {
  36991. this.value += 1;
  36992. }
  36993. return this;
  36994. };
  36995. // used by animation engine
  36996. PathCursor.prototype.markAsDirty = function (propertyName) {
  36997. this.ensureLimits();
  36998. this.raiseOnChange();
  36999. return this;
  37000. };
  37001. PathCursor.prototype.raiseOnChange = function () {
  37002. var _this = this;
  37003. this._onchange.forEach(function (f) { return f(_this); });
  37004. return this;
  37005. };
  37006. PathCursor.prototype.onchange = function (f) {
  37007. this._onchange.push(f);
  37008. return this;
  37009. };
  37010. return PathCursor;
  37011. }());
  37012. BABYLON.PathCursor = PathCursor;
  37013. var Animation = (function () {
  37014. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  37015. this.name = name;
  37016. this.targetProperty = targetProperty;
  37017. this.framePerSecond = framePerSecond;
  37018. this.dataType = dataType;
  37019. this.loopMode = loopMode;
  37020. this.enableBlending = enableBlending;
  37021. this._runtimeAnimations = new Array();
  37022. // The set of event that will be linked to this animation
  37023. this._events = new Array();
  37024. this.blendingSpeed = 0.01;
  37025. this._ranges = {};
  37026. this.targetPropertyPath = targetProperty.split(".");
  37027. this.dataType = dataType;
  37028. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  37029. }
  37030. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  37031. var dataType = undefined;
  37032. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  37033. dataType = Animation.ANIMATIONTYPE_FLOAT;
  37034. }
  37035. else if (from instanceof BABYLON.Quaternion) {
  37036. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  37037. }
  37038. else if (from instanceof BABYLON.Vector3) {
  37039. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  37040. }
  37041. else if (from instanceof BABYLON.Vector2) {
  37042. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  37043. }
  37044. else if (from instanceof BABYLON.Color3) {
  37045. dataType = Animation.ANIMATIONTYPE_COLOR3;
  37046. }
  37047. else if (from instanceof BABYLON.Size) {
  37048. dataType = Animation.ANIMATIONTYPE_SIZE;
  37049. }
  37050. if (dataType == undefined) {
  37051. return null;
  37052. }
  37053. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  37054. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  37055. animation.setKeys(keys);
  37056. if (easingFunction !== undefined) {
  37057. animation.setEasingFunction(easingFunction);
  37058. }
  37059. return animation;
  37060. };
  37061. /**
  37062. * Sets up an animation.
  37063. * @param property the property to animate
  37064. * @param animationType the animation type to apply
  37065. * @param easingFunction the easing function used in the animation
  37066. * @returns The created animation
  37067. */
  37068. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  37069. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  37070. animation.setEasingFunction(easingFunction);
  37071. return animation;
  37072. };
  37073. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  37074. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  37075. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  37076. };
  37077. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  37078. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  37079. node.animations.push(animation);
  37080. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  37081. };
  37082. /**
  37083. * Transition property of the Camera to the target Value.
  37084. * @param property The property to transition
  37085. * @param targetValue The target Value of the property
  37086. * @param host The object where the property to animate belongs
  37087. * @param scene Scene used to run the animation
  37088. * @param frameRate Framerate (in frame/s) to use
  37089. * @param transition The transition type we want to use
  37090. * @param duration The duration of the animation, in milliseconds
  37091. * @param onAnimationEnd Call back trigger at the end of the animation.
  37092. */
  37093. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  37094. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  37095. if (duration <= 0) {
  37096. host[property] = targetValue;
  37097. if (onAnimationEnd) {
  37098. onAnimationEnd();
  37099. }
  37100. return;
  37101. }
  37102. var endFrame = frameRate * (duration / 1000);
  37103. transition.setKeys([{
  37104. frame: 0,
  37105. value: host[property].clone ? host[property].clone() : host[property]
  37106. },
  37107. {
  37108. frame: endFrame,
  37109. value: targetValue
  37110. }]);
  37111. if (!host.animations) {
  37112. host.animations = [];
  37113. }
  37114. host.animations.push(transition);
  37115. var animation = scene.beginAnimation(host, 0, endFrame, false);
  37116. animation.onAnimationEnd = onAnimationEnd;
  37117. return animation;
  37118. };
  37119. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  37120. /**
  37121. * Return the array of runtime animations currently using this animation
  37122. */
  37123. get: function () {
  37124. return this._runtimeAnimations;
  37125. },
  37126. enumerable: true,
  37127. configurable: true
  37128. });
  37129. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  37130. get: function () {
  37131. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  37132. var runtimeAnimation = _a[_i];
  37133. if (!runtimeAnimation.isStopped) {
  37134. return true;
  37135. }
  37136. }
  37137. return false;
  37138. },
  37139. enumerable: true,
  37140. configurable: true
  37141. });
  37142. // Methods
  37143. /**
  37144. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  37145. */
  37146. Animation.prototype.toString = function (fullDetails) {
  37147. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  37148. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  37149. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  37150. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  37151. if (fullDetails) {
  37152. ret += ", Ranges: {";
  37153. var first = true;
  37154. for (var name in this._ranges) {
  37155. if (first) {
  37156. ret += ", ";
  37157. first = false;
  37158. }
  37159. ret += name;
  37160. }
  37161. ret += "}";
  37162. }
  37163. return ret;
  37164. };
  37165. /**
  37166. * Add an event to this animation.
  37167. */
  37168. Animation.prototype.addEvent = function (event) {
  37169. this._events.push(event);
  37170. };
  37171. /**
  37172. * Remove all events found at the given frame
  37173. * @param frame
  37174. */
  37175. Animation.prototype.removeEvents = function (frame) {
  37176. for (var index = 0; index < this._events.length; index++) {
  37177. if (this._events[index].frame === frame) {
  37178. this._events.splice(index, 1);
  37179. index--;
  37180. }
  37181. }
  37182. };
  37183. Animation.prototype.getEvents = function () {
  37184. return this._events;
  37185. };
  37186. Animation.prototype.createRange = function (name, from, to) {
  37187. // check name not already in use; could happen for bones after serialized
  37188. if (!this._ranges[name]) {
  37189. this._ranges[name] = new AnimationRange(name, from, to);
  37190. }
  37191. };
  37192. Animation.prototype.deleteRange = function (name, deleteFrames) {
  37193. if (deleteFrames === void 0) { deleteFrames = true; }
  37194. if (this._ranges[name]) {
  37195. if (deleteFrames) {
  37196. var from = this._ranges[name].from;
  37197. var to = this._ranges[name].to;
  37198. // this loop MUST go high to low for multiple splices to work
  37199. for (var key = this._keys.length - 1; key >= 0; key--) {
  37200. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  37201. this._keys.splice(key, 1);
  37202. }
  37203. }
  37204. }
  37205. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  37206. }
  37207. };
  37208. Animation.prototype.getRange = function (name) {
  37209. return this._ranges[name];
  37210. };
  37211. Animation.prototype.getKeys = function () {
  37212. return this._keys;
  37213. };
  37214. Animation.prototype.getHighestFrame = function () {
  37215. var ret = 0;
  37216. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  37217. if (ret < this._keys[key].frame) {
  37218. ret = this._keys[key].frame;
  37219. }
  37220. }
  37221. return ret;
  37222. };
  37223. Animation.prototype.getEasingFunction = function () {
  37224. return this._easingFunction;
  37225. };
  37226. Animation.prototype.setEasingFunction = function (easingFunction) {
  37227. this._easingFunction = easingFunction;
  37228. };
  37229. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  37230. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  37231. };
  37232. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37233. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37234. };
  37235. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  37236. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  37237. };
  37238. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37239. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  37240. };
  37241. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  37242. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  37243. };
  37244. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37245. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37246. };
  37247. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  37248. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  37249. };
  37250. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37251. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37252. };
  37253. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  37254. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  37255. };
  37256. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  37257. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  37258. };
  37259. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  37260. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  37261. };
  37262. Animation.prototype.clone = function () {
  37263. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  37264. clone.enableBlending = this.enableBlending;
  37265. clone.blendingSpeed = this.blendingSpeed;
  37266. if (this._keys) {
  37267. clone.setKeys(this._keys);
  37268. }
  37269. if (this._ranges) {
  37270. clone._ranges = {};
  37271. for (var name in this._ranges) {
  37272. clone._ranges[name] = this._ranges[name].clone();
  37273. }
  37274. }
  37275. return clone;
  37276. };
  37277. Animation.prototype.setKeys = function (values) {
  37278. this._keys = values.slice(0);
  37279. };
  37280. Animation.prototype.serialize = function () {
  37281. var serializationObject = {};
  37282. serializationObject.name = this.name;
  37283. serializationObject.property = this.targetProperty;
  37284. serializationObject.framePerSecond = this.framePerSecond;
  37285. serializationObject.dataType = this.dataType;
  37286. serializationObject.loopBehavior = this.loopMode;
  37287. serializationObject.enableBlending = this.enableBlending;
  37288. serializationObject.blendingSpeed = this.blendingSpeed;
  37289. var dataType = this.dataType;
  37290. serializationObject.keys = [];
  37291. var keys = this.getKeys();
  37292. for (var index = 0; index < keys.length; index++) {
  37293. var animationKey = keys[index];
  37294. var key = {};
  37295. key.frame = animationKey.frame;
  37296. switch (dataType) {
  37297. case Animation.ANIMATIONTYPE_FLOAT:
  37298. key.values = [animationKey.value];
  37299. break;
  37300. case Animation.ANIMATIONTYPE_QUATERNION:
  37301. case Animation.ANIMATIONTYPE_MATRIX:
  37302. case Animation.ANIMATIONTYPE_VECTOR3:
  37303. case Animation.ANIMATIONTYPE_COLOR3:
  37304. key.values = animationKey.value.asArray();
  37305. break;
  37306. }
  37307. serializationObject.keys.push(key);
  37308. }
  37309. serializationObject.ranges = [];
  37310. for (var name in this._ranges) {
  37311. var range = {};
  37312. range.name = name;
  37313. range.from = this._ranges[name].from;
  37314. range.to = this._ranges[name].to;
  37315. serializationObject.ranges.push(range);
  37316. }
  37317. return serializationObject;
  37318. };
  37319. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  37320. get: function () {
  37321. return Animation._ANIMATIONTYPE_FLOAT;
  37322. },
  37323. enumerable: true,
  37324. configurable: true
  37325. });
  37326. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  37327. get: function () {
  37328. return Animation._ANIMATIONTYPE_VECTOR3;
  37329. },
  37330. enumerable: true,
  37331. configurable: true
  37332. });
  37333. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  37334. get: function () {
  37335. return Animation._ANIMATIONTYPE_VECTOR2;
  37336. },
  37337. enumerable: true,
  37338. configurable: true
  37339. });
  37340. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  37341. get: function () {
  37342. return Animation._ANIMATIONTYPE_SIZE;
  37343. },
  37344. enumerable: true,
  37345. configurable: true
  37346. });
  37347. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  37348. get: function () {
  37349. return Animation._ANIMATIONTYPE_QUATERNION;
  37350. },
  37351. enumerable: true,
  37352. configurable: true
  37353. });
  37354. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  37355. get: function () {
  37356. return Animation._ANIMATIONTYPE_MATRIX;
  37357. },
  37358. enumerable: true,
  37359. configurable: true
  37360. });
  37361. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  37362. get: function () {
  37363. return Animation._ANIMATIONTYPE_COLOR3;
  37364. },
  37365. enumerable: true,
  37366. configurable: true
  37367. });
  37368. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  37369. get: function () {
  37370. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  37371. },
  37372. enumerable: true,
  37373. configurable: true
  37374. });
  37375. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  37376. get: function () {
  37377. return Animation._ANIMATIONLOOPMODE_CYCLE;
  37378. },
  37379. enumerable: true,
  37380. configurable: true
  37381. });
  37382. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  37383. get: function () {
  37384. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  37385. },
  37386. enumerable: true,
  37387. configurable: true
  37388. });
  37389. Animation.Parse = function (parsedAnimation) {
  37390. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  37391. var dataType = parsedAnimation.dataType;
  37392. var keys = [];
  37393. var data;
  37394. var index;
  37395. if (parsedAnimation.enableBlending) {
  37396. animation.enableBlending = parsedAnimation.enableBlending;
  37397. }
  37398. if (parsedAnimation.blendingSpeed) {
  37399. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  37400. }
  37401. for (index = 0; index < parsedAnimation.keys.length; index++) {
  37402. var key = parsedAnimation.keys[index];
  37403. switch (dataType) {
  37404. case Animation.ANIMATIONTYPE_FLOAT:
  37405. data = key.values[0];
  37406. break;
  37407. case Animation.ANIMATIONTYPE_QUATERNION:
  37408. data = BABYLON.Quaternion.FromArray(key.values);
  37409. break;
  37410. case Animation.ANIMATIONTYPE_MATRIX:
  37411. data = BABYLON.Matrix.FromArray(key.values);
  37412. break;
  37413. case Animation.ANIMATIONTYPE_COLOR3:
  37414. data = BABYLON.Color3.FromArray(key.values);
  37415. break;
  37416. case Animation.ANIMATIONTYPE_VECTOR3:
  37417. default:
  37418. data = BABYLON.Vector3.FromArray(key.values);
  37419. break;
  37420. }
  37421. keys.push({
  37422. frame: key.frame,
  37423. value: data
  37424. });
  37425. }
  37426. animation.setKeys(keys);
  37427. if (parsedAnimation.ranges) {
  37428. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  37429. data = parsedAnimation.ranges[index];
  37430. animation.createRange(data.name, data.from, data.to);
  37431. }
  37432. }
  37433. return animation;
  37434. };
  37435. Animation.AppendSerializedAnimations = function (source, destination) {
  37436. if (source.animations) {
  37437. destination.animations = [];
  37438. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  37439. var animation = source.animations[animationIndex];
  37440. destination.animations.push(animation.serialize());
  37441. }
  37442. }
  37443. };
  37444. Animation.AllowMatricesInterpolation = false;
  37445. // Statics
  37446. Animation._ANIMATIONTYPE_FLOAT = 0;
  37447. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  37448. Animation._ANIMATIONTYPE_QUATERNION = 2;
  37449. Animation._ANIMATIONTYPE_MATRIX = 3;
  37450. Animation._ANIMATIONTYPE_COLOR3 = 4;
  37451. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  37452. Animation._ANIMATIONTYPE_SIZE = 6;
  37453. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  37454. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  37455. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  37456. return Animation;
  37457. }());
  37458. BABYLON.Animation = Animation;
  37459. })(BABYLON || (BABYLON = {}));
  37460. //# sourceMappingURL=babylon.animation.js.map
  37461. var BABYLON;
  37462. (function (BABYLON) {
  37463. var RuntimeAnimation = (function () {
  37464. function RuntimeAnimation(target, animation) {
  37465. this._offsetsCache = {};
  37466. this._highLimitsCache = {};
  37467. this._stopped = false;
  37468. this._blendingFactor = 0;
  37469. this._ratioOffset = 0;
  37470. this._animation = animation;
  37471. this._target = target;
  37472. animation._runtimeAnimations.push(this);
  37473. }
  37474. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  37475. get: function () {
  37476. return this._animation;
  37477. },
  37478. enumerable: true,
  37479. configurable: true
  37480. });
  37481. RuntimeAnimation.prototype.reset = function () {
  37482. this._offsetsCache = {};
  37483. this._highLimitsCache = {};
  37484. this.currentFrame = 0;
  37485. this._blendingFactor = 0;
  37486. this._originalBlendValue = null;
  37487. };
  37488. RuntimeAnimation.prototype.isStopped = function () {
  37489. return this._stopped;
  37490. };
  37491. RuntimeAnimation.prototype.dispose = function () {
  37492. var index = this._animation.runtimeAnimations.indexOf(this);
  37493. if (index > -1) {
  37494. this._animation.runtimeAnimations.splice(index, 1);
  37495. }
  37496. };
  37497. RuntimeAnimation.prototype._getKeyValue = function (value) {
  37498. if (typeof value === "function") {
  37499. return value();
  37500. }
  37501. return value;
  37502. };
  37503. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  37504. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  37505. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  37506. }
  37507. this.currentFrame = currentFrame;
  37508. var keys = this._animation.getKeys();
  37509. // Try to get a hash to find the right key
  37510. var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
  37511. if (keys[startKeyIndex].frame >= currentFrame) {
  37512. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  37513. startKeyIndex--;
  37514. }
  37515. }
  37516. for (var key = startKeyIndex; key < keys.length; key++) {
  37517. var endKey = keys[key + 1];
  37518. if (endKey.frame >= currentFrame) {
  37519. var startKey = keys[key];
  37520. var startValue = this._getKeyValue(startKey.value);
  37521. var endValue = this._getKeyValue(endKey.value);
  37522. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  37523. var frameDelta = endKey.frame - startKey.frame;
  37524. // gradient : percent of currentFrame between the frame inf and the frame sup
  37525. var gradient = (currentFrame - startKey.frame) / frameDelta;
  37526. // check for easingFunction and correction of gradient
  37527. var easingFunction = this._animation.getEasingFunction();
  37528. if (easingFunction != null) {
  37529. gradient = easingFunction.ease(gradient);
  37530. }
  37531. switch (this._animation.dataType) {
  37532. // Float
  37533. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  37534. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  37535. switch (loopMode) {
  37536. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37537. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37538. return floatValue;
  37539. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37540. return offsetValue * repeatCount + floatValue;
  37541. }
  37542. break;
  37543. // Quaternion
  37544. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  37545. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  37546. switch (loopMode) {
  37547. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37548. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37549. return quatValue;
  37550. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37551. return quatValue.add(offsetValue.scale(repeatCount));
  37552. }
  37553. return quatValue;
  37554. // Vector3
  37555. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  37556. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  37557. switch (loopMode) {
  37558. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37559. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37560. return vec3Value;
  37561. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37562. return vec3Value.add(offsetValue.scale(repeatCount));
  37563. }
  37564. // Vector2
  37565. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  37566. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  37567. switch (loopMode) {
  37568. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37569. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37570. return vec2Value;
  37571. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37572. return vec2Value.add(offsetValue.scale(repeatCount));
  37573. }
  37574. // Size
  37575. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  37576. switch (loopMode) {
  37577. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37578. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37579. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  37580. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37581. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37582. }
  37583. // Color3
  37584. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  37585. switch (loopMode) {
  37586. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37587. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37588. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  37589. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37590. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37591. }
  37592. // Matrix
  37593. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  37594. switch (loopMode) {
  37595. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37596. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37597. if (BABYLON.Animation.AllowMatricesInterpolation) {
  37598. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  37599. }
  37600. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37601. return startValue;
  37602. }
  37603. default:
  37604. break;
  37605. }
  37606. break;
  37607. }
  37608. }
  37609. return this._getKeyValue(keys[keys.length - 1].value);
  37610. };
  37611. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  37612. if (blend === void 0) { blend = false; }
  37613. // Set value
  37614. var path;
  37615. var destination;
  37616. var targetPropertyPath = this._animation.targetPropertyPath;
  37617. if (targetPropertyPath.length > 1) {
  37618. var property = this._target[targetPropertyPath[0]];
  37619. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  37620. property = property[targetPropertyPath[index]];
  37621. }
  37622. path = targetPropertyPath[targetPropertyPath.length - 1];
  37623. destination = property;
  37624. }
  37625. else {
  37626. path = targetPropertyPath[0];
  37627. destination = this._target;
  37628. }
  37629. // Blending
  37630. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  37631. if (!this._originalBlendValue) {
  37632. if (destination[path].clone) {
  37633. this._originalBlendValue = destination[path].clone();
  37634. }
  37635. else {
  37636. this._originalBlendValue = destination[path];
  37637. }
  37638. }
  37639. if (this._originalBlendValue.prototype) {
  37640. if (this._originalBlendValue.prototype.Lerp) {
  37641. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  37642. }
  37643. else {
  37644. destination[path] = currentValue;
  37645. }
  37646. }
  37647. else if (this._originalBlendValue.m) {
  37648. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  37649. }
  37650. else {
  37651. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  37652. }
  37653. this._blendingFactor += this._animation.blendingSpeed;
  37654. }
  37655. else {
  37656. destination[path] = currentValue;
  37657. }
  37658. if (this._target.markAsDirty) {
  37659. this._target.markAsDirty(this._animation.targetProperty);
  37660. }
  37661. };
  37662. RuntimeAnimation.prototype.goToFrame = function (frame) {
  37663. var keys = this._animation.getKeys();
  37664. if (frame < keys[0].frame) {
  37665. frame = keys[0].frame;
  37666. }
  37667. else if (frame > keys[keys.length - 1].frame) {
  37668. frame = keys[keys.length - 1].frame;
  37669. }
  37670. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  37671. this.setValue(currentValue);
  37672. };
  37673. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  37674. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  37675. this._ratioOffset = this._previousRatio - newRatio;
  37676. };
  37677. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  37678. if (blend === void 0) { blend = false; }
  37679. var targetPropertyPath = this._animation.targetPropertyPath;
  37680. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  37681. this._stopped = true;
  37682. return false;
  37683. }
  37684. var returnValue = true;
  37685. var keys = this._animation.getKeys();
  37686. // Adding a start key at frame 0 if missing
  37687. if (keys[0].frame !== 0) {
  37688. var newKey = { frame: 0, value: keys[0].value };
  37689. keys.splice(0, 0, newKey);
  37690. }
  37691. // Check limits
  37692. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  37693. from = keys[0].frame;
  37694. }
  37695. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  37696. to = keys[keys.length - 1].frame;
  37697. }
  37698. //to and from cannot be the same key
  37699. if (from === to) {
  37700. from++;
  37701. }
  37702. // Compute ratio
  37703. var range = to - from;
  37704. var offsetValue;
  37705. // ratio represents the frame delta between from and to
  37706. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  37707. var highLimitValue = 0;
  37708. this._previousDelay = delay;
  37709. this._previousRatio = ratio;
  37710. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  37711. returnValue = false;
  37712. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  37713. }
  37714. else {
  37715. // Get max value if required
  37716. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  37717. var keyOffset = to.toString() + from.toString();
  37718. if (!this._offsetsCache[keyOffset]) {
  37719. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  37720. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  37721. switch (this._animation.dataType) {
  37722. // Float
  37723. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  37724. this._offsetsCache[keyOffset] = toValue - fromValue;
  37725. break;
  37726. // Quaternion
  37727. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  37728. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37729. break;
  37730. // Vector3
  37731. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  37732. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37733. // Vector2
  37734. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  37735. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37736. // Size
  37737. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  37738. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37739. // Color3
  37740. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  37741. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37742. default:
  37743. break;
  37744. }
  37745. this._highLimitsCache[keyOffset] = toValue;
  37746. }
  37747. highLimitValue = this._highLimitsCache[keyOffset];
  37748. offsetValue = this._offsetsCache[keyOffset];
  37749. }
  37750. }
  37751. if (offsetValue === undefined) {
  37752. switch (this._animation.dataType) {
  37753. // Float
  37754. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  37755. offsetValue = 0;
  37756. break;
  37757. // Quaternion
  37758. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  37759. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  37760. break;
  37761. // Vector3
  37762. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  37763. offsetValue = BABYLON.Vector3.Zero();
  37764. break;
  37765. // Vector2
  37766. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  37767. offsetValue = BABYLON.Vector2.Zero();
  37768. break;
  37769. // Size
  37770. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  37771. offsetValue = BABYLON.Size.Zero();
  37772. break;
  37773. // Color3
  37774. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  37775. offsetValue = BABYLON.Color3.Black();
  37776. }
  37777. }
  37778. // Compute value
  37779. var repeatCount = (ratio / range) >> 0;
  37780. var currentFrame = returnValue ? from + ratio % range : to;
  37781. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  37782. // Set value
  37783. this.setValue(currentValue);
  37784. // Check events
  37785. var events = this._animation.getEvents();
  37786. for (var index = 0; index < events.length; index++) {
  37787. // Make sure current frame has passed event frame and that event frame is within the current range
  37788. // Also, handle both forward and reverse animations
  37789. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  37790. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  37791. var event = events[index];
  37792. if (!event.isDone) {
  37793. // If event should be done only once, remove it.
  37794. if (event.onlyOnce) {
  37795. events.splice(index, 1);
  37796. index--;
  37797. }
  37798. event.isDone = true;
  37799. event.action();
  37800. } // Don't do anything if the event has already be done.
  37801. }
  37802. else if (events[index].isDone && !events[index].onlyOnce) {
  37803. // reset event, the animation is looping
  37804. events[index].isDone = false;
  37805. }
  37806. }
  37807. if (!returnValue) {
  37808. this._stopped = true;
  37809. }
  37810. return returnValue;
  37811. };
  37812. return RuntimeAnimation;
  37813. }());
  37814. BABYLON.RuntimeAnimation = RuntimeAnimation;
  37815. })(BABYLON || (BABYLON = {}));
  37816. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  37817. var BABYLON;
  37818. (function (BABYLON) {
  37819. var Animatable = (function () {
  37820. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  37821. if (fromFrame === void 0) { fromFrame = 0; }
  37822. if (toFrame === void 0) { toFrame = 100; }
  37823. if (loopAnimation === void 0) { loopAnimation = false; }
  37824. if (speedRatio === void 0) { speedRatio = 1.0; }
  37825. this.target = target;
  37826. this.fromFrame = fromFrame;
  37827. this.toFrame = toFrame;
  37828. this.loopAnimation = loopAnimation;
  37829. this.onAnimationEnd = onAnimationEnd;
  37830. this._localDelayOffset = null;
  37831. this._pausedDelay = null;
  37832. this._runtimeAnimations = new Array();
  37833. this._paused = false;
  37834. this._speedRatio = 1;
  37835. this.animationStarted = false;
  37836. if (animations) {
  37837. this.appendAnimations(target, animations);
  37838. }
  37839. this._speedRatio = speedRatio;
  37840. this._scene = scene;
  37841. scene._activeAnimatables.push(this);
  37842. }
  37843. Object.defineProperty(Animatable.prototype, "speedRatio", {
  37844. get: function () {
  37845. return this._speedRatio;
  37846. },
  37847. set: function (value) {
  37848. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  37849. var animation = this._runtimeAnimations[index];
  37850. animation._prepareForSpeedRatioChange(value);
  37851. }
  37852. this._speedRatio = value;
  37853. },
  37854. enumerable: true,
  37855. configurable: true
  37856. });
  37857. // Methods
  37858. Animatable.prototype.getAnimations = function () {
  37859. return this._runtimeAnimations;
  37860. };
  37861. Animatable.prototype.appendAnimations = function (target, animations) {
  37862. for (var index = 0; index < animations.length; index++) {
  37863. var animation = animations[index];
  37864. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  37865. }
  37866. };
  37867. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  37868. var runtimeAnimations = this._runtimeAnimations;
  37869. for (var index = 0; index < runtimeAnimations.length; index++) {
  37870. if (runtimeAnimations[index].animation.targetProperty === property) {
  37871. return runtimeAnimations[index].animation;
  37872. }
  37873. }
  37874. return null;
  37875. };
  37876. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  37877. var runtimeAnimations = this._runtimeAnimations;
  37878. for (var index = 0; index < runtimeAnimations.length; index++) {
  37879. if (runtimeAnimations[index].animation.targetProperty === property) {
  37880. return runtimeAnimations[index];
  37881. }
  37882. }
  37883. return null;
  37884. };
  37885. Animatable.prototype.reset = function () {
  37886. var runtimeAnimations = this._runtimeAnimations;
  37887. for (var index = 0; index < runtimeAnimations.length; index++) {
  37888. runtimeAnimations[index].reset();
  37889. }
  37890. this._localDelayOffset = null;
  37891. this._pausedDelay = null;
  37892. };
  37893. Animatable.prototype.enableBlending = function (blendingSpeed) {
  37894. var runtimeAnimations = this._runtimeAnimations;
  37895. for (var index = 0; index < runtimeAnimations.length; index++) {
  37896. runtimeAnimations[index].animation.enableBlending = true;
  37897. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  37898. }
  37899. };
  37900. Animatable.prototype.disableBlending = function () {
  37901. var runtimeAnimations = this._runtimeAnimations;
  37902. for (var index = 0; index < runtimeAnimations.length; index++) {
  37903. runtimeAnimations[index].animation.enableBlending = false;
  37904. }
  37905. };
  37906. Animatable.prototype.goToFrame = function (frame) {
  37907. var runtimeAnimations = this._runtimeAnimations;
  37908. if (runtimeAnimations[0]) {
  37909. var fps = runtimeAnimations[0].animation.framePerSecond;
  37910. var currentFrame = runtimeAnimations[0].currentFrame;
  37911. var adjustTime = frame - currentFrame;
  37912. var delay = adjustTime * 1000 / fps;
  37913. this._localDelayOffset -= delay;
  37914. }
  37915. for (var index = 0; index < runtimeAnimations.length; index++) {
  37916. runtimeAnimations[index].goToFrame(frame);
  37917. }
  37918. };
  37919. Animatable.prototype.pause = function () {
  37920. if (this._paused) {
  37921. return;
  37922. }
  37923. this._paused = true;
  37924. };
  37925. Animatable.prototype.restart = function () {
  37926. this._paused = false;
  37927. };
  37928. Animatable.prototype.stop = function (animationName) {
  37929. if (animationName) {
  37930. var idx = this._scene._activeAnimatables.indexOf(this);
  37931. if (idx > -1) {
  37932. var runtimeAnimations = this._runtimeAnimations;
  37933. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  37934. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  37935. continue;
  37936. }
  37937. runtimeAnimations[index].dispose();
  37938. runtimeAnimations.splice(index, 1);
  37939. }
  37940. if (runtimeAnimations.length == 0) {
  37941. this._scene._activeAnimatables.splice(idx, 1);
  37942. if (this.onAnimationEnd) {
  37943. this.onAnimationEnd();
  37944. }
  37945. }
  37946. }
  37947. }
  37948. else {
  37949. var index = this._scene._activeAnimatables.indexOf(this);
  37950. if (index > -1) {
  37951. this._scene._activeAnimatables.splice(index, 1);
  37952. var runtimeAnimations = this._runtimeAnimations;
  37953. for (var index = 0; index < runtimeAnimations.length; index++) {
  37954. runtimeAnimations[index].dispose();
  37955. }
  37956. if (this.onAnimationEnd) {
  37957. this.onAnimationEnd();
  37958. }
  37959. }
  37960. }
  37961. };
  37962. Animatable.prototype._animate = function (delay) {
  37963. if (this._paused) {
  37964. this.animationStarted = false;
  37965. if (this._pausedDelay === null) {
  37966. this._pausedDelay = delay;
  37967. }
  37968. return true;
  37969. }
  37970. if (this._localDelayOffset === null) {
  37971. this._localDelayOffset = delay;
  37972. }
  37973. else if (this._pausedDelay !== null) {
  37974. this._localDelayOffset += delay - this._pausedDelay;
  37975. this._pausedDelay = null;
  37976. }
  37977. // Animating
  37978. var running = false;
  37979. var runtimeAnimations = this._runtimeAnimations;
  37980. var index;
  37981. for (index = 0; index < runtimeAnimations.length; index++) {
  37982. var animation = runtimeAnimations[index];
  37983. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  37984. running = running || isRunning;
  37985. }
  37986. this.animationStarted = running;
  37987. if (!running) {
  37988. // Remove from active animatables
  37989. index = this._scene._activeAnimatables.indexOf(this);
  37990. this._scene._activeAnimatables.splice(index, 1);
  37991. // Dispose all runtime animations
  37992. for (index = 0; index < runtimeAnimations.length; index++) {
  37993. runtimeAnimations[index].dispose();
  37994. }
  37995. }
  37996. if (!running && this.onAnimationEnd) {
  37997. this.onAnimationEnd();
  37998. this.onAnimationEnd = null;
  37999. }
  38000. return running;
  38001. };
  38002. return Animatable;
  38003. }());
  38004. BABYLON.Animatable = Animatable;
  38005. })(BABYLON || (BABYLON = {}));
  38006. //# sourceMappingURL=babylon.animatable.js.map
  38007. var BABYLON;
  38008. (function (BABYLON) {
  38009. var EasingFunction = (function () {
  38010. function EasingFunction() {
  38011. // Properties
  38012. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  38013. }
  38014. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  38015. get: function () {
  38016. return EasingFunction._EASINGMODE_EASEIN;
  38017. },
  38018. enumerable: true,
  38019. configurable: true
  38020. });
  38021. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  38022. get: function () {
  38023. return EasingFunction._EASINGMODE_EASEOUT;
  38024. },
  38025. enumerable: true,
  38026. configurable: true
  38027. });
  38028. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  38029. get: function () {
  38030. return EasingFunction._EASINGMODE_EASEINOUT;
  38031. },
  38032. enumerable: true,
  38033. configurable: true
  38034. });
  38035. EasingFunction.prototype.setEasingMode = function (easingMode) {
  38036. var n = Math.min(Math.max(easingMode, 0), 2);
  38037. this._easingMode = n;
  38038. };
  38039. EasingFunction.prototype.getEasingMode = function () {
  38040. return this._easingMode;
  38041. };
  38042. EasingFunction.prototype.easeInCore = function (gradient) {
  38043. throw new Error('You must implement this method');
  38044. };
  38045. EasingFunction.prototype.ease = function (gradient) {
  38046. switch (this._easingMode) {
  38047. case EasingFunction.EASINGMODE_EASEIN:
  38048. return this.easeInCore(gradient);
  38049. case EasingFunction.EASINGMODE_EASEOUT:
  38050. return (1 - this.easeInCore(1 - gradient));
  38051. }
  38052. if (gradient >= 0.5) {
  38053. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  38054. }
  38055. return (this.easeInCore(gradient * 2) * 0.5);
  38056. };
  38057. //Statics
  38058. EasingFunction._EASINGMODE_EASEIN = 0;
  38059. EasingFunction._EASINGMODE_EASEOUT = 1;
  38060. EasingFunction._EASINGMODE_EASEINOUT = 2;
  38061. return EasingFunction;
  38062. }());
  38063. BABYLON.EasingFunction = EasingFunction;
  38064. var CircleEase = (function (_super) {
  38065. __extends(CircleEase, _super);
  38066. function CircleEase() {
  38067. return _super !== null && _super.apply(this, arguments) || this;
  38068. }
  38069. CircleEase.prototype.easeInCore = function (gradient) {
  38070. gradient = Math.max(0, Math.min(1, gradient));
  38071. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  38072. };
  38073. return CircleEase;
  38074. }(EasingFunction));
  38075. BABYLON.CircleEase = CircleEase;
  38076. var BackEase = (function (_super) {
  38077. __extends(BackEase, _super);
  38078. function BackEase(amplitude) {
  38079. if (amplitude === void 0) { amplitude = 1; }
  38080. var _this = _super.call(this) || this;
  38081. _this.amplitude = amplitude;
  38082. return _this;
  38083. }
  38084. BackEase.prototype.easeInCore = function (gradient) {
  38085. var num = Math.max(0, this.amplitude);
  38086. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  38087. };
  38088. return BackEase;
  38089. }(EasingFunction));
  38090. BABYLON.BackEase = BackEase;
  38091. var BounceEase = (function (_super) {
  38092. __extends(BounceEase, _super);
  38093. function BounceEase(bounces, bounciness) {
  38094. if (bounces === void 0) { bounces = 3; }
  38095. if (bounciness === void 0) { bounciness = 2; }
  38096. var _this = _super.call(this) || this;
  38097. _this.bounces = bounces;
  38098. _this.bounciness = bounciness;
  38099. return _this;
  38100. }
  38101. BounceEase.prototype.easeInCore = function (gradient) {
  38102. var y = Math.max(0.0, this.bounces);
  38103. var bounciness = this.bounciness;
  38104. if (bounciness <= 1.0) {
  38105. bounciness = 1.001;
  38106. }
  38107. var num9 = Math.pow(bounciness, y);
  38108. var num5 = 1.0 - bounciness;
  38109. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  38110. var num15 = gradient * num4;
  38111. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  38112. var num3 = Math.floor(num65);
  38113. var num13 = num3 + 1.0;
  38114. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  38115. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  38116. var num7 = (num8 + num12) * 0.5;
  38117. var num6 = gradient - num7;
  38118. var num2 = num7 - num8;
  38119. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  38120. };
  38121. return BounceEase;
  38122. }(EasingFunction));
  38123. BABYLON.BounceEase = BounceEase;
  38124. var CubicEase = (function (_super) {
  38125. __extends(CubicEase, _super);
  38126. function CubicEase() {
  38127. return _super !== null && _super.apply(this, arguments) || this;
  38128. }
  38129. CubicEase.prototype.easeInCore = function (gradient) {
  38130. return (gradient * gradient * gradient);
  38131. };
  38132. return CubicEase;
  38133. }(EasingFunction));
  38134. BABYLON.CubicEase = CubicEase;
  38135. var ElasticEase = (function (_super) {
  38136. __extends(ElasticEase, _super);
  38137. function ElasticEase(oscillations, springiness) {
  38138. if (oscillations === void 0) { oscillations = 3; }
  38139. if (springiness === void 0) { springiness = 3; }
  38140. var _this = _super.call(this) || this;
  38141. _this.oscillations = oscillations;
  38142. _this.springiness = springiness;
  38143. return _this;
  38144. }
  38145. ElasticEase.prototype.easeInCore = function (gradient) {
  38146. var num2;
  38147. var num3 = Math.max(0.0, this.oscillations);
  38148. var num = Math.max(0.0, this.springiness);
  38149. if (num == 0) {
  38150. num2 = gradient;
  38151. }
  38152. else {
  38153. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  38154. }
  38155. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  38156. };
  38157. return ElasticEase;
  38158. }(EasingFunction));
  38159. BABYLON.ElasticEase = ElasticEase;
  38160. var ExponentialEase = (function (_super) {
  38161. __extends(ExponentialEase, _super);
  38162. function ExponentialEase(exponent) {
  38163. if (exponent === void 0) { exponent = 2; }
  38164. var _this = _super.call(this) || this;
  38165. _this.exponent = exponent;
  38166. return _this;
  38167. }
  38168. ExponentialEase.prototype.easeInCore = function (gradient) {
  38169. if (this.exponent <= 0) {
  38170. return gradient;
  38171. }
  38172. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  38173. };
  38174. return ExponentialEase;
  38175. }(EasingFunction));
  38176. BABYLON.ExponentialEase = ExponentialEase;
  38177. var PowerEase = (function (_super) {
  38178. __extends(PowerEase, _super);
  38179. function PowerEase(power) {
  38180. if (power === void 0) { power = 2; }
  38181. var _this = _super.call(this) || this;
  38182. _this.power = power;
  38183. return _this;
  38184. }
  38185. PowerEase.prototype.easeInCore = function (gradient) {
  38186. var y = Math.max(0.0, this.power);
  38187. return Math.pow(gradient, y);
  38188. };
  38189. return PowerEase;
  38190. }(EasingFunction));
  38191. BABYLON.PowerEase = PowerEase;
  38192. var QuadraticEase = (function (_super) {
  38193. __extends(QuadraticEase, _super);
  38194. function QuadraticEase() {
  38195. return _super !== null && _super.apply(this, arguments) || this;
  38196. }
  38197. QuadraticEase.prototype.easeInCore = function (gradient) {
  38198. return (gradient * gradient);
  38199. };
  38200. return QuadraticEase;
  38201. }(EasingFunction));
  38202. BABYLON.QuadraticEase = QuadraticEase;
  38203. var QuarticEase = (function (_super) {
  38204. __extends(QuarticEase, _super);
  38205. function QuarticEase() {
  38206. return _super !== null && _super.apply(this, arguments) || this;
  38207. }
  38208. QuarticEase.prototype.easeInCore = function (gradient) {
  38209. return (gradient * gradient * gradient * gradient);
  38210. };
  38211. return QuarticEase;
  38212. }(EasingFunction));
  38213. BABYLON.QuarticEase = QuarticEase;
  38214. var QuinticEase = (function (_super) {
  38215. __extends(QuinticEase, _super);
  38216. function QuinticEase() {
  38217. return _super !== null && _super.apply(this, arguments) || this;
  38218. }
  38219. QuinticEase.prototype.easeInCore = function (gradient) {
  38220. return (gradient * gradient * gradient * gradient * gradient);
  38221. };
  38222. return QuinticEase;
  38223. }(EasingFunction));
  38224. BABYLON.QuinticEase = QuinticEase;
  38225. var SineEase = (function (_super) {
  38226. __extends(SineEase, _super);
  38227. function SineEase() {
  38228. return _super !== null && _super.apply(this, arguments) || this;
  38229. }
  38230. SineEase.prototype.easeInCore = function (gradient) {
  38231. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  38232. };
  38233. return SineEase;
  38234. }(EasingFunction));
  38235. BABYLON.SineEase = SineEase;
  38236. var BezierCurveEase = (function (_super) {
  38237. __extends(BezierCurveEase, _super);
  38238. function BezierCurveEase(x1, y1, x2, y2) {
  38239. if (x1 === void 0) { x1 = 0; }
  38240. if (y1 === void 0) { y1 = 0; }
  38241. if (x2 === void 0) { x2 = 1; }
  38242. if (y2 === void 0) { y2 = 1; }
  38243. var _this = _super.call(this) || this;
  38244. _this.x1 = x1;
  38245. _this.y1 = y1;
  38246. _this.x2 = x2;
  38247. _this.y2 = y2;
  38248. return _this;
  38249. }
  38250. BezierCurveEase.prototype.easeInCore = function (gradient) {
  38251. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  38252. };
  38253. return BezierCurveEase;
  38254. }(EasingFunction));
  38255. BABYLON.BezierCurveEase = BezierCurveEase;
  38256. })(BABYLON || (BABYLON = {}));
  38257. //# sourceMappingURL=babylon.easing.js.map
  38258. var BABYLON;
  38259. (function (BABYLON) {
  38260. var Condition = (function () {
  38261. function Condition(actionManager) {
  38262. this._actionManager = actionManager;
  38263. }
  38264. Condition.prototype.isValid = function () {
  38265. return true;
  38266. };
  38267. Condition.prototype._getProperty = function (propertyPath) {
  38268. return this._actionManager._getProperty(propertyPath);
  38269. };
  38270. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  38271. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38272. };
  38273. Condition.prototype.serialize = function () {
  38274. };
  38275. Condition.prototype._serialize = function (serializedCondition) {
  38276. return {
  38277. type: 2,
  38278. children: [],
  38279. name: serializedCondition.name,
  38280. properties: serializedCondition.properties
  38281. };
  38282. };
  38283. return Condition;
  38284. }());
  38285. BABYLON.Condition = Condition;
  38286. var ValueCondition = (function (_super) {
  38287. __extends(ValueCondition, _super);
  38288. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  38289. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  38290. var _this = _super.call(this, actionManager) || this;
  38291. _this.propertyPath = propertyPath;
  38292. _this.value = value;
  38293. _this.operator = operator;
  38294. _this._target = target;
  38295. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  38296. _this._property = _this._getProperty(_this.propertyPath);
  38297. return _this;
  38298. }
  38299. Object.defineProperty(ValueCondition, "IsEqual", {
  38300. get: function () {
  38301. return ValueCondition._IsEqual;
  38302. },
  38303. enumerable: true,
  38304. configurable: true
  38305. });
  38306. Object.defineProperty(ValueCondition, "IsDifferent", {
  38307. get: function () {
  38308. return ValueCondition._IsDifferent;
  38309. },
  38310. enumerable: true,
  38311. configurable: true
  38312. });
  38313. Object.defineProperty(ValueCondition, "IsGreater", {
  38314. get: function () {
  38315. return ValueCondition._IsGreater;
  38316. },
  38317. enumerable: true,
  38318. configurable: true
  38319. });
  38320. Object.defineProperty(ValueCondition, "IsLesser", {
  38321. get: function () {
  38322. return ValueCondition._IsLesser;
  38323. },
  38324. enumerable: true,
  38325. configurable: true
  38326. });
  38327. // Methods
  38328. ValueCondition.prototype.isValid = function () {
  38329. switch (this.operator) {
  38330. case ValueCondition.IsGreater:
  38331. return this._effectiveTarget[this._property] > this.value;
  38332. case ValueCondition.IsLesser:
  38333. return this._effectiveTarget[this._property] < this.value;
  38334. case ValueCondition.IsEqual:
  38335. case ValueCondition.IsDifferent:
  38336. var check;
  38337. if (this.value.equals) {
  38338. check = this.value.equals(this._effectiveTarget[this._property]);
  38339. }
  38340. else {
  38341. check = this.value === this._effectiveTarget[this._property];
  38342. }
  38343. return this.operator === ValueCondition.IsEqual ? check : !check;
  38344. }
  38345. return false;
  38346. };
  38347. ValueCondition.prototype.serialize = function () {
  38348. return this._serialize({
  38349. name: "ValueCondition",
  38350. properties: [
  38351. BABYLON.Action._GetTargetProperty(this._target),
  38352. { name: "propertyPath", value: this.propertyPath },
  38353. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38354. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  38355. ]
  38356. });
  38357. };
  38358. ValueCondition.GetOperatorName = function (operator) {
  38359. switch (operator) {
  38360. case ValueCondition._IsEqual: return "IsEqual";
  38361. case ValueCondition._IsDifferent: return "IsDifferent";
  38362. case ValueCondition._IsGreater: return "IsGreater";
  38363. case ValueCondition._IsLesser: return "IsLesser";
  38364. default: return "";
  38365. }
  38366. };
  38367. // Statics
  38368. ValueCondition._IsEqual = 0;
  38369. ValueCondition._IsDifferent = 1;
  38370. ValueCondition._IsGreater = 2;
  38371. ValueCondition._IsLesser = 3;
  38372. return ValueCondition;
  38373. }(Condition));
  38374. BABYLON.ValueCondition = ValueCondition;
  38375. var PredicateCondition = (function (_super) {
  38376. __extends(PredicateCondition, _super);
  38377. function PredicateCondition(actionManager, predicate) {
  38378. var _this = _super.call(this, actionManager) || this;
  38379. _this.predicate = predicate;
  38380. return _this;
  38381. }
  38382. PredicateCondition.prototype.isValid = function () {
  38383. return this.predicate();
  38384. };
  38385. return PredicateCondition;
  38386. }(Condition));
  38387. BABYLON.PredicateCondition = PredicateCondition;
  38388. var StateCondition = (function (_super) {
  38389. __extends(StateCondition, _super);
  38390. function StateCondition(actionManager, target, value) {
  38391. var _this = _super.call(this, actionManager) || this;
  38392. _this.value = value;
  38393. _this._target = target;
  38394. return _this;
  38395. }
  38396. // Methods
  38397. StateCondition.prototype.isValid = function () {
  38398. return this._target.state === this.value;
  38399. };
  38400. StateCondition.prototype.serialize = function () {
  38401. return this._serialize({
  38402. name: "StateCondition",
  38403. properties: [
  38404. BABYLON.Action._GetTargetProperty(this._target),
  38405. { name: "value", value: this.value }
  38406. ]
  38407. });
  38408. };
  38409. return StateCondition;
  38410. }(Condition));
  38411. BABYLON.StateCondition = StateCondition;
  38412. })(BABYLON || (BABYLON = {}));
  38413. //# sourceMappingURL=babylon.condition.js.map
  38414. var BABYLON;
  38415. (function (BABYLON) {
  38416. var Action = (function () {
  38417. function Action(triggerOptions, condition) {
  38418. this.triggerOptions = triggerOptions;
  38419. if (triggerOptions.parameter) {
  38420. this.trigger = triggerOptions.trigger;
  38421. this._triggerParameter = triggerOptions.parameter;
  38422. }
  38423. else {
  38424. this.trigger = triggerOptions;
  38425. }
  38426. this._nextActiveAction = this;
  38427. this._condition = condition;
  38428. }
  38429. // Methods
  38430. Action.prototype._prepare = function () {
  38431. };
  38432. Action.prototype.getTriggerParameter = function () {
  38433. return this._triggerParameter;
  38434. };
  38435. Action.prototype._executeCurrent = function (evt) {
  38436. if (this._nextActiveAction._condition) {
  38437. var condition = this._nextActiveAction._condition;
  38438. var currentRenderId = this._actionManager.getScene().getRenderId();
  38439. // We cache the current evaluation for the current frame
  38440. if (condition._evaluationId === currentRenderId) {
  38441. if (!condition._currentResult) {
  38442. return;
  38443. }
  38444. }
  38445. else {
  38446. condition._evaluationId = currentRenderId;
  38447. if (!condition.isValid()) {
  38448. condition._currentResult = false;
  38449. return;
  38450. }
  38451. condition._currentResult = true;
  38452. }
  38453. }
  38454. this._nextActiveAction.execute(evt);
  38455. this.skipToNextActiveAction();
  38456. };
  38457. Action.prototype.execute = function (evt) {
  38458. };
  38459. Action.prototype.skipToNextActiveAction = function () {
  38460. if (this._nextActiveAction._child) {
  38461. if (!this._nextActiveAction._child._actionManager) {
  38462. this._nextActiveAction._child._actionManager = this._actionManager;
  38463. }
  38464. this._nextActiveAction = this._nextActiveAction._child;
  38465. }
  38466. else {
  38467. this._nextActiveAction = this;
  38468. }
  38469. };
  38470. Action.prototype.then = function (action) {
  38471. this._child = action;
  38472. action._actionManager = this._actionManager;
  38473. action._prepare();
  38474. return action;
  38475. };
  38476. Action.prototype._getProperty = function (propertyPath) {
  38477. return this._actionManager._getProperty(propertyPath);
  38478. };
  38479. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  38480. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38481. };
  38482. Action.prototype.serialize = function (parent) {
  38483. };
  38484. // Called by BABYLON.Action objects in serialize(...). Internal use
  38485. Action.prototype._serialize = function (serializedAction, parent) {
  38486. var serializationObject = {
  38487. type: 1,
  38488. children: [],
  38489. name: serializedAction.name,
  38490. properties: serializedAction.properties || []
  38491. };
  38492. // Serialize child
  38493. if (this._child) {
  38494. this._child.serialize(serializationObject);
  38495. }
  38496. // Check if "this" has a condition
  38497. if (this._condition) {
  38498. var serializedCondition = this._condition.serialize();
  38499. serializedCondition.children.push(serializationObject);
  38500. if (parent) {
  38501. parent.children.push(serializedCondition);
  38502. }
  38503. return serializedCondition;
  38504. }
  38505. if (parent) {
  38506. parent.children.push(serializationObject);
  38507. }
  38508. return serializationObject;
  38509. };
  38510. Action._SerializeValueAsString = function (value) {
  38511. if (typeof value === "number") {
  38512. return value.toString();
  38513. }
  38514. if (typeof value === "boolean") {
  38515. return value ? "true" : "false";
  38516. }
  38517. if (value instanceof BABYLON.Vector2) {
  38518. return value.x + ", " + value.y;
  38519. }
  38520. if (value instanceof BABYLON.Vector3) {
  38521. return value.x + ", " + value.y + ", " + value.z;
  38522. }
  38523. if (value instanceof BABYLON.Color3) {
  38524. return value.r + ", " + value.g + ", " + value.b;
  38525. }
  38526. if (value instanceof BABYLON.Color4) {
  38527. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  38528. }
  38529. return value; // string
  38530. };
  38531. Action._GetTargetProperty = function (target) {
  38532. return {
  38533. name: "target",
  38534. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  38535. : target instanceof BABYLON.Light ? "LightProperties"
  38536. : target instanceof BABYLON.Camera ? "CameraProperties"
  38537. : "SceneProperties",
  38538. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  38539. };
  38540. };
  38541. return Action;
  38542. }());
  38543. BABYLON.Action = Action;
  38544. })(BABYLON || (BABYLON = {}));
  38545. //# sourceMappingURL=babylon.action.js.map
  38546. var BABYLON;
  38547. (function (BABYLON) {
  38548. /**
  38549. * ActionEvent is the event beint sent when an action is triggered.
  38550. */
  38551. var ActionEvent = (function () {
  38552. /**
  38553. * @param source The mesh or sprite that triggered the action.
  38554. * @param pointerX The X mouse cursor position at the time of the event
  38555. * @param pointerY The Y mouse cursor position at the time of the event
  38556. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  38557. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  38558. */
  38559. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  38560. this.source = source;
  38561. this.pointerX = pointerX;
  38562. this.pointerY = pointerY;
  38563. this.meshUnderPointer = meshUnderPointer;
  38564. this.sourceEvent = sourceEvent;
  38565. this.additionalData = additionalData;
  38566. }
  38567. /**
  38568. * Helper function to auto-create an ActionEvent from a source mesh.
  38569. * @param source The source mesh that triggered the event
  38570. * @param evt {Event} The original (browser) event
  38571. */
  38572. ActionEvent.CreateNew = function (source, evt, additionalData) {
  38573. var scene = source.getScene();
  38574. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38575. };
  38576. /**
  38577. * Helper function to auto-create an ActionEvent from a source mesh.
  38578. * @param source The source sprite that triggered the event
  38579. * @param scene Scene associated with the sprite
  38580. * @param evt {Event} The original (browser) event
  38581. */
  38582. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  38583. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38584. };
  38585. /**
  38586. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  38587. * @param scene the scene where the event occurred
  38588. * @param evt {Event} The original (browser) event
  38589. */
  38590. ActionEvent.CreateNewFromScene = function (scene, evt) {
  38591. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  38592. };
  38593. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  38594. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  38595. };
  38596. return ActionEvent;
  38597. }());
  38598. BABYLON.ActionEvent = ActionEvent;
  38599. /**
  38600. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  38601. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  38602. */
  38603. var ActionManager = (function () {
  38604. function ActionManager(scene) {
  38605. // Members
  38606. this.actions = new Array();
  38607. this.hoverCursor = '';
  38608. this._scene = scene;
  38609. scene._actionManagers.push(this);
  38610. }
  38611. Object.defineProperty(ActionManager, "NothingTrigger", {
  38612. get: function () {
  38613. return ActionManager._NothingTrigger;
  38614. },
  38615. enumerable: true,
  38616. configurable: true
  38617. });
  38618. Object.defineProperty(ActionManager, "OnPickTrigger", {
  38619. get: function () {
  38620. return ActionManager._OnPickTrigger;
  38621. },
  38622. enumerable: true,
  38623. configurable: true
  38624. });
  38625. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  38626. get: function () {
  38627. return ActionManager._OnLeftPickTrigger;
  38628. },
  38629. enumerable: true,
  38630. configurable: true
  38631. });
  38632. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  38633. get: function () {
  38634. return ActionManager._OnRightPickTrigger;
  38635. },
  38636. enumerable: true,
  38637. configurable: true
  38638. });
  38639. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  38640. get: function () {
  38641. return ActionManager._OnCenterPickTrigger;
  38642. },
  38643. enumerable: true,
  38644. configurable: true
  38645. });
  38646. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  38647. get: function () {
  38648. return ActionManager._OnPickDownTrigger;
  38649. },
  38650. enumerable: true,
  38651. configurable: true
  38652. });
  38653. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  38654. get: function () {
  38655. return ActionManager._OnDoublePickTrigger;
  38656. },
  38657. enumerable: true,
  38658. configurable: true
  38659. });
  38660. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  38661. get: function () {
  38662. return ActionManager._OnPickUpTrigger;
  38663. },
  38664. enumerable: true,
  38665. configurable: true
  38666. });
  38667. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  38668. /// This trigger will only be raised if you also declared a OnPickDown
  38669. get: function () {
  38670. return ActionManager._OnPickOutTrigger;
  38671. },
  38672. enumerable: true,
  38673. configurable: true
  38674. });
  38675. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  38676. get: function () {
  38677. return ActionManager._OnLongPressTrigger;
  38678. },
  38679. enumerable: true,
  38680. configurable: true
  38681. });
  38682. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  38683. get: function () {
  38684. return ActionManager._OnPointerOverTrigger;
  38685. },
  38686. enumerable: true,
  38687. configurable: true
  38688. });
  38689. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  38690. get: function () {
  38691. return ActionManager._OnPointerOutTrigger;
  38692. },
  38693. enumerable: true,
  38694. configurable: true
  38695. });
  38696. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  38697. get: function () {
  38698. return ActionManager._OnEveryFrameTrigger;
  38699. },
  38700. enumerable: true,
  38701. configurable: true
  38702. });
  38703. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  38704. get: function () {
  38705. return ActionManager._OnIntersectionEnterTrigger;
  38706. },
  38707. enumerable: true,
  38708. configurable: true
  38709. });
  38710. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  38711. get: function () {
  38712. return ActionManager._OnIntersectionExitTrigger;
  38713. },
  38714. enumerable: true,
  38715. configurable: true
  38716. });
  38717. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  38718. get: function () {
  38719. return ActionManager._OnKeyDownTrigger;
  38720. },
  38721. enumerable: true,
  38722. configurable: true
  38723. });
  38724. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  38725. get: function () {
  38726. return ActionManager._OnKeyUpTrigger;
  38727. },
  38728. enumerable: true,
  38729. configurable: true
  38730. });
  38731. // Methods
  38732. ActionManager.prototype.dispose = function () {
  38733. var index = this._scene._actionManagers.indexOf(this);
  38734. for (var i = 0; i < this.actions.length; i++) {
  38735. var action = this.actions[i];
  38736. ActionManager.Triggers[action.trigger]--;
  38737. if (ActionManager.Triggers[action.trigger] === 0) {
  38738. delete ActionManager.Triggers[action.trigger];
  38739. }
  38740. }
  38741. if (index > -1) {
  38742. this._scene._actionManagers.splice(index, 1);
  38743. }
  38744. };
  38745. ActionManager.prototype.getScene = function () {
  38746. return this._scene;
  38747. };
  38748. /**
  38749. * Does this action manager handles actions of any of the given triggers
  38750. * @param {number[]} triggers - the triggers to be tested
  38751. * @return {boolean} whether one (or more) of the triggers is handeled
  38752. */
  38753. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  38754. for (var index = 0; index < this.actions.length; index++) {
  38755. var action = this.actions[index];
  38756. if (triggers.indexOf(action.trigger) > -1) {
  38757. return true;
  38758. }
  38759. }
  38760. return false;
  38761. };
  38762. /**
  38763. * Does this action manager handles actions of a given trigger
  38764. * @param {number} trigger - the trigger to be tested
  38765. * @return {boolean} whether the trigger is handeled
  38766. */
  38767. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  38768. for (var index = 0; index < this.actions.length; index++) {
  38769. var action = this.actions[index];
  38770. if (action.trigger === trigger) {
  38771. return true;
  38772. }
  38773. }
  38774. return false;
  38775. };
  38776. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  38777. /**
  38778. * Does this action manager has pointer triggers
  38779. * @return {boolean} whether or not it has pointer triggers
  38780. */
  38781. get: function () {
  38782. for (var index = 0; index < this.actions.length; index++) {
  38783. var action = this.actions[index];
  38784. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  38785. return true;
  38786. }
  38787. }
  38788. return false;
  38789. },
  38790. enumerable: true,
  38791. configurable: true
  38792. });
  38793. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  38794. /**
  38795. * Does this action manager has pick triggers
  38796. * @return {boolean} whether or not it has pick triggers
  38797. */
  38798. get: function () {
  38799. for (var index = 0; index < this.actions.length; index++) {
  38800. var action = this.actions[index];
  38801. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  38802. return true;
  38803. }
  38804. }
  38805. return false;
  38806. },
  38807. enumerable: true,
  38808. configurable: true
  38809. });
  38810. Object.defineProperty(ActionManager, "HasTriggers", {
  38811. /**
  38812. * Does exist one action manager with at least one trigger
  38813. * @return {boolean} whether or not it exists one action manager with one trigger
  38814. **/
  38815. get: function () {
  38816. for (var t in ActionManager.Triggers) {
  38817. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38818. return true;
  38819. }
  38820. }
  38821. return false;
  38822. },
  38823. enumerable: true,
  38824. configurable: true
  38825. });
  38826. Object.defineProperty(ActionManager, "HasPickTriggers", {
  38827. /**
  38828. * Does exist one action manager with at least one pick trigger
  38829. * @return {boolean} whether or not it exists one action manager with one pick trigger
  38830. **/
  38831. get: function () {
  38832. for (var t in ActionManager.Triggers) {
  38833. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38834. var t_int = parseInt(t);
  38835. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  38836. return true;
  38837. }
  38838. }
  38839. }
  38840. return false;
  38841. },
  38842. enumerable: true,
  38843. configurable: true
  38844. });
  38845. /**
  38846. * Does exist one action manager that handles actions of a given trigger
  38847. * @param {number} trigger - the trigger to be tested
  38848. * @return {boolean} whether the trigger is handeled by at least one action manager
  38849. **/
  38850. ActionManager.HasSpecificTrigger = function (trigger) {
  38851. for (var t in ActionManager.Triggers) {
  38852. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38853. var t_int = parseInt(t);
  38854. if (t_int === trigger) {
  38855. return true;
  38856. }
  38857. }
  38858. }
  38859. return false;
  38860. };
  38861. /**
  38862. * Registers an action to this action manager
  38863. * @param {BABYLON.Action} action - the action to be registered
  38864. * @return {BABYLON.Action} the action amended (prepared) after registration
  38865. */
  38866. ActionManager.prototype.registerAction = function (action) {
  38867. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  38868. if (this.getScene().actionManager !== this) {
  38869. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  38870. return null;
  38871. }
  38872. }
  38873. this.actions.push(action);
  38874. if (ActionManager.Triggers[action.trigger]) {
  38875. ActionManager.Triggers[action.trigger]++;
  38876. }
  38877. else {
  38878. ActionManager.Triggers[action.trigger] = 1;
  38879. }
  38880. action._actionManager = this;
  38881. action._prepare();
  38882. return action;
  38883. };
  38884. /**
  38885. * Process a specific trigger
  38886. * @param {number} trigger - the trigger to process
  38887. * @param evt {BABYLON.ActionEvent} the event details to be processed
  38888. */
  38889. ActionManager.prototype.processTrigger = function (trigger, evt) {
  38890. for (var index = 0; index < this.actions.length; index++) {
  38891. var action = this.actions[index];
  38892. if (action.trigger === trigger) {
  38893. if (trigger === ActionManager.OnKeyUpTrigger
  38894. || trigger === ActionManager.OnKeyDownTrigger) {
  38895. var parameter = action.getTriggerParameter();
  38896. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  38897. if (!parameter.toLowerCase) {
  38898. continue;
  38899. }
  38900. var lowerCase = parameter.toLowerCase();
  38901. if (lowerCase !== evt.sourceEvent.key) {
  38902. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  38903. var actualkey = String.fromCharCode(unicode).toLowerCase();
  38904. if (actualkey !== lowerCase) {
  38905. continue;
  38906. }
  38907. }
  38908. }
  38909. }
  38910. action._executeCurrent(evt);
  38911. }
  38912. }
  38913. };
  38914. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  38915. var properties = propertyPath.split(".");
  38916. for (var index = 0; index < properties.length - 1; index++) {
  38917. target = target[properties[index]];
  38918. }
  38919. return target;
  38920. };
  38921. ActionManager.prototype._getProperty = function (propertyPath) {
  38922. var properties = propertyPath.split(".");
  38923. return properties[properties.length - 1];
  38924. };
  38925. ActionManager.prototype.serialize = function (name) {
  38926. var root = {
  38927. children: [],
  38928. name: name,
  38929. type: 3,
  38930. properties: [] // Empty for root but required
  38931. };
  38932. for (var i = 0; i < this.actions.length; i++) {
  38933. var triggerObject = {
  38934. type: 0,
  38935. children: [],
  38936. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  38937. properties: []
  38938. };
  38939. var triggerOptions = this.actions[i].triggerOptions;
  38940. if (triggerOptions && typeof triggerOptions !== "number") {
  38941. if (triggerOptions.parameter instanceof BABYLON.Node) {
  38942. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  38943. }
  38944. else {
  38945. var parameter = {};
  38946. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  38947. if (triggerOptions.parameter.mesh) {
  38948. parameter._meshId = triggerOptions.parameter.mesh.id;
  38949. }
  38950. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  38951. }
  38952. }
  38953. // Serialize child action, recursively
  38954. this.actions[i].serialize(triggerObject);
  38955. // Add serialized trigger
  38956. root.children.push(triggerObject);
  38957. }
  38958. return root;
  38959. };
  38960. ActionManager.Parse = function (parsedActions, object, scene) {
  38961. var actionManager = new BABYLON.ActionManager(scene);
  38962. if (object === null)
  38963. scene.actionManager = actionManager;
  38964. else
  38965. object.actionManager = actionManager;
  38966. // instanciate a new object
  38967. var instanciate = function (name, params) {
  38968. var newInstance = Object.create(BABYLON[name].prototype);
  38969. newInstance.constructor.apply(newInstance, params);
  38970. return newInstance;
  38971. };
  38972. var parseParameter = function (name, value, target, propertyPath) {
  38973. if (propertyPath === null) {
  38974. // String, boolean or float
  38975. var floatValue = parseFloat(value);
  38976. if (value === "true" || value === "false")
  38977. return value === "true";
  38978. else
  38979. return isNaN(floatValue) ? value : floatValue;
  38980. }
  38981. var effectiveTarget = propertyPath.split(".");
  38982. var values = value.split(",");
  38983. // Get effective Target
  38984. for (var i = 0; i < effectiveTarget.length; i++) {
  38985. target = target[effectiveTarget[i]];
  38986. }
  38987. // Return appropriate value with its type
  38988. if (typeof (target) === "boolean")
  38989. return values[0] === "true";
  38990. if (typeof (target) === "string")
  38991. return values[0];
  38992. // Parameters with multiple values such as Vector3 etc.
  38993. var split = new Array();
  38994. for (var i = 0; i < values.length; i++)
  38995. split.push(parseFloat(values[i]));
  38996. if (target instanceof BABYLON.Vector3)
  38997. return BABYLON.Vector3.FromArray(split);
  38998. if (target instanceof BABYLON.Vector4)
  38999. return BABYLON.Vector4.FromArray(split);
  39000. if (target instanceof BABYLON.Color3)
  39001. return BABYLON.Color3.FromArray(split);
  39002. if (target instanceof BABYLON.Color4)
  39003. return BABYLON.Color4.FromArray(split);
  39004. return parseFloat(values[0]);
  39005. };
  39006. // traverse graph per trigger
  39007. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  39008. if (combineArray === void 0) { combineArray = null; }
  39009. if (parsedAction.detached)
  39010. return;
  39011. var parameters = new Array();
  39012. var target = null;
  39013. var propertyPath = null;
  39014. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  39015. // Parameters
  39016. if (parsedAction.type === 2)
  39017. parameters.push(actionManager);
  39018. else
  39019. parameters.push(trigger);
  39020. if (combine) {
  39021. var actions = new Array();
  39022. for (var j = 0; j < parsedAction.combine.length; j++) {
  39023. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  39024. }
  39025. parameters.push(actions);
  39026. }
  39027. else {
  39028. for (var i = 0; i < parsedAction.properties.length; i++) {
  39029. var value = parsedAction.properties[i].value;
  39030. var name = parsedAction.properties[i].name;
  39031. var targetType = parsedAction.properties[i].targetType;
  39032. if (name === "target")
  39033. if (targetType !== null && targetType === "SceneProperties")
  39034. value = target = scene;
  39035. else
  39036. value = target = scene.getNodeByName(value);
  39037. else if (name === "parent")
  39038. value = scene.getNodeByName(value);
  39039. else if (name === "sound")
  39040. value = scene.getSoundByName(value);
  39041. else if (name !== "propertyPath") {
  39042. if (parsedAction.type === 2 && name === "operator")
  39043. value = BABYLON.ValueCondition[value];
  39044. else
  39045. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  39046. }
  39047. else {
  39048. propertyPath = value;
  39049. }
  39050. parameters.push(value);
  39051. }
  39052. }
  39053. if (combineArray === null) {
  39054. parameters.push(condition);
  39055. }
  39056. else {
  39057. parameters.push(null);
  39058. }
  39059. // If interpolate value action
  39060. if (parsedAction.name === "InterpolateValueAction") {
  39061. var param = parameters[parameters.length - 2];
  39062. parameters[parameters.length - 1] = param;
  39063. parameters[parameters.length - 2] = condition;
  39064. }
  39065. // Action or condition(s) and not CombineAction
  39066. var newAction = instanciate(parsedAction.name, parameters);
  39067. if (newAction instanceof BABYLON.Condition && condition !== null) {
  39068. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  39069. if (action)
  39070. action.then(nothing);
  39071. else
  39072. actionManager.registerAction(nothing);
  39073. action = nothing;
  39074. }
  39075. if (combineArray === null) {
  39076. if (newAction instanceof BABYLON.Condition) {
  39077. condition = newAction;
  39078. newAction = action;
  39079. }
  39080. else {
  39081. condition = null;
  39082. if (action)
  39083. action.then(newAction);
  39084. else
  39085. actionManager.registerAction(newAction);
  39086. }
  39087. }
  39088. else {
  39089. combineArray.push(newAction);
  39090. }
  39091. for (var i = 0; i < parsedAction.children.length; i++)
  39092. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  39093. };
  39094. // triggers
  39095. for (var i = 0; i < parsedActions.children.length; i++) {
  39096. var triggerParams;
  39097. var trigger = parsedActions.children[i];
  39098. if (trigger.properties.length > 0) {
  39099. var param = trigger.properties[0].value;
  39100. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  39101. if (value._meshId) {
  39102. value.mesh = scene.getMeshByID(value._meshId);
  39103. }
  39104. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  39105. }
  39106. else
  39107. triggerParams = BABYLON.ActionManager[trigger.name];
  39108. for (var j = 0; j < trigger.children.length; j++) {
  39109. if (!trigger.detached)
  39110. traverse(trigger.children[j], triggerParams, null, null);
  39111. }
  39112. }
  39113. };
  39114. ActionManager.GetTriggerName = function (trigger) {
  39115. switch (trigger) {
  39116. case 0: return "NothingTrigger";
  39117. case 1: return "OnPickTrigger";
  39118. case 2: return "OnLeftPickTrigger";
  39119. case 3: return "OnRightPickTrigger";
  39120. case 4: return "OnCenterPickTrigger";
  39121. case 5: return "OnPickDownTrigger";
  39122. case 6: return "OnPickUpTrigger";
  39123. case 7: return "OnLongPressTrigger";
  39124. case 8: return "OnPointerOverTrigger";
  39125. case 9: return "OnPointerOutTrigger";
  39126. case 10: return "OnEveryFrameTrigger";
  39127. case 11: return "OnIntersectionEnterTrigger";
  39128. case 12: return "OnIntersectionExitTrigger";
  39129. case 13: return "OnKeyDownTrigger";
  39130. case 14: return "OnKeyUpTrigger";
  39131. case 15: return "OnPickOutTrigger";
  39132. default: return "";
  39133. }
  39134. };
  39135. // Statics
  39136. ActionManager._NothingTrigger = 0;
  39137. ActionManager._OnPickTrigger = 1;
  39138. ActionManager._OnLeftPickTrigger = 2;
  39139. ActionManager._OnRightPickTrigger = 3;
  39140. ActionManager._OnCenterPickTrigger = 4;
  39141. ActionManager._OnPickDownTrigger = 5;
  39142. ActionManager._OnDoublePickTrigger = 6;
  39143. ActionManager._OnPickUpTrigger = 7;
  39144. ActionManager._OnLongPressTrigger = 8;
  39145. ActionManager._OnPointerOverTrigger = 9;
  39146. ActionManager._OnPointerOutTrigger = 10;
  39147. ActionManager._OnEveryFrameTrigger = 11;
  39148. ActionManager._OnIntersectionEnterTrigger = 12;
  39149. ActionManager._OnIntersectionExitTrigger = 13;
  39150. ActionManager._OnKeyDownTrigger = 14;
  39151. ActionManager._OnKeyUpTrigger = 15;
  39152. ActionManager._OnPickOutTrigger = 16;
  39153. ActionManager.Triggers = {};
  39154. return ActionManager;
  39155. }());
  39156. BABYLON.ActionManager = ActionManager;
  39157. })(BABYLON || (BABYLON = {}));
  39158. //# sourceMappingURL=babylon.actionManager.js.map
  39159. var BABYLON;
  39160. (function (BABYLON) {
  39161. var InterpolateValueAction = (function (_super) {
  39162. __extends(InterpolateValueAction, _super);
  39163. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  39164. if (duration === void 0) { duration = 1000; }
  39165. var _this = _super.call(this, triggerOptions, condition) || this;
  39166. _this.propertyPath = propertyPath;
  39167. _this.value = value;
  39168. _this.duration = duration;
  39169. _this.stopOtherAnimations = stopOtherAnimations;
  39170. _this.onInterpolationDone = onInterpolationDone;
  39171. _this._target = _this._effectiveTarget = target;
  39172. return _this;
  39173. }
  39174. InterpolateValueAction.prototype._prepare = function () {
  39175. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39176. this._property = this._getProperty(this.propertyPath);
  39177. };
  39178. InterpolateValueAction.prototype.execute = function () {
  39179. var scene = this._actionManager.getScene();
  39180. var keys = [
  39181. {
  39182. frame: 0,
  39183. value: this._effectiveTarget[this._property]
  39184. }, {
  39185. frame: 100,
  39186. value: this.value
  39187. }
  39188. ];
  39189. var dataType;
  39190. if (typeof this.value === "number") {
  39191. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  39192. }
  39193. else if (this.value instanceof BABYLON.Color3) {
  39194. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  39195. }
  39196. else if (this.value instanceof BABYLON.Vector3) {
  39197. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  39198. }
  39199. else if (this.value instanceof BABYLON.Matrix) {
  39200. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  39201. }
  39202. else if (this.value instanceof BABYLON.Quaternion) {
  39203. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  39204. }
  39205. else {
  39206. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  39207. return;
  39208. }
  39209. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39210. animation.setKeys(keys);
  39211. if (this.stopOtherAnimations) {
  39212. scene.stopAnimation(this._effectiveTarget);
  39213. }
  39214. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  39215. };
  39216. InterpolateValueAction.prototype.serialize = function (parent) {
  39217. return _super.prototype._serialize.call(this, {
  39218. name: "InterpolateValueAction",
  39219. properties: [
  39220. BABYLON.Action._GetTargetProperty(this._target),
  39221. { name: "propertyPath", value: this.propertyPath },
  39222. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39223. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  39224. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  39225. ]
  39226. }, parent);
  39227. };
  39228. return InterpolateValueAction;
  39229. }(BABYLON.Action));
  39230. BABYLON.InterpolateValueAction = InterpolateValueAction;
  39231. })(BABYLON || (BABYLON = {}));
  39232. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  39233. var BABYLON;
  39234. (function (BABYLON) {
  39235. var SwitchBooleanAction = (function (_super) {
  39236. __extends(SwitchBooleanAction, _super);
  39237. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  39238. var _this = _super.call(this, triggerOptions, condition) || this;
  39239. _this.propertyPath = propertyPath;
  39240. _this._target = _this._effectiveTarget = target;
  39241. return _this;
  39242. }
  39243. SwitchBooleanAction.prototype._prepare = function () {
  39244. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39245. this._property = this._getProperty(this.propertyPath);
  39246. };
  39247. SwitchBooleanAction.prototype.execute = function () {
  39248. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  39249. };
  39250. SwitchBooleanAction.prototype.serialize = function (parent) {
  39251. return _super.prototype._serialize.call(this, {
  39252. name: "SwitchBooleanAction",
  39253. properties: [
  39254. BABYLON.Action._GetTargetProperty(this._target),
  39255. { name: "propertyPath", value: this.propertyPath }
  39256. ]
  39257. }, parent);
  39258. };
  39259. return SwitchBooleanAction;
  39260. }(BABYLON.Action));
  39261. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  39262. var SetStateAction = (function (_super) {
  39263. __extends(SetStateAction, _super);
  39264. function SetStateAction(triggerOptions, target, value, condition) {
  39265. var _this = _super.call(this, triggerOptions, condition) || this;
  39266. _this.value = value;
  39267. _this._target = target;
  39268. return _this;
  39269. }
  39270. SetStateAction.prototype.execute = function () {
  39271. this._target.state = this.value;
  39272. };
  39273. SetStateAction.prototype.serialize = function (parent) {
  39274. return _super.prototype._serialize.call(this, {
  39275. name: "SetStateAction",
  39276. properties: [
  39277. BABYLON.Action._GetTargetProperty(this._target),
  39278. { name: "value", value: this.value }
  39279. ]
  39280. }, parent);
  39281. };
  39282. return SetStateAction;
  39283. }(BABYLON.Action));
  39284. BABYLON.SetStateAction = SetStateAction;
  39285. var SetValueAction = (function (_super) {
  39286. __extends(SetValueAction, _super);
  39287. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  39288. var _this = _super.call(this, triggerOptions, condition) || this;
  39289. _this.propertyPath = propertyPath;
  39290. _this.value = value;
  39291. _this._target = _this._effectiveTarget = target;
  39292. return _this;
  39293. }
  39294. SetValueAction.prototype._prepare = function () {
  39295. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39296. this._property = this._getProperty(this.propertyPath);
  39297. };
  39298. SetValueAction.prototype.execute = function () {
  39299. this._effectiveTarget[this._property] = this.value;
  39300. if (this._target.markAsDirty) {
  39301. this._target.markAsDirty(this._property);
  39302. }
  39303. };
  39304. SetValueAction.prototype.serialize = function (parent) {
  39305. return _super.prototype._serialize.call(this, {
  39306. name: "SetValueAction",
  39307. properties: [
  39308. BABYLON.Action._GetTargetProperty(this._target),
  39309. { name: "propertyPath", value: this.propertyPath },
  39310. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39311. ]
  39312. }, parent);
  39313. };
  39314. return SetValueAction;
  39315. }(BABYLON.Action));
  39316. BABYLON.SetValueAction = SetValueAction;
  39317. var IncrementValueAction = (function (_super) {
  39318. __extends(IncrementValueAction, _super);
  39319. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  39320. var _this = _super.call(this, triggerOptions, condition) || this;
  39321. _this.propertyPath = propertyPath;
  39322. _this.value = value;
  39323. _this._target = _this._effectiveTarget = target;
  39324. return _this;
  39325. }
  39326. IncrementValueAction.prototype._prepare = function () {
  39327. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39328. this._property = this._getProperty(this.propertyPath);
  39329. if (typeof this._effectiveTarget[this._property] !== "number") {
  39330. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  39331. }
  39332. };
  39333. IncrementValueAction.prototype.execute = function () {
  39334. this._effectiveTarget[this._property] += this.value;
  39335. if (this._target.markAsDirty) {
  39336. this._target.markAsDirty(this._property);
  39337. }
  39338. };
  39339. IncrementValueAction.prototype.serialize = function (parent) {
  39340. return _super.prototype._serialize.call(this, {
  39341. name: "IncrementValueAction",
  39342. properties: [
  39343. BABYLON.Action._GetTargetProperty(this._target),
  39344. { name: "propertyPath", value: this.propertyPath },
  39345. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39346. ]
  39347. }, parent);
  39348. };
  39349. return IncrementValueAction;
  39350. }(BABYLON.Action));
  39351. BABYLON.IncrementValueAction = IncrementValueAction;
  39352. var PlayAnimationAction = (function (_super) {
  39353. __extends(PlayAnimationAction, _super);
  39354. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  39355. var _this = _super.call(this, triggerOptions, condition) || this;
  39356. _this.from = from;
  39357. _this.to = to;
  39358. _this.loop = loop;
  39359. _this._target = target;
  39360. return _this;
  39361. }
  39362. PlayAnimationAction.prototype._prepare = function () {
  39363. };
  39364. PlayAnimationAction.prototype.execute = function () {
  39365. var scene = this._actionManager.getScene();
  39366. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  39367. };
  39368. PlayAnimationAction.prototype.serialize = function (parent) {
  39369. return _super.prototype._serialize.call(this, {
  39370. name: "PlayAnimationAction",
  39371. properties: [
  39372. BABYLON.Action._GetTargetProperty(this._target),
  39373. { name: "from", value: String(this.from) },
  39374. { name: "to", value: String(this.to) },
  39375. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  39376. ]
  39377. }, parent);
  39378. };
  39379. return PlayAnimationAction;
  39380. }(BABYLON.Action));
  39381. BABYLON.PlayAnimationAction = PlayAnimationAction;
  39382. var StopAnimationAction = (function (_super) {
  39383. __extends(StopAnimationAction, _super);
  39384. function StopAnimationAction(triggerOptions, target, condition) {
  39385. var _this = _super.call(this, triggerOptions, condition) || this;
  39386. _this._target = target;
  39387. return _this;
  39388. }
  39389. StopAnimationAction.prototype._prepare = function () {
  39390. };
  39391. StopAnimationAction.prototype.execute = function () {
  39392. var scene = this._actionManager.getScene();
  39393. scene.stopAnimation(this._target);
  39394. };
  39395. StopAnimationAction.prototype.serialize = function (parent) {
  39396. return _super.prototype._serialize.call(this, {
  39397. name: "StopAnimationAction",
  39398. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  39399. }, parent);
  39400. };
  39401. return StopAnimationAction;
  39402. }(BABYLON.Action));
  39403. BABYLON.StopAnimationAction = StopAnimationAction;
  39404. var DoNothingAction = (function (_super) {
  39405. __extends(DoNothingAction, _super);
  39406. function DoNothingAction(triggerOptions, condition) {
  39407. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  39408. return _super.call(this, triggerOptions, condition) || this;
  39409. }
  39410. DoNothingAction.prototype.execute = function () {
  39411. };
  39412. DoNothingAction.prototype.serialize = function (parent) {
  39413. return _super.prototype._serialize.call(this, {
  39414. name: "DoNothingAction",
  39415. properties: []
  39416. }, parent);
  39417. };
  39418. return DoNothingAction;
  39419. }(BABYLON.Action));
  39420. BABYLON.DoNothingAction = DoNothingAction;
  39421. var CombineAction = (function (_super) {
  39422. __extends(CombineAction, _super);
  39423. function CombineAction(triggerOptions, children, condition) {
  39424. var _this = _super.call(this, triggerOptions, condition) || this;
  39425. _this.children = children;
  39426. return _this;
  39427. }
  39428. CombineAction.prototype._prepare = function () {
  39429. for (var index = 0; index < this.children.length; index++) {
  39430. this.children[index]._actionManager = this._actionManager;
  39431. this.children[index]._prepare();
  39432. }
  39433. };
  39434. CombineAction.prototype.execute = function (evt) {
  39435. for (var index = 0; index < this.children.length; index++) {
  39436. this.children[index].execute(evt);
  39437. }
  39438. };
  39439. CombineAction.prototype.serialize = function (parent) {
  39440. var serializationObject = _super.prototype._serialize.call(this, {
  39441. name: "CombineAction",
  39442. properties: [],
  39443. combine: []
  39444. }, parent);
  39445. for (var i = 0; i < this.children.length; i++) {
  39446. serializationObject.combine.push(this.children[i].serialize(null));
  39447. }
  39448. return serializationObject;
  39449. };
  39450. return CombineAction;
  39451. }(BABYLON.Action));
  39452. BABYLON.CombineAction = CombineAction;
  39453. var ExecuteCodeAction = (function (_super) {
  39454. __extends(ExecuteCodeAction, _super);
  39455. function ExecuteCodeAction(triggerOptions, func, condition) {
  39456. var _this = _super.call(this, triggerOptions, condition) || this;
  39457. _this.func = func;
  39458. return _this;
  39459. }
  39460. ExecuteCodeAction.prototype.execute = function (evt) {
  39461. this.func(evt);
  39462. };
  39463. return ExecuteCodeAction;
  39464. }(BABYLON.Action));
  39465. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  39466. var SetParentAction = (function (_super) {
  39467. __extends(SetParentAction, _super);
  39468. function SetParentAction(triggerOptions, target, parent, condition) {
  39469. var _this = _super.call(this, triggerOptions, condition) || this;
  39470. _this._target = target;
  39471. _this._parent = parent;
  39472. return _this;
  39473. }
  39474. SetParentAction.prototype._prepare = function () {
  39475. };
  39476. SetParentAction.prototype.execute = function () {
  39477. if (this._target.parent === this._parent) {
  39478. return;
  39479. }
  39480. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  39481. invertParentWorldMatrix.invert();
  39482. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  39483. this._target.parent = this._parent;
  39484. };
  39485. SetParentAction.prototype.serialize = function (parent) {
  39486. return _super.prototype._serialize.call(this, {
  39487. name: "SetParentAction",
  39488. properties: [
  39489. BABYLON.Action._GetTargetProperty(this._target),
  39490. BABYLON.Action._GetTargetProperty(this._parent),
  39491. ]
  39492. }, parent);
  39493. };
  39494. return SetParentAction;
  39495. }(BABYLON.Action));
  39496. BABYLON.SetParentAction = SetParentAction;
  39497. var PlaySoundAction = (function (_super) {
  39498. __extends(PlaySoundAction, _super);
  39499. function PlaySoundAction(triggerOptions, sound, condition) {
  39500. var _this = _super.call(this, triggerOptions, condition) || this;
  39501. _this._sound = sound;
  39502. return _this;
  39503. }
  39504. PlaySoundAction.prototype._prepare = function () {
  39505. };
  39506. PlaySoundAction.prototype.execute = function () {
  39507. if (this._sound !== undefined)
  39508. this._sound.play();
  39509. };
  39510. PlaySoundAction.prototype.serialize = function (parent) {
  39511. return _super.prototype._serialize.call(this, {
  39512. name: "PlaySoundAction",
  39513. properties: [{ name: "sound", value: this._sound.name }]
  39514. }, parent);
  39515. };
  39516. return PlaySoundAction;
  39517. }(BABYLON.Action));
  39518. BABYLON.PlaySoundAction = PlaySoundAction;
  39519. var StopSoundAction = (function (_super) {
  39520. __extends(StopSoundAction, _super);
  39521. function StopSoundAction(triggerOptions, sound, condition) {
  39522. var _this = _super.call(this, triggerOptions, condition) || this;
  39523. _this._sound = sound;
  39524. return _this;
  39525. }
  39526. StopSoundAction.prototype._prepare = function () {
  39527. };
  39528. StopSoundAction.prototype.execute = function () {
  39529. if (this._sound !== undefined)
  39530. this._sound.stop();
  39531. };
  39532. StopSoundAction.prototype.serialize = function (parent) {
  39533. return _super.prototype._serialize.call(this, {
  39534. name: "StopSoundAction",
  39535. properties: [{ name: "sound", value: this._sound.name }]
  39536. }, parent);
  39537. };
  39538. return StopSoundAction;
  39539. }(BABYLON.Action));
  39540. BABYLON.StopSoundAction = StopSoundAction;
  39541. })(BABYLON || (BABYLON = {}));
  39542. //# sourceMappingURL=babylon.directActions.js.map
  39543. var BABYLON;
  39544. (function (BABYLON) {
  39545. var SpriteManager = (function () {
  39546. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  39547. if (epsilon === void 0) { epsilon = 0.01; }
  39548. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39549. this.name = name;
  39550. this.sprites = new Array();
  39551. this.renderingGroupId = 0;
  39552. this.layerMask = 0x0FFFFFFF;
  39553. this.fogEnabled = true;
  39554. this.isPickable = false;
  39555. /**
  39556. * An event triggered when the manager is disposed.
  39557. * @type {BABYLON.Observable}
  39558. */
  39559. this.onDisposeObservable = new BABYLON.Observable();
  39560. this._vertexBuffers = {};
  39561. this._capacity = capacity;
  39562. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  39563. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39564. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39565. if (cellSize.width && cellSize.height) {
  39566. this.cellWidth = cellSize.width;
  39567. this.cellHeight = cellSize.height;
  39568. }
  39569. else if (cellSize !== undefined) {
  39570. this.cellWidth = cellSize;
  39571. this.cellHeight = cellSize;
  39572. }
  39573. else {
  39574. return;
  39575. }
  39576. this._epsilon = epsilon;
  39577. this._scene = scene;
  39578. this._scene.spriteManagers.push(this);
  39579. var indices = [];
  39580. var index = 0;
  39581. for (var count = 0; count < capacity; count++) {
  39582. indices.push(index);
  39583. indices.push(index + 1);
  39584. indices.push(index + 2);
  39585. indices.push(index);
  39586. indices.push(index + 2);
  39587. indices.push(index + 3);
  39588. index += 4;
  39589. }
  39590. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39591. // VBO
  39592. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  39593. this._vertexData = new Float32Array(capacity * 16 * 4);
  39594. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  39595. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  39596. var options = this._buffer.createVertexBuffer("options", 4, 4);
  39597. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  39598. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  39599. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  39600. this._vertexBuffers["options"] = options;
  39601. this._vertexBuffers["cellInfo"] = cellInfo;
  39602. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  39603. // Effects
  39604. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  39605. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  39606. }
  39607. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  39608. set: function (callback) {
  39609. if (this._onDisposeObserver) {
  39610. this.onDisposeObservable.remove(this._onDisposeObserver);
  39611. }
  39612. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  39613. },
  39614. enumerable: true,
  39615. configurable: true
  39616. });
  39617. Object.defineProperty(SpriteManager.prototype, "texture", {
  39618. get: function () {
  39619. return this._spriteTexture;
  39620. },
  39621. set: function (value) {
  39622. this._spriteTexture = value;
  39623. },
  39624. enumerable: true,
  39625. configurable: true
  39626. });
  39627. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  39628. var arrayOffset = index * 16;
  39629. if (offsetX === 0)
  39630. offsetX = this._epsilon;
  39631. else if (offsetX === 1)
  39632. offsetX = 1 - this._epsilon;
  39633. if (offsetY === 0)
  39634. offsetY = this._epsilon;
  39635. else if (offsetY === 1)
  39636. offsetY = 1 - this._epsilon;
  39637. this._vertexData[arrayOffset] = sprite.position.x;
  39638. this._vertexData[arrayOffset + 1] = sprite.position.y;
  39639. this._vertexData[arrayOffset + 2] = sprite.position.z;
  39640. this._vertexData[arrayOffset + 3] = sprite.angle;
  39641. this._vertexData[arrayOffset + 4] = sprite.width;
  39642. this._vertexData[arrayOffset + 5] = sprite.height;
  39643. this._vertexData[arrayOffset + 6] = offsetX;
  39644. this._vertexData[arrayOffset + 7] = offsetY;
  39645. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  39646. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  39647. var offset = (sprite.cellIndex / rowSize) >> 0;
  39648. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  39649. this._vertexData[arrayOffset + 11] = offset;
  39650. // Color
  39651. this._vertexData[arrayOffset + 12] = sprite.color.r;
  39652. this._vertexData[arrayOffset + 13] = sprite.color.g;
  39653. this._vertexData[arrayOffset + 14] = sprite.color.b;
  39654. this._vertexData[arrayOffset + 15] = sprite.color.a;
  39655. };
  39656. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  39657. var count = Math.min(this._capacity, this.sprites.length);
  39658. var min = BABYLON.Vector3.Zero();
  39659. var max = BABYLON.Vector3.Zero();
  39660. var distance = Number.MAX_VALUE;
  39661. var currentSprite;
  39662. var cameraSpacePosition = BABYLON.Vector3.Zero();
  39663. var cameraView = camera.getViewMatrix();
  39664. for (var index = 0; index < count; index++) {
  39665. var sprite = this.sprites[index];
  39666. if (!sprite) {
  39667. continue;
  39668. }
  39669. if (predicate) {
  39670. if (!predicate(sprite)) {
  39671. continue;
  39672. }
  39673. }
  39674. else if (!sprite.isPickable) {
  39675. continue;
  39676. }
  39677. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  39678. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  39679. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  39680. if (ray.intersectsBoxMinMax(min, max)) {
  39681. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  39682. if (distance > currentDistance) {
  39683. distance = currentDistance;
  39684. currentSprite = sprite;
  39685. if (fastCheck) {
  39686. break;
  39687. }
  39688. }
  39689. }
  39690. }
  39691. if (currentSprite) {
  39692. var result = new BABYLON.PickingInfo();
  39693. result.hit = true;
  39694. result.pickedSprite = currentSprite;
  39695. result.distance = distance;
  39696. return result;
  39697. }
  39698. return null;
  39699. };
  39700. SpriteManager.prototype.render = function () {
  39701. // Check
  39702. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  39703. return;
  39704. var engine = this._scene.getEngine();
  39705. var baseSize = this._spriteTexture.getBaseSize();
  39706. // Sprites
  39707. var deltaTime = engine.getDeltaTime();
  39708. var max = Math.min(this._capacity, this.sprites.length);
  39709. var rowSize = baseSize.width / this.cellWidth;
  39710. var offset = 0;
  39711. for (var index = 0; index < max; index++) {
  39712. var sprite = this.sprites[index];
  39713. if (!sprite) {
  39714. continue;
  39715. }
  39716. sprite._animate(deltaTime);
  39717. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  39718. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  39719. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  39720. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  39721. }
  39722. this._buffer.update(this._vertexData);
  39723. // Render
  39724. var effect = this._effectBase;
  39725. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39726. effect = this._effectFog;
  39727. }
  39728. engine.enableEffect(effect);
  39729. var viewMatrix = this._scene.getViewMatrix();
  39730. effect.setTexture("diffuseSampler", this._spriteTexture);
  39731. effect.setMatrix("view", viewMatrix);
  39732. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  39733. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  39734. // Fog
  39735. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39736. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  39737. effect.setColor3("vFogColor", this._scene.fogColor);
  39738. }
  39739. // VBOs
  39740. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39741. // Draw order
  39742. engine.setDepthFunctionToLessOrEqual();
  39743. effect.setBool("alphaTest", true);
  39744. engine.setColorWrite(false);
  39745. engine.draw(true, 0, max * 6);
  39746. engine.setColorWrite(true);
  39747. effect.setBool("alphaTest", false);
  39748. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39749. engine.draw(true, 0, max * 6);
  39750. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39751. };
  39752. SpriteManager.prototype.dispose = function () {
  39753. if (this._buffer) {
  39754. this._buffer.dispose();
  39755. this._buffer = null;
  39756. }
  39757. if (this._indexBuffer) {
  39758. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39759. this._indexBuffer = null;
  39760. }
  39761. if (this._spriteTexture) {
  39762. this._spriteTexture.dispose();
  39763. this._spriteTexture = null;
  39764. }
  39765. // Remove from scene
  39766. var index = this._scene.spriteManagers.indexOf(this);
  39767. this._scene.spriteManagers.splice(index, 1);
  39768. // Callback
  39769. this.onDisposeObservable.notifyObservers(this);
  39770. this.onDisposeObservable.clear();
  39771. };
  39772. return SpriteManager;
  39773. }());
  39774. BABYLON.SpriteManager = SpriteManager;
  39775. })(BABYLON || (BABYLON = {}));
  39776. //# sourceMappingURL=babylon.spriteManager.js.map
  39777. var BABYLON;
  39778. (function (BABYLON) {
  39779. var Sprite = (function () {
  39780. function Sprite(name, manager) {
  39781. this.name = name;
  39782. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39783. this.width = 1.0;
  39784. this.height = 1.0;
  39785. this.angle = 0;
  39786. this.cellIndex = 0;
  39787. this.invertU = 0;
  39788. this.invertV = 0;
  39789. this.animations = new Array();
  39790. this.isPickable = false;
  39791. this._animationStarted = false;
  39792. this._loopAnimation = false;
  39793. this._fromIndex = 0;
  39794. this._toIndex = 0;
  39795. this._delay = 0;
  39796. this._direction = 1;
  39797. this._frameCount = 0;
  39798. this._time = 0;
  39799. this._manager = manager;
  39800. this._manager.sprites.push(this);
  39801. this.position = BABYLON.Vector3.Zero();
  39802. }
  39803. Object.defineProperty(Sprite.prototype, "size", {
  39804. get: function () {
  39805. return this.width;
  39806. },
  39807. set: function (value) {
  39808. this.width = value;
  39809. this.height = value;
  39810. },
  39811. enumerable: true,
  39812. configurable: true
  39813. });
  39814. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  39815. this._fromIndex = from;
  39816. this._toIndex = to;
  39817. this._loopAnimation = loop;
  39818. this._delay = delay;
  39819. this._animationStarted = true;
  39820. this._direction = from < to ? 1 : -1;
  39821. this.cellIndex = from;
  39822. this._time = 0;
  39823. this._onAnimationEnd = onAnimationEnd;
  39824. };
  39825. Sprite.prototype.stopAnimation = function () {
  39826. this._animationStarted = false;
  39827. };
  39828. Sprite.prototype._animate = function (deltaTime) {
  39829. if (!this._animationStarted)
  39830. return;
  39831. this._time += deltaTime;
  39832. if (this._time > this._delay) {
  39833. this._time = this._time % this._delay;
  39834. this.cellIndex += this._direction;
  39835. if (this.cellIndex > this._toIndex) {
  39836. if (this._loopAnimation) {
  39837. this.cellIndex = this._fromIndex;
  39838. }
  39839. else {
  39840. this.cellIndex = this._toIndex;
  39841. this._animationStarted = false;
  39842. if (this._onAnimationEnd) {
  39843. this._onAnimationEnd();
  39844. }
  39845. if (this.disposeWhenFinishedAnimating) {
  39846. this.dispose();
  39847. }
  39848. }
  39849. }
  39850. }
  39851. };
  39852. Sprite.prototype.dispose = function () {
  39853. for (var i = 0; i < this._manager.sprites.length; i++) {
  39854. if (this._manager.sprites[i] == this) {
  39855. this._manager.sprites.splice(i, 1);
  39856. }
  39857. }
  39858. };
  39859. return Sprite;
  39860. }());
  39861. BABYLON.Sprite = Sprite;
  39862. })(BABYLON || (BABYLON = {}));
  39863. //# sourceMappingURL=babylon.sprite.js.map
  39864. var BABYLON;
  39865. (function (BABYLON) {
  39866. var IntersectionInfo = (function () {
  39867. function IntersectionInfo(bu, bv, distance) {
  39868. this.bu = bu;
  39869. this.bv = bv;
  39870. this.distance = distance;
  39871. this.faceId = 0;
  39872. this.subMeshId = 0;
  39873. }
  39874. return IntersectionInfo;
  39875. }());
  39876. BABYLON.IntersectionInfo = IntersectionInfo;
  39877. var PickingInfo = (function () {
  39878. function PickingInfo() {
  39879. this.hit = false;
  39880. this.distance = 0;
  39881. this.pickedPoint = null;
  39882. this.pickedMesh = null;
  39883. this.bu = 0;
  39884. this.bv = 0;
  39885. this.faceId = -1;
  39886. this.subMeshId = 0;
  39887. this.pickedSprite = null;
  39888. }
  39889. // Methods
  39890. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  39891. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  39892. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  39893. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39894. return null;
  39895. }
  39896. var indices = this.pickedMesh.getIndices();
  39897. var result;
  39898. if (useVerticesNormals) {
  39899. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39900. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  39901. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  39902. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  39903. normal0 = normal0.scale(this.bu);
  39904. normal1 = normal1.scale(this.bv);
  39905. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  39906. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  39907. }
  39908. else {
  39909. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39910. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  39911. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  39912. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  39913. var p1p2 = vertex1.subtract(vertex2);
  39914. var p3p2 = vertex3.subtract(vertex2);
  39915. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  39916. }
  39917. if (useWorldCoordinates) {
  39918. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  39919. }
  39920. return BABYLON.Vector3.Normalize(result);
  39921. };
  39922. PickingInfo.prototype.getTextureCoordinates = function () {
  39923. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39924. return null;
  39925. }
  39926. var indices = this.pickedMesh.getIndices();
  39927. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39928. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  39929. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  39930. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  39931. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  39932. uv1 = uv1.scale(this.bu);
  39933. uv2 = uv2.scale(this.bv);
  39934. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  39935. };
  39936. return PickingInfo;
  39937. }());
  39938. BABYLON.PickingInfo = PickingInfo;
  39939. })(BABYLON || (BABYLON = {}));
  39940. //# sourceMappingURL=babylon.pickingInfo.js.map
  39941. var BABYLON;
  39942. (function (BABYLON) {
  39943. var Ray = (function () {
  39944. function Ray(origin, direction, length) {
  39945. if (length === void 0) { length = Number.MAX_VALUE; }
  39946. this.origin = origin;
  39947. this.direction = direction;
  39948. this.length = length;
  39949. }
  39950. // Methods
  39951. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  39952. var d = 0.0;
  39953. var maxValue = Number.MAX_VALUE;
  39954. var inv;
  39955. var min;
  39956. var max;
  39957. var temp;
  39958. if (Math.abs(this.direction.x) < 0.0000001) {
  39959. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  39960. return false;
  39961. }
  39962. }
  39963. else {
  39964. inv = 1.0 / this.direction.x;
  39965. min = (minimum.x - this.origin.x) * inv;
  39966. max = (maximum.x - this.origin.x) * inv;
  39967. if (max === -Infinity) {
  39968. max = Infinity;
  39969. }
  39970. if (min > max) {
  39971. temp = min;
  39972. min = max;
  39973. max = temp;
  39974. }
  39975. d = Math.max(min, d);
  39976. maxValue = Math.min(max, maxValue);
  39977. if (d > maxValue) {
  39978. return false;
  39979. }
  39980. }
  39981. if (Math.abs(this.direction.y) < 0.0000001) {
  39982. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  39983. return false;
  39984. }
  39985. }
  39986. else {
  39987. inv = 1.0 / this.direction.y;
  39988. min = (minimum.y - this.origin.y) * inv;
  39989. max = (maximum.y - this.origin.y) * inv;
  39990. if (max === -Infinity) {
  39991. max = Infinity;
  39992. }
  39993. if (min > max) {
  39994. temp = min;
  39995. min = max;
  39996. max = temp;
  39997. }
  39998. d = Math.max(min, d);
  39999. maxValue = Math.min(max, maxValue);
  40000. if (d > maxValue) {
  40001. return false;
  40002. }
  40003. }
  40004. if (Math.abs(this.direction.z) < 0.0000001) {
  40005. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  40006. return false;
  40007. }
  40008. }
  40009. else {
  40010. inv = 1.0 / this.direction.z;
  40011. min = (minimum.z - this.origin.z) * inv;
  40012. max = (maximum.z - this.origin.z) * inv;
  40013. if (max === -Infinity) {
  40014. max = Infinity;
  40015. }
  40016. if (min > max) {
  40017. temp = min;
  40018. min = max;
  40019. max = temp;
  40020. }
  40021. d = Math.max(min, d);
  40022. maxValue = Math.min(max, maxValue);
  40023. if (d > maxValue) {
  40024. return false;
  40025. }
  40026. }
  40027. return true;
  40028. };
  40029. Ray.prototype.intersectsBox = function (box) {
  40030. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  40031. };
  40032. Ray.prototype.intersectsSphere = function (sphere) {
  40033. var x = sphere.center.x - this.origin.x;
  40034. var y = sphere.center.y - this.origin.y;
  40035. var z = sphere.center.z - this.origin.z;
  40036. var pyth = (x * x) + (y * y) + (z * z);
  40037. var rr = sphere.radius * sphere.radius;
  40038. if (pyth <= rr) {
  40039. return true;
  40040. }
  40041. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  40042. if (dot < 0.0) {
  40043. return false;
  40044. }
  40045. var temp = pyth - (dot * dot);
  40046. return temp <= rr;
  40047. };
  40048. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  40049. if (!this._edge1) {
  40050. this._edge1 = BABYLON.Vector3.Zero();
  40051. this._edge2 = BABYLON.Vector3.Zero();
  40052. this._pvec = BABYLON.Vector3.Zero();
  40053. this._tvec = BABYLON.Vector3.Zero();
  40054. this._qvec = BABYLON.Vector3.Zero();
  40055. }
  40056. vertex1.subtractToRef(vertex0, this._edge1);
  40057. vertex2.subtractToRef(vertex0, this._edge2);
  40058. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  40059. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  40060. if (det === 0) {
  40061. return null;
  40062. }
  40063. var invdet = 1 / det;
  40064. this.origin.subtractToRef(vertex0, this._tvec);
  40065. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  40066. if (bu < 0 || bu > 1.0) {
  40067. return null;
  40068. }
  40069. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  40070. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  40071. if (bv < 0 || bu + bv > 1.0) {
  40072. return null;
  40073. }
  40074. //check if the distance is longer than the predefined length.
  40075. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  40076. if (distance > this.length) {
  40077. return null;
  40078. }
  40079. return new BABYLON.IntersectionInfo(bu, bv, distance);
  40080. };
  40081. Ray.prototype.intersectsPlane = function (plane) {
  40082. var distance;
  40083. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  40084. if (Math.abs(result1) < 9.99999997475243E-07) {
  40085. return null;
  40086. }
  40087. else {
  40088. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  40089. distance = (-plane.d - result2) / result1;
  40090. if (distance < 0.0) {
  40091. if (distance < -9.99999997475243E-07) {
  40092. return null;
  40093. }
  40094. else {
  40095. return 0;
  40096. }
  40097. }
  40098. return distance;
  40099. }
  40100. };
  40101. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  40102. var tm = BABYLON.Tmp.Matrix[0];
  40103. mesh.getWorldMatrix().invertToRef(tm);
  40104. if (this._tmpRay) {
  40105. Ray.TransformToRef(this, tm, this._tmpRay);
  40106. }
  40107. else {
  40108. this._tmpRay = Ray.Transform(this, tm);
  40109. }
  40110. return mesh.intersects(this._tmpRay, fastCheck);
  40111. };
  40112. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  40113. if (results) {
  40114. results.length = 0;
  40115. }
  40116. else {
  40117. results = [];
  40118. }
  40119. for (var i = 0; i < meshes.length; i++) {
  40120. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  40121. if (pickInfo.hit) {
  40122. results.push(pickInfo);
  40123. }
  40124. }
  40125. results.sort(this._comparePickingInfo);
  40126. return results;
  40127. };
  40128. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  40129. if (pickingInfoA.distance < pickingInfoB.distance) {
  40130. return -1;
  40131. }
  40132. else if (pickingInfoA.distance > pickingInfoB.distance) {
  40133. return 1;
  40134. }
  40135. else {
  40136. return 0;
  40137. }
  40138. };
  40139. /**
  40140. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  40141. * @param sega the first point of the segment to test the intersection against
  40142. * @param segb the second point of the segment to test the intersection against
  40143. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  40144. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  40145. */
  40146. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  40147. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  40148. var u = segb.subtract(sega);
  40149. var v = rsegb.subtract(this.origin);
  40150. var w = sega.subtract(this.origin);
  40151. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  40152. var b = BABYLON.Vector3.Dot(u, v);
  40153. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  40154. var d = BABYLON.Vector3.Dot(u, w);
  40155. var e = BABYLON.Vector3.Dot(v, w);
  40156. var D = a * c - b * b; // always >= 0
  40157. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  40158. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  40159. // compute the line parameters of the two closest points
  40160. if (D < Ray.smallnum) {
  40161. sN = 0.0; // force using point P0 on segment S1
  40162. sD = 1.0; // to prevent possible division by 0.0 later
  40163. tN = e;
  40164. tD = c;
  40165. }
  40166. else {
  40167. sN = (b * e - c * d);
  40168. tN = (a * e - b * d);
  40169. if (sN < 0.0) {
  40170. sN = 0.0;
  40171. tN = e;
  40172. tD = c;
  40173. }
  40174. else if (sN > sD) {
  40175. sN = sD;
  40176. tN = e + b;
  40177. tD = c;
  40178. }
  40179. }
  40180. if (tN < 0.0) {
  40181. tN = 0.0;
  40182. // recompute sc for this edge
  40183. if (-d < 0.0) {
  40184. sN = 0.0;
  40185. }
  40186. else if (-d > a)
  40187. sN = sD;
  40188. else {
  40189. sN = -d;
  40190. sD = a;
  40191. }
  40192. }
  40193. else if (tN > tD) {
  40194. tN = tD;
  40195. // recompute sc for this edge
  40196. if ((-d + b) < 0.0) {
  40197. sN = 0;
  40198. }
  40199. else if ((-d + b) > a) {
  40200. sN = sD;
  40201. }
  40202. else {
  40203. sN = (-d + b);
  40204. sD = a;
  40205. }
  40206. }
  40207. // finally do the division to get sc and tc
  40208. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  40209. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  40210. // get the difference of the two closest points
  40211. var qtc = v.multiplyByFloats(tc, tc, tc);
  40212. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  40213. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  40214. if (isIntersected) {
  40215. return qtc.length();
  40216. }
  40217. return -1;
  40218. };
  40219. // Statics
  40220. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  40221. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  40222. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  40223. var direction = end.subtract(start);
  40224. direction.normalize();
  40225. return new Ray(start, direction);
  40226. };
  40227. /**
  40228. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  40229. * transformed to the given world matrix.
  40230. * @param origin The origin point
  40231. * @param end The end point
  40232. * @param world a matrix to transform the ray to. Default is the identity matrix.
  40233. */
  40234. Ray.CreateNewFromTo = function (origin, end, world) {
  40235. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  40236. var direction = end.subtract(origin);
  40237. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  40238. direction.normalize();
  40239. return Ray.Transform(new Ray(origin, direction, length), world);
  40240. };
  40241. Ray.Transform = function (ray, matrix) {
  40242. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  40243. Ray.TransformToRef(ray, matrix, result);
  40244. return result;
  40245. };
  40246. Ray.TransformToRef = function (ray, matrix, result) {
  40247. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  40248. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  40249. result.length = ray.length;
  40250. var dir = result.direction;
  40251. var len = dir.length();
  40252. if (!(len === 0 || len === 1)) {
  40253. var num = 1.0 / len;
  40254. dir.x *= num;
  40255. dir.y *= num;
  40256. dir.z *= num;
  40257. result.length *= len;
  40258. }
  40259. };
  40260. Ray.smallnum = 0.00000001;
  40261. Ray.rayl = 10e8;
  40262. return Ray;
  40263. }());
  40264. BABYLON.Ray = Ray;
  40265. })(BABYLON || (BABYLON = {}));
  40266. //# sourceMappingURL=babylon.ray.js.map
  40267. var BABYLON;
  40268. (function (BABYLON) {
  40269. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  40270. if (boxMin.x > sphereCenter.x + sphereRadius)
  40271. return false;
  40272. if (sphereCenter.x - sphereRadius > boxMax.x)
  40273. return false;
  40274. if (boxMin.y > sphereCenter.y + sphereRadius)
  40275. return false;
  40276. if (sphereCenter.y - sphereRadius > boxMax.y)
  40277. return false;
  40278. if (boxMin.z > sphereCenter.z + sphereRadius)
  40279. return false;
  40280. if (sphereCenter.z - sphereRadius > boxMax.z)
  40281. return false;
  40282. return true;
  40283. };
  40284. var getLowestRoot = (function () {
  40285. var result = { root: 0, found: false };
  40286. return function (a, b, c, maxR) {
  40287. result.root = 0;
  40288. result.found = false;
  40289. var determinant = b * b - 4.0 * a * c;
  40290. if (determinant < 0)
  40291. return result;
  40292. var sqrtD = Math.sqrt(determinant);
  40293. var r1 = (-b - sqrtD) / (2.0 * a);
  40294. var r2 = (-b + sqrtD) / (2.0 * a);
  40295. if (r1 > r2) {
  40296. var temp = r2;
  40297. r2 = r1;
  40298. r1 = temp;
  40299. }
  40300. if (r1 > 0 && r1 < maxR) {
  40301. result.root = r1;
  40302. result.found = true;
  40303. return result;
  40304. }
  40305. if (r2 > 0 && r2 < maxR) {
  40306. result.root = r2;
  40307. result.found = true;
  40308. return result;
  40309. }
  40310. return result;
  40311. };
  40312. })();
  40313. var Collider = (function () {
  40314. function Collider() {
  40315. this.radius = BABYLON.Vector3.One();
  40316. this.retry = 0;
  40317. this.basePointWorld = BABYLON.Vector3.Zero();
  40318. this.velocityWorld = BABYLON.Vector3.Zero();
  40319. this.normalizedVelocity = BABYLON.Vector3.Zero();
  40320. this._collisionPoint = BABYLON.Vector3.Zero();
  40321. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  40322. this._tempVector = BABYLON.Vector3.Zero();
  40323. this._tempVector2 = BABYLON.Vector3.Zero();
  40324. this._tempVector3 = BABYLON.Vector3.Zero();
  40325. this._tempVector4 = BABYLON.Vector3.Zero();
  40326. this._edge = BABYLON.Vector3.Zero();
  40327. this._baseToVertex = BABYLON.Vector3.Zero();
  40328. this._destinationPoint = BABYLON.Vector3.Zero();
  40329. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  40330. this._displacementVector = BABYLON.Vector3.Zero();
  40331. this._collisionMask = -1;
  40332. }
  40333. Object.defineProperty(Collider.prototype, "collisionMask", {
  40334. get: function () {
  40335. return this._collisionMask;
  40336. },
  40337. set: function (mask) {
  40338. this._collisionMask = !isNaN(mask) ? mask : -1;
  40339. },
  40340. enumerable: true,
  40341. configurable: true
  40342. });
  40343. // Methods
  40344. Collider.prototype._initialize = function (source, dir, e) {
  40345. this.velocity = dir;
  40346. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  40347. this.basePoint = source;
  40348. source.multiplyToRef(this.radius, this.basePointWorld);
  40349. dir.multiplyToRef(this.radius, this.velocityWorld);
  40350. this.velocityWorldLength = this.velocityWorld.length();
  40351. this.epsilon = e;
  40352. this.collisionFound = false;
  40353. };
  40354. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  40355. pa.subtractToRef(point, this._tempVector);
  40356. pb.subtractToRef(point, this._tempVector2);
  40357. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  40358. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40359. if (d < 0)
  40360. return false;
  40361. pc.subtractToRef(point, this._tempVector3);
  40362. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  40363. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40364. if (d < 0)
  40365. return false;
  40366. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  40367. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40368. return d >= 0;
  40369. };
  40370. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  40371. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  40372. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  40373. if (distance > this.velocityWorldLength + max + sphereRadius) {
  40374. return false;
  40375. }
  40376. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  40377. return false;
  40378. return true;
  40379. };
  40380. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  40381. var t0;
  40382. var embeddedInPlane = false;
  40383. //defensive programming, actually not needed.
  40384. if (!trianglePlaneArray) {
  40385. trianglePlaneArray = [];
  40386. }
  40387. if (!trianglePlaneArray[faceIndex]) {
  40388. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  40389. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  40390. }
  40391. var trianglePlane = trianglePlaneArray[faceIndex];
  40392. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  40393. return;
  40394. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  40395. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  40396. if (normalDotVelocity == 0) {
  40397. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  40398. return;
  40399. embeddedInPlane = true;
  40400. t0 = 0;
  40401. }
  40402. else {
  40403. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40404. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40405. if (t0 > t1) {
  40406. var temp = t1;
  40407. t1 = t0;
  40408. t0 = temp;
  40409. }
  40410. if (t0 > 1.0 || t1 < 0.0)
  40411. return;
  40412. if (t0 < 0)
  40413. t0 = 0;
  40414. if (t0 > 1.0)
  40415. t0 = 1.0;
  40416. }
  40417. this._collisionPoint.copyFromFloats(0, 0, 0);
  40418. var found = false;
  40419. var t = 1.0;
  40420. if (!embeddedInPlane) {
  40421. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  40422. this.velocity.scaleToRef(t0, this._tempVector);
  40423. this._planeIntersectionPoint.addInPlace(this._tempVector);
  40424. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  40425. found = true;
  40426. t = t0;
  40427. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  40428. }
  40429. }
  40430. if (!found) {
  40431. var velocitySquaredLength = this.velocity.lengthSquared();
  40432. var a = velocitySquaredLength;
  40433. this.basePoint.subtractToRef(p1, this._tempVector);
  40434. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40435. var c = this._tempVector.lengthSquared() - 1.0;
  40436. var lowestRoot = getLowestRoot(a, b, c, t);
  40437. if (lowestRoot.found) {
  40438. t = lowestRoot.root;
  40439. found = true;
  40440. this._collisionPoint.copyFrom(p1);
  40441. }
  40442. this.basePoint.subtractToRef(p2, this._tempVector);
  40443. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40444. c = this._tempVector.lengthSquared() - 1.0;
  40445. lowestRoot = getLowestRoot(a, b, c, t);
  40446. if (lowestRoot.found) {
  40447. t = lowestRoot.root;
  40448. found = true;
  40449. this._collisionPoint.copyFrom(p2);
  40450. }
  40451. this.basePoint.subtractToRef(p3, this._tempVector);
  40452. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40453. c = this._tempVector.lengthSquared() - 1.0;
  40454. lowestRoot = getLowestRoot(a, b, c, t);
  40455. if (lowestRoot.found) {
  40456. t = lowestRoot.root;
  40457. found = true;
  40458. this._collisionPoint.copyFrom(p3);
  40459. }
  40460. p2.subtractToRef(p1, this._edge);
  40461. p1.subtractToRef(this.basePoint, this._baseToVertex);
  40462. var edgeSquaredLength = this._edge.lengthSquared();
  40463. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40464. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40465. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40466. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40467. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40468. lowestRoot = getLowestRoot(a, b, c, t);
  40469. if (lowestRoot.found) {
  40470. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40471. if (f >= 0.0 && f <= 1.0) {
  40472. t = lowestRoot.root;
  40473. found = true;
  40474. this._edge.scaleInPlace(f);
  40475. p1.addToRef(this._edge, this._collisionPoint);
  40476. }
  40477. }
  40478. p3.subtractToRef(p2, this._edge);
  40479. p2.subtractToRef(this.basePoint, this._baseToVertex);
  40480. edgeSquaredLength = this._edge.lengthSquared();
  40481. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40482. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40483. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40484. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40485. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40486. lowestRoot = getLowestRoot(a, b, c, t);
  40487. if (lowestRoot.found) {
  40488. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40489. if (f >= 0.0 && f <= 1.0) {
  40490. t = lowestRoot.root;
  40491. found = true;
  40492. this._edge.scaleInPlace(f);
  40493. p2.addToRef(this._edge, this._collisionPoint);
  40494. }
  40495. }
  40496. p1.subtractToRef(p3, this._edge);
  40497. p3.subtractToRef(this.basePoint, this._baseToVertex);
  40498. edgeSquaredLength = this._edge.lengthSquared();
  40499. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40500. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40501. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40502. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40503. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40504. lowestRoot = getLowestRoot(a, b, c, t);
  40505. if (lowestRoot.found) {
  40506. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40507. if (f >= 0.0 && f <= 1.0) {
  40508. t = lowestRoot.root;
  40509. found = true;
  40510. this._edge.scaleInPlace(f);
  40511. p3.addToRef(this._edge, this._collisionPoint);
  40512. }
  40513. }
  40514. }
  40515. if (found) {
  40516. var distToCollision = t * this.velocity.length();
  40517. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  40518. if (!this.intersectionPoint) {
  40519. this.intersectionPoint = this._collisionPoint.clone();
  40520. }
  40521. else {
  40522. this.intersectionPoint.copyFrom(this._collisionPoint);
  40523. }
  40524. this.nearestDistance = distToCollision;
  40525. this.collisionFound = true;
  40526. }
  40527. }
  40528. };
  40529. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  40530. for (var i = indexStart; i < indexEnd; i += 3) {
  40531. var p1 = pts[indices[i] - decal];
  40532. var p2 = pts[indices[i + 1] - decal];
  40533. var p3 = pts[indices[i + 2] - decal];
  40534. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  40535. }
  40536. };
  40537. Collider.prototype._getResponse = function (pos, vel) {
  40538. pos.addToRef(vel, this._destinationPoint);
  40539. vel.scaleInPlace((this.nearestDistance / vel.length()));
  40540. this.basePoint.addToRef(vel, pos);
  40541. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  40542. this._slidePlaneNormal.normalize();
  40543. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  40544. pos.addInPlace(this._displacementVector);
  40545. this.intersectionPoint.addInPlace(this._displacementVector);
  40546. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  40547. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  40548. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  40549. };
  40550. return Collider;
  40551. }());
  40552. BABYLON.Collider = Collider;
  40553. })(BABYLON || (BABYLON = {}));
  40554. //# sourceMappingURL=babylon.collider.js.map
  40555. var BABYLON;
  40556. (function (BABYLON) {
  40557. //WebWorker code will be inserted to this variable.
  40558. BABYLON.CollisionWorker = "";
  40559. var WorkerTaskType;
  40560. (function (WorkerTaskType) {
  40561. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  40562. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  40563. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  40564. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  40565. var WorkerReplyType;
  40566. (function (WorkerReplyType) {
  40567. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  40568. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  40569. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  40570. var CollisionCoordinatorWorker = (function () {
  40571. function CollisionCoordinatorWorker() {
  40572. var _this = this;
  40573. this._scaledPosition = BABYLON.Vector3.Zero();
  40574. this._scaledVelocity = BABYLON.Vector3.Zero();
  40575. this.onMeshUpdated = function (mesh) {
  40576. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  40577. };
  40578. this.onGeometryUpdated = function (geometry) {
  40579. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  40580. };
  40581. this._afterRender = function () {
  40582. if (!_this._init)
  40583. return;
  40584. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  40585. return;
  40586. }
  40587. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  40588. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  40589. if (_this._runningUpdated > 4) {
  40590. return;
  40591. }
  40592. ++_this._runningUpdated;
  40593. var payload = {
  40594. updatedMeshes: _this._addUpdateMeshesList,
  40595. updatedGeometries: _this._addUpdateGeometriesList,
  40596. removedGeometries: _this._toRemoveGeometryArray,
  40597. removedMeshes: _this._toRemoveMeshesArray
  40598. };
  40599. var message = {
  40600. payload: payload,
  40601. taskType: WorkerTaskType.UPDATE
  40602. };
  40603. var serializable = [];
  40604. for (var id in payload.updatedGeometries) {
  40605. if (payload.updatedGeometries.hasOwnProperty(id)) {
  40606. //prepare transferables
  40607. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  40608. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  40609. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  40610. }
  40611. }
  40612. _this._worker.postMessage(message, serializable);
  40613. _this._addUpdateMeshesList = {};
  40614. _this._addUpdateGeometriesList = {};
  40615. _this._toRemoveGeometryArray = [];
  40616. _this._toRemoveMeshesArray = [];
  40617. };
  40618. this._onMessageFromWorker = function (e) {
  40619. var returnData = e.data;
  40620. if (returnData.error != WorkerReplyType.SUCCESS) {
  40621. //TODO what errors can be returned from the worker?
  40622. BABYLON.Tools.Warn("error returned from worker!");
  40623. return;
  40624. }
  40625. switch (returnData.taskType) {
  40626. case WorkerTaskType.INIT:
  40627. _this._init = true;
  40628. //Update the worked with ALL of the scene's current state
  40629. _this._scene.meshes.forEach(function (mesh) {
  40630. _this.onMeshAdded(mesh);
  40631. });
  40632. _this._scene.getGeometries().forEach(function (geometry) {
  40633. _this.onGeometryAdded(geometry);
  40634. });
  40635. break;
  40636. case WorkerTaskType.UPDATE:
  40637. _this._runningUpdated--;
  40638. break;
  40639. case WorkerTaskType.COLLIDE:
  40640. _this._runningCollisionTask = false;
  40641. var returnPayload = returnData.payload;
  40642. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  40643. return;
  40644. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  40645. //cleanup
  40646. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  40647. break;
  40648. }
  40649. };
  40650. this._collisionsCallbackArray = [];
  40651. this._init = false;
  40652. this._runningUpdated = 0;
  40653. this._runningCollisionTask = false;
  40654. this._addUpdateMeshesList = {};
  40655. this._addUpdateGeometriesList = {};
  40656. this._toRemoveGeometryArray = [];
  40657. this._toRemoveMeshesArray = [];
  40658. }
  40659. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40660. if (!this._init)
  40661. return;
  40662. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  40663. return;
  40664. position.divideToRef(collider.radius, this._scaledPosition);
  40665. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40666. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  40667. var payload = {
  40668. collider: {
  40669. position: this._scaledPosition.asArray(),
  40670. velocity: this._scaledVelocity.asArray(),
  40671. radius: collider.radius.asArray()
  40672. },
  40673. collisionId: collisionIndex,
  40674. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  40675. maximumRetry: maximumRetry
  40676. };
  40677. var message = {
  40678. payload: payload,
  40679. taskType: WorkerTaskType.COLLIDE
  40680. };
  40681. this._worker.postMessage(message);
  40682. };
  40683. CollisionCoordinatorWorker.prototype.init = function (scene) {
  40684. this._scene = scene;
  40685. this._scene.registerAfterRender(this._afterRender);
  40686. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  40687. this._worker = new Worker(workerUrl);
  40688. this._worker.onmessage = this._onMessageFromWorker;
  40689. var message = {
  40690. payload: {},
  40691. taskType: WorkerTaskType.INIT
  40692. };
  40693. this._worker.postMessage(message);
  40694. };
  40695. CollisionCoordinatorWorker.prototype.destroy = function () {
  40696. this._scene.unregisterAfterRender(this._afterRender);
  40697. this._worker.terminate();
  40698. };
  40699. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  40700. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  40701. this.onMeshUpdated(mesh);
  40702. };
  40703. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  40704. this._toRemoveMeshesArray.push(mesh.uniqueId);
  40705. };
  40706. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  40707. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  40708. geometry.onGeometryUpdated = this.onGeometryUpdated;
  40709. this.onGeometryUpdated(geometry);
  40710. };
  40711. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  40712. this._toRemoveGeometryArray.push(geometry.id);
  40713. };
  40714. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  40715. var submeshes = [];
  40716. if (mesh.subMeshes) {
  40717. submeshes = mesh.subMeshes.map(function (sm, idx) {
  40718. return {
  40719. position: idx,
  40720. verticesStart: sm.verticesStart,
  40721. verticesCount: sm.verticesCount,
  40722. indexStart: sm.indexStart,
  40723. indexCount: sm.indexCount,
  40724. hasMaterial: !!sm.getMaterial(),
  40725. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40726. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  40727. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40728. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  40729. };
  40730. });
  40731. }
  40732. var geometryId = null;
  40733. if (mesh instanceof BABYLON.Mesh) {
  40734. geometryId = mesh.geometry ? mesh.geometry.id : null;
  40735. }
  40736. else if (mesh instanceof BABYLON.InstancedMesh) {
  40737. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  40738. }
  40739. return {
  40740. uniqueId: mesh.uniqueId,
  40741. id: mesh.id,
  40742. name: mesh.name,
  40743. geometryId: geometryId,
  40744. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40745. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  40746. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40747. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  40748. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  40749. subMeshes: submeshes,
  40750. checkCollisions: mesh.checkCollisions
  40751. };
  40752. };
  40753. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  40754. return {
  40755. id: geometry.id,
  40756. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  40757. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  40758. indices: new Uint32Array(geometry.getIndices() || []),
  40759. };
  40760. };
  40761. return CollisionCoordinatorWorker;
  40762. }());
  40763. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  40764. var CollisionCoordinatorLegacy = (function () {
  40765. function CollisionCoordinatorLegacy() {
  40766. this._scaledPosition = BABYLON.Vector3.Zero();
  40767. this._scaledVelocity = BABYLON.Vector3.Zero();
  40768. this._finalPosition = BABYLON.Vector3.Zero();
  40769. }
  40770. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40771. position.divideToRef(collider.radius, this._scaledPosition);
  40772. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40773. collider.collidedMesh = null;
  40774. collider.retry = 0;
  40775. collider.initialVelocity = this._scaledVelocity;
  40776. collider.initialPosition = this._scaledPosition;
  40777. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  40778. this._finalPosition.multiplyInPlace(collider.radius);
  40779. //run the callback
  40780. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  40781. };
  40782. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  40783. this._scene = scene;
  40784. };
  40785. CollisionCoordinatorLegacy.prototype.destroy = function () {
  40786. //Legacy need no destruction method.
  40787. };
  40788. //No update in legacy mode
  40789. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  40790. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  40791. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  40792. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  40793. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  40794. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  40795. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  40796. if (excludedMesh === void 0) { excludedMesh = null; }
  40797. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  40798. if (collider.retry >= maximumRetry) {
  40799. finalPosition.copyFrom(position);
  40800. return;
  40801. }
  40802. // Check if this is a mesh else camera or -1
  40803. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  40804. collider._initialize(position, velocity, closeDistance);
  40805. // Check all meshes
  40806. for (var index = 0; index < this._scene.meshes.length; index++) {
  40807. var mesh = this._scene.meshes[index];
  40808. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  40809. mesh._checkCollision(collider);
  40810. }
  40811. }
  40812. if (!collider.collisionFound) {
  40813. position.addToRef(velocity, finalPosition);
  40814. return;
  40815. }
  40816. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  40817. collider._getResponse(position, velocity);
  40818. }
  40819. if (velocity.length() <= closeDistance) {
  40820. finalPosition.copyFrom(position);
  40821. return;
  40822. }
  40823. collider.retry++;
  40824. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  40825. };
  40826. return CollisionCoordinatorLegacy;
  40827. }());
  40828. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  40829. })(BABYLON || (BABYLON = {}));
  40830. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  40831. var BABYLON;
  40832. (function (BABYLON) {
  40833. var Particle = (function () {
  40834. function Particle(particleSystem) {
  40835. this.particleSystem = particleSystem;
  40836. this.position = BABYLON.Vector3.Zero();
  40837. this.direction = BABYLON.Vector3.Zero();
  40838. this.color = new BABYLON.Color4(0, 0, 0, 0);
  40839. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  40840. this.lifeTime = 1.0;
  40841. this.age = 0;
  40842. this.size = 0;
  40843. this.angle = 0;
  40844. this.angularSpeed = 0;
  40845. this._currentFrameCounter = 0;
  40846. this.cellIndex = 0;
  40847. if (!this.particleSystem.isAnimationSheetEnabled) {
  40848. return;
  40849. }
  40850. this.cellIndex = this.particleSystem.startSpriteCellID;
  40851. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  40852. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  40853. }
  40854. else {
  40855. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  40856. }
  40857. }
  40858. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  40859. // (ageOffset / scaledUpdateSpeed) / available cells
  40860. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  40861. this._currentFrameCounter += scaledUpdateSpeed;
  40862. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  40863. this._currentFrameCounter = 0;
  40864. this.cellIndex++;
  40865. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  40866. this.cellIndex = this.particleSystem.endSpriteCellID;
  40867. }
  40868. }
  40869. };
  40870. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  40871. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  40872. this.cellIndex++;
  40873. this._currentFrameCounter = 0;
  40874. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  40875. if (this.particleSystem.spriteCellLoop) {
  40876. this.cellIndex = this.particleSystem.startSpriteCellID;
  40877. }
  40878. else {
  40879. this.cellIndex = this.particleSystem.endSpriteCellID;
  40880. }
  40881. }
  40882. }
  40883. else {
  40884. this._currentFrameCounter++;
  40885. }
  40886. };
  40887. Particle.prototype.copyTo = function (other) {
  40888. other.position.copyFrom(this.position);
  40889. other.direction.copyFrom(this.direction);
  40890. other.color.copyFrom(this.color);
  40891. other.colorStep.copyFrom(this.colorStep);
  40892. other.lifeTime = this.lifeTime;
  40893. other.age = this.age;
  40894. other.size = this.size;
  40895. other.angle = this.angle;
  40896. other.angularSpeed = this.angularSpeed;
  40897. other.particleSystem = this.particleSystem;
  40898. other.cellIndex = this.cellIndex;
  40899. };
  40900. return Particle;
  40901. }());
  40902. BABYLON.Particle = Particle;
  40903. })(BABYLON || (BABYLON = {}));
  40904. //# sourceMappingURL=babylon.particle.js.map
  40905. var BABYLON;
  40906. (function (BABYLON) {
  40907. var randomNumber = function (min, max) {
  40908. if (min === max) {
  40909. return (min);
  40910. }
  40911. var random = Math.random();
  40912. return ((random * (max - min)) + min);
  40913. };
  40914. var ParticleSystem = (function () {
  40915. // end of sheet animation
  40916. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  40917. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  40918. if (epsilon === void 0) { epsilon = 0.01; }
  40919. var _this = this;
  40920. this.name = name;
  40921. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  40922. // Members
  40923. this.animations = [];
  40924. this.renderingGroupId = 0;
  40925. this.emitter = null;
  40926. this.emitRate = 10;
  40927. this.manualEmitCount = -1;
  40928. this.updateSpeed = 0.01;
  40929. this.targetStopDuration = 0;
  40930. this.disposeOnStop = false;
  40931. this.minEmitPower = 1;
  40932. this.maxEmitPower = 1;
  40933. this.minLifeTime = 1;
  40934. this.maxLifeTime = 1;
  40935. this.minSize = 1;
  40936. this.maxSize = 1;
  40937. this.minAngularSpeed = 0;
  40938. this.maxAngularSpeed = 0;
  40939. this.layerMask = 0x0FFFFFFF;
  40940. this.customShader = null;
  40941. this.preventAutoStart = false;
  40942. /**
  40943. * An event triggered when the system is disposed.
  40944. * @type {BABYLON.Observable}
  40945. */
  40946. this.onDisposeObservable = new BABYLON.Observable();
  40947. this.onAnimationEnd = null;
  40948. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  40949. this.forceDepthWrite = false;
  40950. this.gravity = BABYLON.Vector3.Zero();
  40951. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  40952. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  40953. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  40954. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40955. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40956. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40957. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  40958. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40959. this.particles = new Array();
  40960. this._stockParticles = new Array();
  40961. this._newPartsExcess = 0;
  40962. this._vertexBuffers = {};
  40963. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  40964. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  40965. this._scaledDirection = BABYLON.Vector3.Zero();
  40966. this._scaledGravity = BABYLON.Vector3.Zero();
  40967. this._currentRenderId = -1;
  40968. this._started = false;
  40969. this._stopped = false;
  40970. this._actualFrame = 0;
  40971. // sheet animation
  40972. this.startSpriteCellID = 0;
  40973. this.endSpriteCellID = 0;
  40974. this.spriteCellLoop = true;
  40975. this.spriteCellChangeSpeed = 0;
  40976. this.spriteCellWidth = 0;
  40977. this.spriteCellHeight = 0;
  40978. this._vertexBufferSize = 11;
  40979. this.appendParticleVertexes = null;
  40980. this.id = name;
  40981. this._capacity = capacity;
  40982. this._epsilon = epsilon;
  40983. if (_isAnimationSheetEnabled) {
  40984. this._vertexBufferSize = 12;
  40985. }
  40986. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40987. this._customEffect = customEffect;
  40988. scene.particleSystems.push(this);
  40989. this._createIndexBuffer();
  40990. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  40991. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  40992. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  40993. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  40994. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  40995. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  40996. if (this._isAnimationSheetEnabled) {
  40997. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  40998. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  40999. }
  41000. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  41001. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  41002. this._vertexBuffers["options"] = options;
  41003. // Default behaviors
  41004. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  41005. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  41006. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  41007. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  41008. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  41009. };
  41010. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  41011. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  41012. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  41013. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  41014. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  41015. };
  41016. this.updateFunction = function (particles) {
  41017. for (var index = 0; index < particles.length; index++) {
  41018. var particle = particles[index];
  41019. particle.age += _this._scaledUpdateSpeed;
  41020. if (particle.age >= particle.lifeTime) {
  41021. _this.recycleParticle(particle);
  41022. index--;
  41023. continue;
  41024. }
  41025. else {
  41026. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  41027. particle.color.addInPlace(_this._scaledColorStep);
  41028. if (particle.color.a < 0)
  41029. particle.color.a = 0;
  41030. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  41031. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  41032. particle.position.addInPlace(_this._scaledDirection);
  41033. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  41034. particle.direction.addInPlace(_this._scaledGravity);
  41035. if (_this._isAnimationSheetEnabled) {
  41036. particle.updateCellIndex(_this._scaledUpdateSpeed);
  41037. }
  41038. }
  41039. }
  41040. };
  41041. }
  41042. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  41043. set: function (callback) {
  41044. if (this._onDisposeObserver) {
  41045. this.onDisposeObservable.remove(this._onDisposeObserver);
  41046. }
  41047. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  41048. },
  41049. enumerable: true,
  41050. configurable: true
  41051. });
  41052. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  41053. get: function () {
  41054. return this._isAnimationSheetEnabled;
  41055. },
  41056. enumerable: true,
  41057. configurable: true
  41058. });
  41059. ParticleSystem.prototype._createIndexBuffer = function () {
  41060. var indices = [];
  41061. var index = 0;
  41062. for (var count = 0; count < this._capacity; count++) {
  41063. indices.push(index);
  41064. indices.push(index + 1);
  41065. indices.push(index + 2);
  41066. indices.push(index);
  41067. indices.push(index + 2);
  41068. indices.push(index + 3);
  41069. index += 4;
  41070. }
  41071. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  41072. };
  41073. ParticleSystem.prototype.recycleParticle = function (particle) {
  41074. var lastParticle = this.particles.pop();
  41075. if (lastParticle !== particle) {
  41076. lastParticle.copyTo(particle);
  41077. this._stockParticles.push(lastParticle);
  41078. }
  41079. };
  41080. ParticleSystem.prototype.getCapacity = function () {
  41081. return this._capacity;
  41082. };
  41083. ParticleSystem.prototype.isAlive = function () {
  41084. return this._alive;
  41085. };
  41086. ParticleSystem.prototype.isStarted = function () {
  41087. return this._started;
  41088. };
  41089. ParticleSystem.prototype.start = function () {
  41090. this._started = true;
  41091. this._stopped = false;
  41092. this._actualFrame = 0;
  41093. };
  41094. ParticleSystem.prototype.stop = function () {
  41095. this._stopped = true;
  41096. };
  41097. // animation sheet
  41098. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  41099. var offset = index * this._vertexBufferSize;
  41100. this._vertexData[offset] = particle.position.x;
  41101. this._vertexData[offset + 1] = particle.position.y;
  41102. this._vertexData[offset + 2] = particle.position.z;
  41103. this._vertexData[offset + 3] = particle.color.r;
  41104. this._vertexData[offset + 4] = particle.color.g;
  41105. this._vertexData[offset + 5] = particle.color.b;
  41106. this._vertexData[offset + 6] = particle.color.a;
  41107. this._vertexData[offset + 7] = particle.angle;
  41108. this._vertexData[offset + 8] = particle.size;
  41109. this._vertexData[offset + 9] = offsetX;
  41110. this._vertexData[offset + 10] = offsetY;
  41111. };
  41112. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  41113. if (offsetX === 0)
  41114. offsetX = this._epsilon;
  41115. else if (offsetX === 1)
  41116. offsetX = 1 - this._epsilon;
  41117. if (offsetY === 0)
  41118. offsetY = this._epsilon;
  41119. else if (offsetY === 1)
  41120. offsetY = 1 - this._epsilon;
  41121. var offset = index * this._vertexBufferSize;
  41122. this._vertexData[offset] = particle.position.x;
  41123. this._vertexData[offset + 1] = particle.position.y;
  41124. this._vertexData[offset + 2] = particle.position.z;
  41125. this._vertexData[offset + 3] = particle.color.r;
  41126. this._vertexData[offset + 4] = particle.color.g;
  41127. this._vertexData[offset + 5] = particle.color.b;
  41128. this._vertexData[offset + 6] = particle.color.a;
  41129. this._vertexData[offset + 7] = particle.angle;
  41130. this._vertexData[offset + 8] = particle.size;
  41131. this._vertexData[offset + 9] = offsetX;
  41132. this._vertexData[offset + 10] = offsetY;
  41133. this._vertexData[offset + 11] = particle.cellIndex;
  41134. };
  41135. ParticleSystem.prototype._update = function (newParticles) {
  41136. // Update current
  41137. this._alive = this.particles.length > 0;
  41138. this.updateFunction(this.particles);
  41139. // Add new ones
  41140. var worldMatrix;
  41141. if (this.emitter.position) {
  41142. var emitterMesh = this.emitter;
  41143. worldMatrix = emitterMesh.getWorldMatrix();
  41144. }
  41145. else {
  41146. var emitterPosition = this.emitter;
  41147. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  41148. }
  41149. var particle;
  41150. for (var index = 0; index < newParticles; index++) {
  41151. if (this.particles.length === this._capacity) {
  41152. break;
  41153. }
  41154. if (this._stockParticles.length !== 0) {
  41155. particle = this._stockParticles.pop();
  41156. particle.age = 0;
  41157. particle.cellIndex = this.startSpriteCellID;
  41158. }
  41159. else {
  41160. particle = new BABYLON.Particle(this);
  41161. }
  41162. this.particles.push(particle);
  41163. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  41164. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  41165. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  41166. particle.size = randomNumber(this.minSize, this.maxSize);
  41167. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  41168. this.startPositionFunction(worldMatrix, particle.position, particle);
  41169. var step = randomNumber(0, 1.0);
  41170. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  41171. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  41172. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  41173. }
  41174. };
  41175. ParticleSystem.prototype._getEffect = function () {
  41176. if (this._customEffect) {
  41177. return this._customEffect;
  41178. }
  41179. ;
  41180. var defines = [];
  41181. if (this._scene.clipPlane) {
  41182. defines.push("#define CLIPPLANE");
  41183. }
  41184. if (this._isAnimationSheetEnabled) {
  41185. defines.push("#define ANIMATESHEET");
  41186. }
  41187. // Effect
  41188. var join = defines.join("\n");
  41189. if (this._cachedDefines !== join) {
  41190. this._cachedDefines = join;
  41191. var attributesNamesOrOptions;
  41192. var effectCreationOption;
  41193. if (this._isAnimationSheetEnabled) {
  41194. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  41195. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  41196. }
  41197. else {
  41198. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  41199. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  41200. }
  41201. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  41202. }
  41203. return this._effect;
  41204. };
  41205. ParticleSystem.prototype.animate = function () {
  41206. if (!this._started)
  41207. return;
  41208. var effect = this._getEffect();
  41209. // Check
  41210. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  41211. return;
  41212. if (this._currentRenderId === this._scene.getRenderId()) {
  41213. return;
  41214. }
  41215. this._currentRenderId = this._scene.getRenderId();
  41216. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  41217. // determine the number of particles we need to create
  41218. var newParticles;
  41219. if (this.manualEmitCount > -1) {
  41220. newParticles = this.manualEmitCount;
  41221. this._newPartsExcess = 0;
  41222. this.manualEmitCount = 0;
  41223. }
  41224. else {
  41225. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  41226. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  41227. }
  41228. if (this._newPartsExcess > 1.0) {
  41229. newParticles += this._newPartsExcess >> 0;
  41230. this._newPartsExcess -= this._newPartsExcess >> 0;
  41231. }
  41232. this._alive = false;
  41233. if (!this._stopped) {
  41234. this._actualFrame += this._scaledUpdateSpeed;
  41235. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  41236. this.stop();
  41237. }
  41238. else {
  41239. newParticles = 0;
  41240. }
  41241. this._update(newParticles);
  41242. // Stopped?
  41243. if (this._stopped) {
  41244. if (!this._alive) {
  41245. this._started = false;
  41246. if (this.onAnimationEnd) {
  41247. this.onAnimationEnd();
  41248. }
  41249. if (this.disposeOnStop) {
  41250. this._scene._toBeDisposed.push(this);
  41251. }
  41252. }
  41253. }
  41254. // Animation sheet
  41255. if (this._isAnimationSheetEnabled) {
  41256. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  41257. }
  41258. else {
  41259. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  41260. }
  41261. // Update VBO
  41262. var offset = 0;
  41263. for (var index = 0; index < this.particles.length; index++) {
  41264. var particle = this.particles[index];
  41265. this.appendParticleVertexes(offset, particle);
  41266. offset += 4;
  41267. }
  41268. this._vertexBuffer.update(this._vertexData);
  41269. };
  41270. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  41271. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  41272. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  41273. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  41274. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  41275. };
  41276. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  41277. this._appendParticleVertex(offset++, particle, 0, 0);
  41278. this._appendParticleVertex(offset++, particle, 1, 0);
  41279. this._appendParticleVertex(offset++, particle, 1, 1);
  41280. this._appendParticleVertex(offset++, particle, 0, 1);
  41281. };
  41282. ParticleSystem.prototype.rebuild = function () {
  41283. this._createIndexBuffer();
  41284. this._vertexBuffer._rebuild();
  41285. };
  41286. ParticleSystem.prototype.render = function () {
  41287. var effect = this._getEffect();
  41288. // Check
  41289. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  41290. return 0;
  41291. var engine = this._scene.getEngine();
  41292. // Render
  41293. engine.enableEffect(effect);
  41294. engine.setState(false);
  41295. var viewMatrix = this._scene.getViewMatrix();
  41296. effect.setTexture("diffuseSampler", this.particleTexture);
  41297. effect.setMatrix("view", viewMatrix);
  41298. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  41299. if (this._isAnimationSheetEnabled) {
  41300. var baseSize = this.particleTexture.getBaseSize();
  41301. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  41302. }
  41303. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  41304. if (this._scene.clipPlane) {
  41305. var clipPlane = this._scene.clipPlane;
  41306. var invView = viewMatrix.clone();
  41307. invView.invert();
  41308. effect.setMatrix("invView", invView);
  41309. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41310. }
  41311. // VBOs
  41312. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41313. // Draw order
  41314. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  41315. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  41316. }
  41317. else {
  41318. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41319. }
  41320. if (this.forceDepthWrite) {
  41321. engine.setDepthWrite(true);
  41322. }
  41323. engine.draw(true, 0, this.particles.length * 6);
  41324. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41325. return this.particles.length;
  41326. };
  41327. ParticleSystem.prototype.dispose = function () {
  41328. if (this._vertexBuffer) {
  41329. this._vertexBuffer.dispose();
  41330. this._vertexBuffer = null;
  41331. }
  41332. if (this._indexBuffer) {
  41333. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41334. this._indexBuffer = null;
  41335. }
  41336. if (this.particleTexture) {
  41337. this.particleTexture.dispose();
  41338. this.particleTexture = null;
  41339. }
  41340. // Remove from scene
  41341. var index = this._scene.particleSystems.indexOf(this);
  41342. if (index > -1) {
  41343. this._scene.particleSystems.splice(index, 1);
  41344. }
  41345. // Callback
  41346. this.onDisposeObservable.notifyObservers(this);
  41347. this.onDisposeObservable.clear();
  41348. };
  41349. // Clone
  41350. ParticleSystem.prototype.clone = function (name, newEmitter) {
  41351. var custom = null;
  41352. var program = null;
  41353. if (this.customShader != null) {
  41354. program = this.customShader;
  41355. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41356. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41357. }
  41358. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  41359. result.customShader = program;
  41360. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  41361. if (newEmitter === undefined) {
  41362. newEmitter = this.emitter;
  41363. }
  41364. result.emitter = newEmitter;
  41365. if (this.particleTexture) {
  41366. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  41367. }
  41368. if (!this.preventAutoStart) {
  41369. result.start();
  41370. }
  41371. return result;
  41372. };
  41373. ParticleSystem.prototype.serialize = function () {
  41374. var serializationObject = {};
  41375. serializationObject.name = this.name;
  41376. serializationObject.id = this.id;
  41377. // Emitter
  41378. if (this.emitter.position) {
  41379. var emitterMesh = this.emitter;
  41380. serializationObject.emitterId = emitterMesh.id;
  41381. }
  41382. else {
  41383. var emitterPosition = this.emitter;
  41384. serializationObject.emitter = emitterPosition.asArray();
  41385. }
  41386. serializationObject.capacity = this.getCapacity();
  41387. if (this.particleTexture) {
  41388. serializationObject.textureName = this.particleTexture.name;
  41389. }
  41390. // Animations
  41391. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  41392. // Particle system
  41393. serializationObject.minAngularSpeed = this.minAngularSpeed;
  41394. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  41395. serializationObject.minSize = this.minSize;
  41396. serializationObject.maxSize = this.maxSize;
  41397. serializationObject.minEmitPower = this.minEmitPower;
  41398. serializationObject.maxEmitPower = this.maxEmitPower;
  41399. serializationObject.minLifeTime = this.minLifeTime;
  41400. serializationObject.maxLifeTime = this.maxLifeTime;
  41401. serializationObject.emitRate = this.emitRate;
  41402. serializationObject.minEmitBox = this.minEmitBox.asArray();
  41403. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  41404. serializationObject.gravity = this.gravity.asArray();
  41405. serializationObject.direction1 = this.direction1.asArray();
  41406. serializationObject.direction2 = this.direction2.asArray();
  41407. serializationObject.color1 = this.color1.asArray();
  41408. serializationObject.color2 = this.color2.asArray();
  41409. serializationObject.colorDead = this.colorDead.asArray();
  41410. serializationObject.updateSpeed = this.updateSpeed;
  41411. serializationObject.targetStopDuration = this.targetStopDuration;
  41412. serializationObject.textureMask = this.textureMask.asArray();
  41413. serializationObject.blendMode = this.blendMode;
  41414. serializationObject.customShader = this.customShader;
  41415. serializationObject.preventAutoStart = this.preventAutoStart;
  41416. return serializationObject;
  41417. };
  41418. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  41419. var name = parsedParticleSystem.name;
  41420. var custom = null;
  41421. var program = null;
  41422. if (parsedParticleSystem.customShader) {
  41423. program = parsedParticleSystem.customShader;
  41424. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41425. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41426. }
  41427. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  41428. particleSystem.customShader = program;
  41429. if (parsedParticleSystem.id) {
  41430. particleSystem.id = parsedParticleSystem.id;
  41431. }
  41432. // Auto start
  41433. if (parsedParticleSystem.preventAutoStart) {
  41434. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  41435. }
  41436. // Texture
  41437. if (parsedParticleSystem.textureName) {
  41438. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  41439. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  41440. }
  41441. // Emitter
  41442. if (parsedParticleSystem.emitterId) {
  41443. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  41444. }
  41445. else {
  41446. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  41447. }
  41448. // Animations
  41449. if (parsedParticleSystem.animations) {
  41450. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  41451. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  41452. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  41453. }
  41454. }
  41455. if (parsedParticleSystem.autoAnimate) {
  41456. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  41457. }
  41458. // Particle system
  41459. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  41460. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  41461. particleSystem.minSize = parsedParticleSystem.minSize;
  41462. particleSystem.maxSize = parsedParticleSystem.maxSize;
  41463. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  41464. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  41465. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  41466. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  41467. particleSystem.emitRate = parsedParticleSystem.emitRate;
  41468. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  41469. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  41470. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  41471. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  41472. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  41473. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  41474. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  41475. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  41476. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  41477. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  41478. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  41479. particleSystem.blendMode = parsedParticleSystem.blendMode;
  41480. if (!particleSystem.preventAutoStart) {
  41481. particleSystem.start();
  41482. }
  41483. return particleSystem;
  41484. };
  41485. // Statics
  41486. ParticleSystem.BLENDMODE_ONEONE = 0;
  41487. ParticleSystem.BLENDMODE_STANDARD = 1;
  41488. return ParticleSystem;
  41489. }());
  41490. BABYLON.ParticleSystem = ParticleSystem;
  41491. })(BABYLON || (BABYLON = {}));
  41492. //# sourceMappingURL=babylon.particleSystem.js.map
  41493. var BABYLON;
  41494. (function (BABYLON) {
  41495. var SolidParticle = (function () {
  41496. /**
  41497. * Creates a Solid Particle object.
  41498. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  41499. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  41500. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  41501. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  41502. * `shapeId` (integer) is the model shape identifier in the SPS.
  41503. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  41504. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  41505. */
  41506. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  41507. this.idx = 0; // particle global index
  41508. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  41509. this.position = BABYLON.Vector3.Zero(); // position
  41510. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41511. this.scaling = BABYLON.Vector3.One(); // scaling
  41512. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  41513. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41514. this.alive = true; // alive
  41515. this.isVisible = true; // visibility
  41516. this._pos = 0; // index of this particle in the global "positions" array
  41517. this.shapeId = 0; // model shape id
  41518. this.idxInShape = 0; // index of the particle in its shape id
  41519. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  41520. this.idx = particleIndex;
  41521. this._pos = positionIndex;
  41522. this._model = model;
  41523. this.shapeId = shapeId;
  41524. this.idxInShape = idxInShape;
  41525. this._sps = sps;
  41526. if (modelBoundingInfo) {
  41527. this._modelBoundingInfo = modelBoundingInfo;
  41528. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  41529. }
  41530. }
  41531. Object.defineProperty(SolidParticle.prototype, "scale", {
  41532. /**
  41533. * legacy support, changed scale to scaling
  41534. */
  41535. get: function () {
  41536. return this.scaling;
  41537. },
  41538. set: function (scale) {
  41539. this.scaling = scale;
  41540. },
  41541. enumerable: true,
  41542. configurable: true
  41543. });
  41544. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41545. /**
  41546. * legacy support, changed quaternion to rotationQuaternion
  41547. */
  41548. get: function () {
  41549. return this.rotationQuaternion;
  41550. },
  41551. set: function (q) {
  41552. this.rotationQuaternion = q;
  41553. },
  41554. enumerable: true,
  41555. configurable: true
  41556. });
  41557. /**
  41558. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  41559. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  41560. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  41561. */
  41562. SolidParticle.prototype.intersectsMesh = function (target) {
  41563. if (!this._boundingInfo || !target._boundingInfo) {
  41564. return false;
  41565. }
  41566. if (this._sps._bSphereOnly) {
  41567. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  41568. }
  41569. return this._boundingInfo.intersects(target._boundingInfo, false);
  41570. };
  41571. return SolidParticle;
  41572. }());
  41573. BABYLON.SolidParticle = SolidParticle;
  41574. var ModelShape = (function () {
  41575. /**
  41576. * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
  41577. * SPS internal tool, don't use it manually.
  41578. */
  41579. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41580. this.shapeID = id;
  41581. this._shape = shape;
  41582. this._shapeUV = shapeUV;
  41583. this._positionFunction = posFunction;
  41584. this._vertexFunction = vtxFunction;
  41585. }
  41586. return ModelShape;
  41587. }());
  41588. BABYLON.ModelShape = ModelShape;
  41589. })(BABYLON || (BABYLON = {}));
  41590. //# sourceMappingURL=babylon.solidParticle.js.map
  41591. var BABYLON;
  41592. (function (BABYLON) {
  41593. /**
  41594. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  41595. */
  41596. var SolidParticleSystem = (function () {
  41597. /**
  41598. * Creates a SPS (Solid Particle System) object.
  41599. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41600. * `scene` (Scene) is the scene in which the SPS is added.
  41601. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  41602. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  41603. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  41604. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  41605. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  41606. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  41607. */
  41608. function SolidParticleSystem(name, scene, options) {
  41609. // public members
  41610. /**
  41611. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41612. * Example : var p = SPS.particles[i];
  41613. */
  41614. this.particles = new Array();
  41615. /**
  41616. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41617. */
  41618. this.nbParticles = 0;
  41619. /**
  41620. * If the particles must ever face the camera (default false). Useful for planar particles.
  41621. */
  41622. this.billboard = false;
  41623. /**
  41624. * Recompute normals when adding a shape
  41625. */
  41626. this.recomputeNormals = true;
  41627. /**
  41628. * This a counter ofr your own usage. It's not set by any SPS functions.
  41629. */
  41630. this.counter = 0;
  41631. /**
  41632. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41633. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  41634. */
  41635. this.vars = {};
  41636. this._positions = new Array();
  41637. this._indices = new Array();
  41638. this._normals = new Array();
  41639. this._colors = new Array();
  41640. this._uvs = new Array();
  41641. this._index = 0; // indices index
  41642. this._updatable = true;
  41643. this._pickable = false;
  41644. this._isVisibilityBoxLocked = false;
  41645. this._alwaysVisible = false;
  41646. this._shapeCounter = 0;
  41647. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  41648. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41649. this._computeParticleColor = true;
  41650. this._computeParticleTexture = true;
  41651. this._computeParticleRotation = true;
  41652. this._computeParticleVertex = false;
  41653. this._computeBoundingBox = false;
  41654. this._cam_axisZ = BABYLON.Vector3.Zero();
  41655. this._cam_axisY = BABYLON.Vector3.Zero();
  41656. this._cam_axisX = BABYLON.Vector3.Zero();
  41657. this._axisX = BABYLON.Axis.X;
  41658. this._axisY = BABYLON.Axis.Y;
  41659. this._axisZ = BABYLON.Axis.Z;
  41660. this._camDir = BABYLON.Vector3.Zero();
  41661. this._rotMatrix = new BABYLON.Matrix();
  41662. this._invertMatrix = new BABYLON.Matrix();
  41663. this._rotated = BABYLON.Vector3.Zero();
  41664. this._quaternion = new BABYLON.Quaternion();
  41665. this._vertex = BABYLON.Vector3.Zero();
  41666. this._normal = BABYLON.Vector3.Zero();
  41667. this._yaw = 0.0;
  41668. this._pitch = 0.0;
  41669. this._roll = 0.0;
  41670. this._halfroll = 0.0;
  41671. this._halfpitch = 0.0;
  41672. this._halfyaw = 0.0;
  41673. this._sinRoll = 0.0;
  41674. this._cosRoll = 0.0;
  41675. this._sinPitch = 0.0;
  41676. this._cosPitch = 0.0;
  41677. this._sinYaw = 0.0;
  41678. this._cosYaw = 0.0;
  41679. this._mustUnrotateFixedNormals = false;
  41680. this._minimum = BABYLON.Tmp.Vector3[0];
  41681. this._maximum = BABYLON.Tmp.Vector3[1];
  41682. this._scale = BABYLON.Tmp.Vector3[2];
  41683. this._translation = BABYLON.Tmp.Vector3[3];
  41684. this._minBbox = BABYLON.Tmp.Vector3[4];
  41685. this._maxBbox = BABYLON.Tmp.Vector3[5];
  41686. this._particlesIntersect = false;
  41687. this._bSphereOnly = false;
  41688. this._bSphereRadiusFactor = 1.0;
  41689. this.name = name;
  41690. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  41691. this._camera = scene.activeCamera;
  41692. this._pickable = options ? options.isPickable : false;
  41693. this._particlesIntersect = options ? options.particleIntersection : false;
  41694. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  41695. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  41696. if (options && options.updatable) {
  41697. this._updatable = options.updatable;
  41698. }
  41699. else {
  41700. this._updatable = true;
  41701. }
  41702. if (this._pickable) {
  41703. this.pickedParticles = [];
  41704. }
  41705. }
  41706. /**
  41707. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41708. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41709. */
  41710. SolidParticleSystem.prototype.buildMesh = function () {
  41711. if (this.nbParticles === 0) {
  41712. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41713. this.addShape(triangle, 1);
  41714. triangle.dispose();
  41715. }
  41716. this._positions32 = new Float32Array(this._positions);
  41717. this._uvs32 = new Float32Array(this._uvs);
  41718. this._colors32 = new Float32Array(this._colors);
  41719. if (this.recomputeNormals) {
  41720. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41721. }
  41722. this._normals32 = new Float32Array(this._normals);
  41723. this._fixedNormal32 = new Float32Array(this._normals);
  41724. if (this._mustUnrotateFixedNormals) {
  41725. this._unrotateFixedNormals();
  41726. }
  41727. var vertexData = new BABYLON.VertexData();
  41728. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41729. vertexData.indices = this._indices;
  41730. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41731. if (this._uvs32) {
  41732. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41733. ;
  41734. }
  41735. if (this._colors32) {
  41736. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41737. }
  41738. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41739. vertexData.applyToMesh(mesh, this._updatable);
  41740. this.mesh = mesh;
  41741. this.mesh.isPickable = this._pickable;
  41742. // free memory
  41743. this._positions = null;
  41744. this._normals = null;
  41745. this._uvs = null;
  41746. this._colors = null;
  41747. if (!this._updatable) {
  41748. this.particles.length = 0;
  41749. }
  41750. return mesh;
  41751. };
  41752. /**
  41753. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41754. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41755. * Thus the particles generated from `digest()` have their property `position` set yet.
  41756. * `mesh` ( Mesh ) is the mesh to be digested
  41757. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41758. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41759. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41760. */
  41761. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41762. var size = (options && options.facetNb) || 1;
  41763. var number = (options && options.number);
  41764. var delta = (options && options.delta) || 0;
  41765. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41766. var meshInd = mesh.getIndices();
  41767. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41768. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41769. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41770. var f = 0; // facet counter
  41771. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41772. // compute size from number
  41773. if (number) {
  41774. number = (number > totalFacets) ? totalFacets : number;
  41775. size = Math.round(totalFacets / number);
  41776. delta = 0;
  41777. }
  41778. else {
  41779. size = (size > totalFacets) ? totalFacets : size;
  41780. }
  41781. var facetPos = []; // submesh positions
  41782. var facetInd = []; // submesh indices
  41783. var facetUV = []; // submesh UV
  41784. var facetCol = []; // submesh colors
  41785. var barycenter = BABYLON.Tmp.Vector3[0];
  41786. var rand;
  41787. var sizeO = size;
  41788. while (f < totalFacets) {
  41789. size = sizeO + Math.floor((1 + delta) * Math.random());
  41790. if (f > totalFacets - size) {
  41791. size = totalFacets - f;
  41792. }
  41793. // reset temp arrays
  41794. facetPos.length = 0;
  41795. facetInd.length = 0;
  41796. facetUV.length = 0;
  41797. facetCol.length = 0;
  41798. // iterate over "size" facets
  41799. var fi = 0;
  41800. for (var j = f * 3; j < (f + size) * 3; j++) {
  41801. facetInd.push(fi);
  41802. var i = meshInd[j];
  41803. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41804. if (meshUV) {
  41805. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41806. }
  41807. if (meshCol) {
  41808. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41809. }
  41810. fi++;
  41811. }
  41812. // create a model shape for each single particle
  41813. var idx = this.nbParticles;
  41814. var shape = this._posToShape(facetPos);
  41815. var shapeUV = this._uvsToShapeUV(facetUV);
  41816. // compute the barycenter of the shape
  41817. var v;
  41818. for (v = 0; v < shape.length; v++) {
  41819. barycenter.addInPlace(shape[v]);
  41820. }
  41821. barycenter.scaleInPlace(1 / shape.length);
  41822. // shift the shape from its barycenter to the origin
  41823. for (v = 0; v < shape.length; v++) {
  41824. shape[v].subtractInPlace(barycenter);
  41825. }
  41826. var bInfo;
  41827. if (this._particlesIntersect) {
  41828. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  41829. }
  41830. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41831. // add the particle in the SPS
  41832. var currentPos = this._positions.length;
  41833. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  41834. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  41835. // initialize the particle position
  41836. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41837. this._index += shape.length;
  41838. idx++;
  41839. this.nbParticles++;
  41840. this._shapeCounter++;
  41841. f += size;
  41842. }
  41843. return this;
  41844. };
  41845. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  41846. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  41847. var index = 0;
  41848. var idx = 0;
  41849. for (var p = 0; p < this.particles.length; p++) {
  41850. this._particle = this.particles[p];
  41851. this._shape = this._particle._model._shape;
  41852. if (this._particle.rotationQuaternion) {
  41853. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41854. }
  41855. else {
  41856. this._yaw = this._particle.rotation.y;
  41857. this._pitch = this._particle.rotation.x;
  41858. this._roll = this._particle.rotation.z;
  41859. this._quaternionRotationYPR();
  41860. }
  41861. this._quaternionToRotationMatrix();
  41862. this._rotMatrix.invertToRef(this._invertMatrix);
  41863. for (var pt = 0; pt < this._shape.length; pt++) {
  41864. idx = index + pt * 3;
  41865. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  41866. this._fixedNormal32[idx] = this._normal.x;
  41867. this._fixedNormal32[idx + 1] = this._normal.y;
  41868. this._fixedNormal32[idx + 2] = this._normal.z;
  41869. }
  41870. index = idx + 3;
  41871. }
  41872. };
  41873. //reset copy
  41874. SolidParticleSystem.prototype._resetCopy = function () {
  41875. this._copy.position.x = 0;
  41876. this._copy.position.y = 0;
  41877. this._copy.position.z = 0;
  41878. this._copy.rotation.x = 0;
  41879. this._copy.rotation.y = 0;
  41880. this._copy.rotation.z = 0;
  41881. this._copy.rotationQuaternion = null;
  41882. this._copy.scaling.x = 1;
  41883. this._copy.scaling.y = 1;
  41884. this._copy.scaling.z = 1;
  41885. this._copy.uvs.x = 0;
  41886. this._copy.uvs.y = 0;
  41887. this._copy.uvs.z = 1;
  41888. this._copy.uvs.w = 1;
  41889. this._copy.color = null;
  41890. };
  41891. // _meshBuilder : inserts the shape model in the global SPS mesh
  41892. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  41893. var i;
  41894. var u = 0;
  41895. var c = 0;
  41896. var n = 0;
  41897. this._resetCopy();
  41898. if (options && options.positionFunction) {
  41899. options.positionFunction(this._copy, idx, idxInShape);
  41900. this._mustUnrotateFixedNormals = true;
  41901. }
  41902. if (this._copy.rotationQuaternion) {
  41903. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41904. }
  41905. else {
  41906. this._yaw = this._copy.rotation.y;
  41907. this._pitch = this._copy.rotation.x;
  41908. this._roll = this._copy.rotation.z;
  41909. this._quaternionRotationYPR();
  41910. }
  41911. this._quaternionToRotationMatrix();
  41912. for (i = 0; i < shape.length; i++) {
  41913. this._vertex.x = shape[i].x;
  41914. this._vertex.y = shape[i].y;
  41915. this._vertex.z = shape[i].z;
  41916. if (options && options.vertexFunction) {
  41917. options.vertexFunction(this._copy, this._vertex, i);
  41918. }
  41919. this._vertex.x *= this._copy.scaling.x;
  41920. this._vertex.y *= this._copy.scaling.y;
  41921. this._vertex.z *= this._copy.scaling.z;
  41922. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41923. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41924. if (meshUV) {
  41925. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  41926. u += 2;
  41927. }
  41928. if (this._copy.color) {
  41929. this._color = this._copy.color;
  41930. }
  41931. else if (meshCol && meshCol[c] !== undefined) {
  41932. this._color.r = meshCol[c];
  41933. this._color.g = meshCol[c + 1];
  41934. this._color.b = meshCol[c + 2];
  41935. this._color.a = meshCol[c + 3];
  41936. }
  41937. else {
  41938. this._color.r = 1;
  41939. this._color.g = 1;
  41940. this._color.b = 1;
  41941. this._color.a = 1;
  41942. }
  41943. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41944. c += 4;
  41945. if (!this.recomputeNormals && meshNor) {
  41946. this._normal.x = meshNor[n];
  41947. this._normal.y = meshNor[n + 1];
  41948. this._normal.z = meshNor[n + 2];
  41949. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  41950. normals.push(this._normal.x, this._normal.y, this._normal.z);
  41951. n += 3;
  41952. }
  41953. }
  41954. for (i = 0; i < meshInd.length; i++) {
  41955. indices.push(p + meshInd[i]);
  41956. }
  41957. if (this._pickable) {
  41958. var nbfaces = meshInd.length / 3;
  41959. for (i = 0; i < nbfaces; i++) {
  41960. this.pickedParticles.push({ idx: idx, faceId: i });
  41961. }
  41962. }
  41963. return this._copy;
  41964. };
  41965. // returns a shape array from positions array
  41966. SolidParticleSystem.prototype._posToShape = function (positions) {
  41967. var shape = [];
  41968. for (var i = 0; i < positions.length; i += 3) {
  41969. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41970. }
  41971. return shape;
  41972. };
  41973. // returns a shapeUV array from a Vector4 uvs
  41974. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41975. var shapeUV = [];
  41976. if (uvs) {
  41977. for (var i = 0; i < uvs.length; i++)
  41978. shapeUV.push(uvs[i]);
  41979. }
  41980. return shapeUV;
  41981. };
  41982. // adds a new particle object in the particles array
  41983. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  41984. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  41985. this.particles.push(sp);
  41986. return sp;
  41987. };
  41988. /**
  41989. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41990. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  41991. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  41992. * `nb` (positive integer) the number of particles to be created from this model
  41993. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41994. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41995. */
  41996. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41997. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41998. var meshInd = mesh.getIndices();
  41999. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42000. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42001. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42002. var bbInfo;
  42003. if (this._particlesIntersect) {
  42004. bbInfo = mesh.getBoundingInfo();
  42005. }
  42006. var shape = this._posToShape(meshPos);
  42007. var shapeUV = this._uvsToShapeUV(meshUV);
  42008. var posfunc = options ? options.positionFunction : null;
  42009. var vtxfunc = options ? options.vertexFunction : null;
  42010. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  42011. // particles
  42012. var sp;
  42013. var currentCopy;
  42014. var idx = this.nbParticles;
  42015. for (var i = 0; i < nb; i++) {
  42016. var currentPos = this._positions.length;
  42017. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  42018. if (this._updatable) {
  42019. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  42020. sp.position.copyFrom(currentCopy.position);
  42021. sp.rotation.copyFrom(currentCopy.rotation);
  42022. if (currentCopy.rotationQuaternion) {
  42023. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  42024. }
  42025. if (currentCopy.color) {
  42026. sp.color.copyFrom(currentCopy.color);
  42027. }
  42028. sp.scaling.copyFrom(currentCopy.scaling);
  42029. sp.uvs.copyFrom(currentCopy.uvs);
  42030. }
  42031. this._index += shape.length;
  42032. idx++;
  42033. }
  42034. this.nbParticles += nb;
  42035. this._shapeCounter++;
  42036. return this._shapeCounter - 1;
  42037. };
  42038. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  42039. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  42040. this._resetCopy();
  42041. if (particle._model._positionFunction) {
  42042. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  42043. }
  42044. if (this._copy.rotationQuaternion) {
  42045. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  42046. }
  42047. else {
  42048. this._yaw = this._copy.rotation.y;
  42049. this._pitch = this._copy.rotation.x;
  42050. this._roll = this._copy.rotation.z;
  42051. this._quaternionRotationYPR();
  42052. }
  42053. this._quaternionToRotationMatrix();
  42054. this._shape = particle._model._shape;
  42055. for (var pt = 0; pt < this._shape.length; pt++) {
  42056. this._vertex.x = this._shape[pt].x;
  42057. this._vertex.y = this._shape[pt].y;
  42058. this._vertex.z = this._shape[pt].z;
  42059. if (particle._model._vertexFunction) {
  42060. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  42061. }
  42062. this._vertex.x *= this._copy.scaling.x;
  42063. this._vertex.y *= this._copy.scaling.y;
  42064. this._vertex.z *= this._copy.scaling.z;
  42065. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  42066. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  42067. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  42068. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  42069. }
  42070. particle.position.x = 0.0;
  42071. particle.position.y = 0.0;
  42072. particle.position.z = 0.0;
  42073. particle.rotation.x = 0.0;
  42074. particle.rotation.y = 0.0;
  42075. particle.rotation.z = 0.0;
  42076. particle.rotationQuaternion = null;
  42077. particle.scaling.x = 1.0;
  42078. particle.scaling.y = 1.0;
  42079. particle.scaling.z = 1.0;
  42080. };
  42081. /**
  42082. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  42083. * Returns the SPS.
  42084. */
  42085. SolidParticleSystem.prototype.rebuildMesh = function () {
  42086. for (var p = 0; p < this.particles.length; p++) {
  42087. this._rebuildParticle(this.particles[p]);
  42088. }
  42089. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42090. return this;
  42091. };
  42092. /**
  42093. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  42094. * This method calls `updateParticle()` for each particle of the SPS.
  42095. * For an animated SPS, it is usually called within the render loop.
  42096. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  42097. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  42098. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  42099. * Returns the SPS.
  42100. */
  42101. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  42102. if (start === void 0) { start = 0; }
  42103. if (end === void 0) { end = this.nbParticles - 1; }
  42104. if (update === void 0) { update = true; }
  42105. if (!this._updatable) {
  42106. return;
  42107. }
  42108. // custom beforeUpdate
  42109. this.beforeUpdateParticles(start, end, update);
  42110. this._cam_axisX.x = 1.0;
  42111. this._cam_axisX.y = 0.0;
  42112. this._cam_axisX.z = 0.0;
  42113. this._cam_axisY.x = 0.0;
  42114. this._cam_axisY.y = 1.0;
  42115. this._cam_axisY.z = 0.0;
  42116. this._cam_axisZ.x = 0.0;
  42117. this._cam_axisZ.y = 0.0;
  42118. this._cam_axisZ.z = 1.0;
  42119. // if the particles will always face the camera
  42120. if (this.billboard) {
  42121. this.mesh.computeWorldMatrix(true);
  42122. // compute the camera position and un-rotate it by the current mesh rotation
  42123. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  42124. this._quaternionToRotationMatrix();
  42125. this._rotMatrix.invertToRef(this._invertMatrix);
  42126. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  42127. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  42128. this._cam_axisZ.normalize();
  42129. // same for camera up vector extracted from the cam view matrix
  42130. var view = this._camera.getViewMatrix(true);
  42131. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  42132. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  42133. this._cam_axisY.normalize();
  42134. this._cam_axisX.normalize();
  42135. }
  42136. }
  42137. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  42138. var idx = 0; // current position index in the global array positions32
  42139. var index = 0; // position start index in the global array positions32 of the current particle
  42140. var colidx = 0; // current color index in the global array colors32
  42141. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  42142. var uvidx = 0; // current uv index in the global array uvs32
  42143. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  42144. var pt = 0; // current index in the particle model shape
  42145. if (this.mesh.isFacetDataEnabled) {
  42146. this._computeBoundingBox = true;
  42147. }
  42148. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  42149. if (this._computeBoundingBox) {
  42150. if (start == 0 && end == this.nbParticles - 1) {
  42151. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  42152. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  42153. }
  42154. else {
  42155. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  42156. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  42157. }
  42158. }
  42159. // particle loop
  42160. index = this.particles[start]._pos;
  42161. var vpos = (index / 3) | 0;
  42162. colorIndex = vpos * 4;
  42163. uvIndex = vpos * 2;
  42164. for (var p = start; p <= end; p++) {
  42165. this._particle = this.particles[p];
  42166. this._shape = this._particle._model._shape;
  42167. this._shapeUV = this._particle._model._shapeUV;
  42168. // call to custom user function to update the particle properties
  42169. this.updateParticle(this._particle);
  42170. // skip the computations for inactive or already invisible particles
  42171. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  42172. // increment indexes for the next particle
  42173. pt = this._shape.length;
  42174. index += pt * 3;
  42175. colorIndex += pt * 4;
  42176. uvIndex += pt * 2;
  42177. continue;
  42178. }
  42179. if (this._particle.isVisible) {
  42180. this._particle._stillInvisible = false; // un-mark permanent invisibility
  42181. // particle rotation matrix
  42182. if (this.billboard) {
  42183. this._particle.rotation.x = 0.0;
  42184. this._particle.rotation.y = 0.0;
  42185. }
  42186. if (this._computeParticleRotation || this.billboard) {
  42187. if (this._particle.rotationQuaternion) {
  42188. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  42189. }
  42190. else {
  42191. this._yaw = this._particle.rotation.y;
  42192. this._pitch = this._particle.rotation.x;
  42193. this._roll = this._particle.rotation.z;
  42194. this._quaternionRotationYPR();
  42195. }
  42196. this._quaternionToRotationMatrix();
  42197. }
  42198. // particle vertex loop
  42199. for (pt = 0; pt < this._shape.length; pt++) {
  42200. idx = index + pt * 3;
  42201. colidx = colorIndex + pt * 4;
  42202. uvidx = uvIndex + pt * 2;
  42203. this._vertex.x = this._shape[pt].x;
  42204. this._vertex.y = this._shape[pt].y;
  42205. this._vertex.z = this._shape[pt].z;
  42206. if (this._computeParticleVertex) {
  42207. this.updateParticleVertex(this._particle, this._vertex, pt);
  42208. }
  42209. // positions
  42210. this._vertex.x *= this._particle.scaling.x;
  42211. this._vertex.y *= this._particle.scaling.y;
  42212. this._vertex.z *= this._particle.scaling.z;
  42213. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  42214. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  42215. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  42216. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42217. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  42218. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  42219. if (this._computeBoundingBox) {
  42220. if (this._positions32[idx] < this._minimum.x) {
  42221. this._minimum.x = this._positions32[idx];
  42222. }
  42223. if (this._positions32[idx] > this._maximum.x) {
  42224. this._maximum.x = this._positions32[idx];
  42225. }
  42226. if (this._positions32[idx + 1] < this._minimum.y) {
  42227. this._minimum.y = this._positions32[idx + 1];
  42228. }
  42229. if (this._positions32[idx + 1] > this._maximum.y) {
  42230. this._maximum.y = this._positions32[idx + 1];
  42231. }
  42232. if (this._positions32[idx + 2] < this._minimum.z) {
  42233. this._minimum.z = this._positions32[idx + 2];
  42234. }
  42235. if (this._positions32[idx + 2] > this._maximum.z) {
  42236. this._maximum.z = this._positions32[idx + 2];
  42237. }
  42238. }
  42239. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  42240. if (!this._computeParticleVertex) {
  42241. this._normal.x = this._fixedNormal32[idx];
  42242. this._normal.y = this._fixedNormal32[idx + 1];
  42243. this._normal.z = this._fixedNormal32[idx + 2];
  42244. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  42245. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  42246. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  42247. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42248. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  42249. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  42250. }
  42251. if (this._computeParticleColor) {
  42252. this._colors32[colidx] = this._particle.color.r;
  42253. this._colors32[colidx + 1] = this._particle.color.g;
  42254. this._colors32[colidx + 2] = this._particle.color.b;
  42255. this._colors32[colidx + 3] = this._particle.color.a;
  42256. }
  42257. if (this._computeParticleTexture) {
  42258. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42259. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42260. }
  42261. }
  42262. }
  42263. else {
  42264. this._particle._stillInvisible = true; // mark the particle as invisible
  42265. for (pt = 0; pt < this._shape.length; pt++) {
  42266. idx = index + pt * 3;
  42267. colidx = colorIndex + pt * 4;
  42268. uvidx = uvIndex + pt * 2;
  42269. this._positions32[idx] = 0.0;
  42270. this._positions32[idx + 1] = 0.0;
  42271. this._positions32[idx + 2] = 0.0;
  42272. this._normals32[idx] = 0.0;
  42273. this._normals32[idx + 1] = 0.0;
  42274. this._normals32[idx + 2] = 0.0;
  42275. if (this._computeParticleColor) {
  42276. this._colors32[colidx] = this._particle.color.r;
  42277. this._colors32[colidx + 1] = this._particle.color.g;
  42278. this._colors32[colidx + 2] = this._particle.color.b;
  42279. this._colors32[colidx + 3] = this._particle.color.a;
  42280. }
  42281. if (this._computeParticleTexture) {
  42282. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42283. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42284. }
  42285. }
  42286. }
  42287. // if the particle intersections must be computed : update the bbInfo
  42288. if (this._particlesIntersect) {
  42289. var bInfo = this._particle._boundingInfo;
  42290. var bBox = bInfo.boundingBox;
  42291. var bSphere = bInfo.boundingSphere;
  42292. if (!this._bSphereOnly) {
  42293. // place, scale and rotate the particle bbox within the SPS local system, then update it
  42294. for (var b = 0; b < bBox.vectors.length; b++) {
  42295. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  42296. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  42297. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  42298. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  42299. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  42300. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  42301. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42302. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  42303. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  42304. }
  42305. bBox._update(this.mesh._worldMatrix);
  42306. }
  42307. // place and scale the particle bouding sphere in the SPS local system, then update it
  42308. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  42309. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  42310. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  42311. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  42312. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  42313. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  42314. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  42315. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  42316. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  42317. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  42318. bSphere._update(this.mesh._worldMatrix);
  42319. }
  42320. // increment indexes for the next particle
  42321. index = idx + 3;
  42322. colorIndex = colidx + 4;
  42323. uvIndex = uvidx + 2;
  42324. }
  42325. // if the VBO must be updated
  42326. if (update) {
  42327. if (this._computeParticleColor) {
  42328. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  42329. }
  42330. if (this._computeParticleTexture) {
  42331. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  42332. }
  42333. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42334. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  42335. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  42336. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  42337. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  42338. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  42339. for (var i = 0; i < this._normals32.length; i++) {
  42340. this._fixedNormal32[i] = this._normals32[i];
  42341. }
  42342. }
  42343. if (!this.mesh.areNormalsFrozen) {
  42344. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  42345. }
  42346. }
  42347. }
  42348. if (this._computeBoundingBox) {
  42349. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  42350. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  42351. }
  42352. this.afterUpdateParticles(start, end, update);
  42353. return this;
  42354. };
  42355. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  42356. this._halfroll = this._roll * 0.5;
  42357. this._halfpitch = this._pitch * 0.5;
  42358. this._halfyaw = this._yaw * 0.5;
  42359. this._sinRoll = Math.sin(this._halfroll);
  42360. this._cosRoll = Math.cos(this._halfroll);
  42361. this._sinPitch = Math.sin(this._halfpitch);
  42362. this._cosPitch = Math.cos(this._halfpitch);
  42363. this._sinYaw = Math.sin(this._halfyaw);
  42364. this._cosYaw = Math.cos(this._halfyaw);
  42365. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  42366. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  42367. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  42368. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  42369. };
  42370. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  42371. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  42372. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  42373. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  42374. this._rotMatrix.m[3] = 0;
  42375. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  42376. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  42377. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  42378. this._rotMatrix.m[7] = 0;
  42379. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  42380. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  42381. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  42382. this._rotMatrix.m[11] = 0;
  42383. this._rotMatrix.m[12] = 0;
  42384. this._rotMatrix.m[13] = 0;
  42385. this._rotMatrix.m[14] = 0;
  42386. this._rotMatrix.m[15] = 1.0;
  42387. };
  42388. /**
  42389. * Disposes the SPS.
  42390. * Returns nothing.
  42391. */
  42392. SolidParticleSystem.prototype.dispose = function () {
  42393. this.mesh.dispose();
  42394. this.vars = null;
  42395. // drop references to internal big arrays for the GC
  42396. this._positions = null;
  42397. this._indices = null;
  42398. this._normals = null;
  42399. this._uvs = null;
  42400. this._colors = null;
  42401. this._positions32 = null;
  42402. this._normals32 = null;
  42403. this._fixedNormal32 = null;
  42404. this._uvs32 = null;
  42405. this._colors32 = null;
  42406. this.pickedParticles = null;
  42407. };
  42408. /**
  42409. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  42410. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42411. * Returns the SPS.
  42412. */
  42413. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  42414. if (!this._isVisibilityBoxLocked) {
  42415. this.mesh.refreshBoundingInfo();
  42416. }
  42417. return this;
  42418. };
  42419. /**
  42420. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  42421. * @param size the size (float) of the visibility box
  42422. * note : this doesn't lock the SPS mesh bounding box.
  42423. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42424. */
  42425. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  42426. var vis = size / 2;
  42427. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  42428. };
  42429. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  42430. // getter and setter
  42431. get: function () {
  42432. return this._alwaysVisible;
  42433. },
  42434. /**
  42435. * Sets the SPS as always visible or not
  42436. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42437. */
  42438. set: function (val) {
  42439. this._alwaysVisible = val;
  42440. this.mesh.alwaysSelectAsActiveMesh = val;
  42441. },
  42442. enumerable: true,
  42443. configurable: true
  42444. });
  42445. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42446. get: function () {
  42447. return this._isVisibilityBoxLocked;
  42448. },
  42449. /**
  42450. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42451. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42452. */
  42453. set: function (val) {
  42454. this._isVisibilityBoxLocked = val;
  42455. this.mesh.getBoundingInfo().isLocked = val;
  42456. },
  42457. enumerable: true,
  42458. configurable: true
  42459. });
  42460. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42461. // getters
  42462. get: function () {
  42463. return this._computeParticleRotation;
  42464. },
  42465. // Optimizer setters
  42466. /**
  42467. * Tells to `setParticles()` to compute the particle rotations or not.
  42468. * Default value : true. The SPS is faster when it's set to false.
  42469. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42470. */
  42471. set: function (val) {
  42472. this._computeParticleRotation = val;
  42473. },
  42474. enumerable: true,
  42475. configurable: true
  42476. });
  42477. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42478. get: function () {
  42479. return this._computeParticleColor;
  42480. },
  42481. /**
  42482. * Tells to `setParticles()` to compute the particle colors or not.
  42483. * Default value : true. The SPS is faster when it's set to false.
  42484. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42485. */
  42486. set: function (val) {
  42487. this._computeParticleColor = val;
  42488. },
  42489. enumerable: true,
  42490. configurable: true
  42491. });
  42492. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42493. get: function () {
  42494. return this._computeParticleTexture;
  42495. },
  42496. /**
  42497. * Tells to `setParticles()` to compute the particle textures or not.
  42498. * Default value : true. The SPS is faster when it's set to false.
  42499. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42500. */
  42501. set: function (val) {
  42502. this._computeParticleTexture = val;
  42503. },
  42504. enumerable: true,
  42505. configurable: true
  42506. });
  42507. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42508. get: function () {
  42509. return this._computeParticleVertex;
  42510. },
  42511. /**
  42512. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42513. * Default value : false. The SPS is faster when it's set to false.
  42514. * Note : the particle custom vertex positions aren't stored values.
  42515. */
  42516. set: function (val) {
  42517. this._computeParticleVertex = val;
  42518. },
  42519. enumerable: true,
  42520. configurable: true
  42521. });
  42522. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42523. get: function () {
  42524. return this._computeBoundingBox;
  42525. },
  42526. /**
  42527. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42528. */
  42529. set: function (val) {
  42530. this._computeBoundingBox = val;
  42531. },
  42532. enumerable: true,
  42533. configurable: true
  42534. });
  42535. // =======================================================================
  42536. // Particle behavior logic
  42537. // these following methods may be overwritten by the user to fit his needs
  42538. /**
  42539. * This function does nothing. It may be overwritten to set all the particle first values.
  42540. * The SPS doesn't call this function, you may have to call it by your own.
  42541. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42542. */
  42543. SolidParticleSystem.prototype.initParticles = function () {
  42544. };
  42545. /**
  42546. * This function does nothing. It may be overwritten to recycle a particle.
  42547. * The SPS doesn't call this function, you may have to call it by your own.
  42548. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42549. */
  42550. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42551. return particle;
  42552. };
  42553. /**
  42554. * Updates a particle : this function should be overwritten by the user.
  42555. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42556. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42557. * ex : just set a particle position or velocity and recycle conditions
  42558. */
  42559. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42560. return particle;
  42561. };
  42562. /**
  42563. * Updates a vertex of a particle : it can be overwritten by the user.
  42564. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42565. * @param particle the current particle
  42566. * @param vertex the current index of the current particle
  42567. * @param pt the index of the current vertex in the particle shape
  42568. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  42569. * ex : just set a vertex particle position
  42570. */
  42571. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42572. return vertex;
  42573. };
  42574. /**
  42575. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42576. * This does nothing and may be overwritten by the user.
  42577. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42578. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42579. * @param update the boolean update value actually passed to setParticles()
  42580. */
  42581. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42582. };
  42583. /**
  42584. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42585. * This will be passed three parameters.
  42586. * This does nothing and may be overwritten by the user.
  42587. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42588. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42589. * @param update the boolean update value actually passed to setParticles()
  42590. */
  42591. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42592. };
  42593. return SolidParticleSystem;
  42594. }());
  42595. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42596. })(BABYLON || (BABYLON = {}));
  42597. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  42598. /// <reference path="babylon.mesh.ts" />
  42599. var BABYLON;
  42600. (function (BABYLON) {
  42601. var GroundMesh = (function (_super) {
  42602. __extends(GroundMesh, _super);
  42603. function GroundMesh(name, scene) {
  42604. var _this = _super.call(this, name, scene) || this;
  42605. _this.generateOctree = false;
  42606. _this._worldInverse = new BABYLON.Matrix();
  42607. return _this;
  42608. }
  42609. GroundMesh.prototype.getClassName = function () {
  42610. return "GroundMesh";
  42611. };
  42612. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  42613. get: function () {
  42614. return Math.min(this._subdivisionsX, this._subdivisionsY);
  42615. },
  42616. enumerable: true,
  42617. configurable: true
  42618. });
  42619. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  42620. get: function () {
  42621. return this._subdivisionsX;
  42622. },
  42623. enumerable: true,
  42624. configurable: true
  42625. });
  42626. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  42627. get: function () {
  42628. return this._subdivisionsY;
  42629. },
  42630. enumerable: true,
  42631. configurable: true
  42632. });
  42633. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  42634. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  42635. this._subdivisionsX = chunksCount;
  42636. this._subdivisionsY = chunksCount;
  42637. this.subdivide(chunksCount);
  42638. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  42639. };
  42640. /**
  42641. * Returns a height (y) value in the Worl system :
  42642. * the ground altitude at the coordinates (x, z) expressed in the World system.
  42643. * Returns the ground y position if (x, z) are outside the ground surface.
  42644. */
  42645. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  42646. var world = this.getWorldMatrix();
  42647. var invMat = BABYLON.Tmp.Matrix[5];
  42648. world.invertToRef(invMat);
  42649. var tmpVect = BABYLON.Tmp.Vector3[8];
  42650. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  42651. x = tmpVect.x;
  42652. z = tmpVect.z;
  42653. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42654. return this.position.y;
  42655. }
  42656. if (!this._heightQuads || this._heightQuads.length == 0) {
  42657. this._initHeightQuads();
  42658. this._computeHeightQuads();
  42659. }
  42660. var facet = this._getFacetAt(x, z);
  42661. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  42662. // return y in the World system
  42663. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  42664. return tmpVect.y;
  42665. };
  42666. /**
  42667. * Returns a normalized vector (Vector3) orthogonal to the ground
  42668. * at the ground coordinates (x, z) expressed in the World system.
  42669. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  42670. */
  42671. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  42672. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  42673. this.getNormalAtCoordinatesToRef(x, z, normal);
  42674. return normal;
  42675. };
  42676. /**
  42677. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  42678. * at the ground coordinates (x, z) expressed in the World system.
  42679. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  42680. * Returns the GroundMesh.
  42681. */
  42682. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  42683. var world = this.getWorldMatrix();
  42684. var tmpMat = BABYLON.Tmp.Matrix[5];
  42685. world.invertToRef(tmpMat);
  42686. var tmpVect = BABYLON.Tmp.Vector3[8];
  42687. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  42688. x = tmpVect.x;
  42689. z = tmpVect.z;
  42690. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42691. return this;
  42692. }
  42693. if (!this._heightQuads || this._heightQuads.length == 0) {
  42694. this._initHeightQuads();
  42695. this._computeHeightQuads();
  42696. }
  42697. var facet = this._getFacetAt(x, z);
  42698. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  42699. return this;
  42700. };
  42701. /**
  42702. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  42703. * if the ground has been updated.
  42704. * This can be used in the render loop.
  42705. * Returns the GroundMesh.
  42706. */
  42707. GroundMesh.prototype.updateCoordinateHeights = function () {
  42708. if (!this._heightQuads || this._heightQuads.length == 0) {
  42709. this._initHeightQuads();
  42710. }
  42711. this._computeHeightQuads();
  42712. return this;
  42713. };
  42714. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  42715. GroundMesh.prototype._getFacetAt = function (x, z) {
  42716. // retrieve col and row from x, z coordinates in the ground local system
  42717. var subdivisionsX = this._subdivisionsX;
  42718. var subdivisionsY = this._subdivisionsY;
  42719. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  42720. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  42721. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42722. var facet;
  42723. if (z < quad.slope.x * x + quad.slope.y) {
  42724. facet = quad.facet1;
  42725. }
  42726. else {
  42727. facet = quad.facet2;
  42728. }
  42729. return facet;
  42730. };
  42731. // Creates and populates the heightMap array with "facet" elements :
  42732. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42733. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42734. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42735. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42736. // Returns the GroundMesh.
  42737. GroundMesh.prototype._initHeightQuads = function () {
  42738. var subdivisionsX = this._subdivisionsX;
  42739. var subdivisionsY = this._subdivisionsY;
  42740. this._heightQuads = new Array();
  42741. for (var row = 0; row < subdivisionsY; row++) {
  42742. for (var col = 0; col < subdivisionsX; col++) {
  42743. 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) };
  42744. this._heightQuads[row * subdivisionsX + col] = quad;
  42745. }
  42746. }
  42747. return this;
  42748. };
  42749. // Compute each quad element values and update the the heightMap array :
  42750. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42751. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42752. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42753. // Returns the GroundMesh.
  42754. GroundMesh.prototype._computeHeightQuads = function () {
  42755. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42756. var v1 = BABYLON.Tmp.Vector3[3];
  42757. var v2 = BABYLON.Tmp.Vector3[2];
  42758. var v3 = BABYLON.Tmp.Vector3[1];
  42759. var v4 = BABYLON.Tmp.Vector3[0];
  42760. var v1v2 = BABYLON.Tmp.Vector3[4];
  42761. var v1v3 = BABYLON.Tmp.Vector3[5];
  42762. var v1v4 = BABYLON.Tmp.Vector3[6];
  42763. var norm1 = BABYLON.Tmp.Vector3[7];
  42764. var norm2 = BABYLON.Tmp.Vector3[8];
  42765. var i = 0;
  42766. var j = 0;
  42767. var k = 0;
  42768. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42769. var h = 0;
  42770. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42771. var d2 = 0;
  42772. var subdivisionsX = this._subdivisionsX;
  42773. var subdivisionsY = this._subdivisionsY;
  42774. for (var row = 0; row < subdivisionsY; row++) {
  42775. for (var col = 0; col < subdivisionsX; col++) {
  42776. i = col * 3;
  42777. j = row * (subdivisionsX + 1) * 3;
  42778. k = (row + 1) * (subdivisionsX + 1) * 3;
  42779. v1.x = positions[j + i];
  42780. v1.y = positions[j + i + 1];
  42781. v1.z = positions[j + i + 2];
  42782. v2.x = positions[j + i + 3];
  42783. v2.y = positions[j + i + 4];
  42784. v2.z = positions[j + i + 5];
  42785. v3.x = positions[k + i];
  42786. v3.y = positions[k + i + 1];
  42787. v3.z = positions[k + i + 2];
  42788. v4.x = positions[k + i + 3];
  42789. v4.y = positions[k + i + 4];
  42790. v4.z = positions[k + i + 5];
  42791. // 2D slope V1V4
  42792. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42793. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42794. // facet equations :
  42795. // we compute each facet normal vector
  42796. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42797. // we compute the value d by applying the equation to v1 which belongs to the plane
  42798. // then we store the facet equation in a Vector4
  42799. v2.subtractToRef(v1, v1v2);
  42800. v3.subtractToRef(v1, v1v3);
  42801. v4.subtractToRef(v1, v1v4);
  42802. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42803. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42804. norm1.normalize();
  42805. norm2.normalize();
  42806. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42807. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42808. var quad = this._heightQuads[row * subdivisionsX + col];
  42809. quad.slope.copyFromFloats(cd, h);
  42810. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42811. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42812. }
  42813. }
  42814. return this;
  42815. };
  42816. GroundMesh.prototype.serialize = function (serializationObject) {
  42817. _super.prototype.serialize.call(this, serializationObject);
  42818. serializationObject.subdivisionsX = this._subdivisionsX;
  42819. serializationObject.subdivisionsY = this._subdivisionsY;
  42820. serializationObject.minX = this._minX;
  42821. serializationObject.maxX = this._maxX;
  42822. serializationObject.minZ = this._minZ;
  42823. serializationObject.maxZ = this._maxZ;
  42824. serializationObject.width = this._width;
  42825. serializationObject.height = this._height;
  42826. };
  42827. GroundMesh.Parse = function (parsedMesh, scene) {
  42828. var result = new GroundMesh(parsedMesh.name, scene);
  42829. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  42830. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  42831. result._minX = parsedMesh.minX;
  42832. result._maxX = parsedMesh.maxX;
  42833. result._minZ = parsedMesh.minZ;
  42834. result._maxZ = parsedMesh.maxZ;
  42835. result._width = parsedMesh.width;
  42836. result._height = parsedMesh.height;
  42837. return result;
  42838. };
  42839. return GroundMesh;
  42840. }(BABYLON.Mesh));
  42841. BABYLON.GroundMesh = GroundMesh;
  42842. })(BABYLON || (BABYLON = {}));
  42843. //# sourceMappingURL=babylon.groundMesh.js.map
  42844. var BABYLON;
  42845. (function (BABYLON) {
  42846. /**
  42847. * Creates an instance based on a source mesh.
  42848. */
  42849. var InstancedMesh = (function (_super) {
  42850. __extends(InstancedMesh, _super);
  42851. function InstancedMesh(name, source) {
  42852. var _this = _super.call(this, name, source.getScene()) || this;
  42853. source.instances.push(_this);
  42854. _this._sourceMesh = source;
  42855. _this.position.copyFrom(source.position);
  42856. _this.rotation.copyFrom(source.rotation);
  42857. _this.scaling.copyFrom(source.scaling);
  42858. if (source.rotationQuaternion) {
  42859. _this.rotationQuaternion = source.rotationQuaternion.clone();
  42860. }
  42861. _this.infiniteDistance = source.infiniteDistance;
  42862. _this.setPivotMatrix(source.getPivotMatrix());
  42863. _this.refreshBoundingInfo();
  42864. _this._syncSubMeshes();
  42865. return _this;
  42866. }
  42867. /**
  42868. * Returns the string "InstancedMesh".
  42869. */
  42870. InstancedMesh.prototype.getClassName = function () {
  42871. return "InstancedMesh";
  42872. };
  42873. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  42874. // Methods
  42875. get: function () {
  42876. return this._sourceMesh.receiveShadows;
  42877. },
  42878. enumerable: true,
  42879. configurable: true
  42880. });
  42881. Object.defineProperty(InstancedMesh.prototype, "material", {
  42882. get: function () {
  42883. return this._sourceMesh.material;
  42884. },
  42885. enumerable: true,
  42886. configurable: true
  42887. });
  42888. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  42889. get: function () {
  42890. return this._sourceMesh.visibility;
  42891. },
  42892. enumerable: true,
  42893. configurable: true
  42894. });
  42895. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  42896. get: function () {
  42897. return this._sourceMesh.skeleton;
  42898. },
  42899. enumerable: true,
  42900. configurable: true
  42901. });
  42902. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  42903. get: function () {
  42904. return this._sourceMesh.renderingGroupId;
  42905. },
  42906. enumerable: true,
  42907. configurable: true
  42908. });
  42909. /**
  42910. * Returns the total number of vertices (integer).
  42911. */
  42912. InstancedMesh.prototype.getTotalVertices = function () {
  42913. return this._sourceMesh.getTotalVertices();
  42914. };
  42915. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  42916. get: function () {
  42917. return this._sourceMesh;
  42918. },
  42919. enumerable: true,
  42920. configurable: true
  42921. });
  42922. /**
  42923. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  42924. */
  42925. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  42926. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  42927. };
  42928. /**
  42929. * Sets the vertex data of the mesh geometry for the requested `kind`.
  42930. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  42931. * The `data` are either a numeric array either a Float32Array.
  42932. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  42933. * 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).
  42934. * Note that a new underlying VertexBuffer object is created each call.
  42935. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  42936. *
  42937. * Possible `kind` values :
  42938. * - BABYLON.VertexBuffer.PositionKind
  42939. * - BABYLON.VertexBuffer.UVKind
  42940. * - BABYLON.VertexBuffer.UV2Kind
  42941. * - BABYLON.VertexBuffer.UV3Kind
  42942. * - BABYLON.VertexBuffer.UV4Kind
  42943. * - BABYLON.VertexBuffer.UV5Kind
  42944. * - BABYLON.VertexBuffer.UV6Kind
  42945. * - BABYLON.VertexBuffer.ColorKind
  42946. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42947. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42948. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42949. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42950. *
  42951. * Returns the Mesh.
  42952. */
  42953. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  42954. if (this.sourceMesh) {
  42955. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  42956. }
  42957. return this.sourceMesh;
  42958. };
  42959. /**
  42960. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  42961. * If the mesh has no geometry, it is simply returned as it is.
  42962. * The `data` are either a numeric array either a Float32Array.
  42963. * No new underlying VertexBuffer object is created.
  42964. * 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.
  42965. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  42966. *
  42967. * Possible `kind` values :
  42968. * - BABYLON.VertexBuffer.PositionKind
  42969. * - BABYLON.VertexBuffer.UVKind
  42970. * - BABYLON.VertexBuffer.UV2Kind
  42971. * - BABYLON.VertexBuffer.UV3Kind
  42972. * - BABYLON.VertexBuffer.UV4Kind
  42973. * - BABYLON.VertexBuffer.UV5Kind
  42974. * - BABYLON.VertexBuffer.UV6Kind
  42975. * - BABYLON.VertexBuffer.ColorKind
  42976. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42977. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42978. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42979. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42980. *
  42981. * Returns the Mesh.
  42982. */
  42983. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  42984. if (this.sourceMesh) {
  42985. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  42986. }
  42987. return this.sourceMesh;
  42988. };
  42989. /**
  42990. * Sets the mesh indices.
  42991. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  42992. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  42993. * This method creates a new index buffer each call.
  42994. * Returns the Mesh.
  42995. */
  42996. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  42997. if (this.sourceMesh) {
  42998. this.sourceMesh.setIndices(indices, totalVertices);
  42999. }
  43000. return this.sourceMesh;
  43001. };
  43002. /**
  43003. * Boolean : True if the mesh owns the requested kind of data.
  43004. */
  43005. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  43006. return this._sourceMesh.isVerticesDataPresent(kind);
  43007. };
  43008. /**
  43009. * Returns an array of indices (IndicesArray).
  43010. */
  43011. InstancedMesh.prototype.getIndices = function () {
  43012. return this._sourceMesh.getIndices();
  43013. };
  43014. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  43015. get: function () {
  43016. return this._sourceMesh._positions;
  43017. },
  43018. enumerable: true,
  43019. configurable: true
  43020. });
  43021. /**
  43022. * Sets a new updated BoundingInfo to the mesh.
  43023. * Returns the mesh.
  43024. */
  43025. InstancedMesh.prototype.refreshBoundingInfo = function () {
  43026. var meshBB = this._sourceMesh.getBoundingInfo();
  43027. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  43028. this._updateBoundingInfo();
  43029. return this;
  43030. };
  43031. InstancedMesh.prototype._preActivate = function () {
  43032. if (this._currentLOD) {
  43033. this._currentLOD._preActivate();
  43034. }
  43035. return this;
  43036. };
  43037. InstancedMesh.prototype._activate = function (renderId) {
  43038. if (this._currentLOD) {
  43039. this._currentLOD._registerInstanceForRenderId(this, renderId);
  43040. }
  43041. return this;
  43042. };
  43043. /**
  43044. * Returns the current associated LOD AbstractMesh.
  43045. */
  43046. InstancedMesh.prototype.getLOD = function (camera) {
  43047. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  43048. if (this._currentLOD === this.sourceMesh) {
  43049. return this;
  43050. }
  43051. return this._currentLOD;
  43052. };
  43053. InstancedMesh.prototype._syncSubMeshes = function () {
  43054. this.releaseSubMeshes();
  43055. if (this._sourceMesh.subMeshes) {
  43056. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  43057. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  43058. }
  43059. }
  43060. return this;
  43061. };
  43062. InstancedMesh.prototype._generatePointsArray = function () {
  43063. return this._sourceMesh._generatePointsArray();
  43064. };
  43065. /**
  43066. * Creates a new InstancedMesh from the current mesh.
  43067. * - name (string) : the cloned mesh name
  43068. * - newParent (optional Node) : the optional Node to parent the clone to.
  43069. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  43070. *
  43071. * Returns the clone.
  43072. */
  43073. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43074. var result = this._sourceMesh.createInstance(name);
  43075. // Deep copy
  43076. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  43077. // Bounding info
  43078. this.refreshBoundingInfo();
  43079. // Parent
  43080. if (newParent) {
  43081. result.parent = newParent;
  43082. }
  43083. if (!doNotCloneChildren) {
  43084. // Children
  43085. for (var index = 0; index < this.getScene().meshes.length; index++) {
  43086. var mesh = this.getScene().meshes[index];
  43087. if (mesh.parent === this) {
  43088. mesh.clone(mesh.name, result);
  43089. }
  43090. }
  43091. }
  43092. result.computeWorldMatrix(true);
  43093. return result;
  43094. };
  43095. /**
  43096. * Disposes the InstancedMesh.
  43097. * Returns nothing.
  43098. */
  43099. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  43100. // Remove from mesh
  43101. var index = this._sourceMesh.instances.indexOf(this);
  43102. this._sourceMesh.instances.splice(index, 1);
  43103. _super.prototype.dispose.call(this, doNotRecurse);
  43104. };
  43105. return InstancedMesh;
  43106. }(BABYLON.AbstractMesh));
  43107. BABYLON.InstancedMesh = InstancedMesh;
  43108. })(BABYLON || (BABYLON = {}));
  43109. //# sourceMappingURL=babylon.instancedMesh.js.map
  43110. /// <reference path="babylon.mesh.ts" />
  43111. var BABYLON;
  43112. (function (BABYLON) {
  43113. var LinesMesh = (function (_super) {
  43114. __extends(LinesMesh, _super);
  43115. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  43116. if (parent === void 0) { parent = null; }
  43117. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  43118. _this.useVertexColor = useVertexColor;
  43119. _this.color = new BABYLON.Color3(1, 1, 1);
  43120. _this.alpha = 1;
  43121. if (source) {
  43122. _this.color = source.color.clone();
  43123. _this.alpha = source.alpha;
  43124. _this.useVertexColor = source.useVertexColor;
  43125. }
  43126. _this._intersectionThreshold = 0.1;
  43127. var options = {
  43128. attributes: [BABYLON.VertexBuffer.PositionKind],
  43129. uniforms: ["world", "viewProjection"],
  43130. needAlphaBlending: false,
  43131. };
  43132. if (!useVertexColor) {
  43133. options.uniforms.push("color");
  43134. options.needAlphaBlending = true;
  43135. }
  43136. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  43137. return _this;
  43138. }
  43139. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  43140. /**
  43141. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43142. * This margin is expressed in world space coordinates, so its value may vary.
  43143. * Default value is 0.1
  43144. * @returns the intersection Threshold value.
  43145. */
  43146. get: function () {
  43147. return this._intersectionThreshold;
  43148. },
  43149. /**
  43150. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43151. * This margin is expressed in world space coordinates, so its value may vary.
  43152. * @param value the new threshold to apply
  43153. */
  43154. set: function (value) {
  43155. if (this._intersectionThreshold === value) {
  43156. return;
  43157. }
  43158. this._intersectionThreshold = value;
  43159. if (this.geometry) {
  43160. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  43161. }
  43162. },
  43163. enumerable: true,
  43164. configurable: true
  43165. });
  43166. /**
  43167. * Returns the string "LineMesh"
  43168. */
  43169. LinesMesh.prototype.getClassName = function () {
  43170. return "LinesMesh";
  43171. };
  43172. Object.defineProperty(LinesMesh.prototype, "material", {
  43173. get: function () {
  43174. return this._colorShader;
  43175. },
  43176. enumerable: true,
  43177. configurable: true
  43178. });
  43179. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  43180. get: function () {
  43181. return false;
  43182. },
  43183. enumerable: true,
  43184. configurable: true
  43185. });
  43186. LinesMesh.prototype.createInstance = function (name) {
  43187. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  43188. return null;
  43189. };
  43190. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  43191. // VBOs
  43192. this._geometry._bind(this._colorShader.getEffect());
  43193. // Color
  43194. if (!this.useVertexColor) {
  43195. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  43196. }
  43197. return this;
  43198. };
  43199. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  43200. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  43201. return this;
  43202. }
  43203. var engine = this.getScene().getEngine();
  43204. // Draw order
  43205. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  43206. return this;
  43207. };
  43208. LinesMesh.prototype.dispose = function (doNotRecurse) {
  43209. this._colorShader.dispose();
  43210. _super.prototype.dispose.call(this, doNotRecurse);
  43211. };
  43212. /**
  43213. * Returns a new LineMesh object cloned from the current one.
  43214. */
  43215. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43216. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  43217. };
  43218. return LinesMesh;
  43219. }(BABYLON.Mesh));
  43220. BABYLON.LinesMesh = LinesMesh;
  43221. })(BABYLON || (BABYLON = {}));
  43222. //# sourceMappingURL=babylon.linesMesh.js.map
  43223. var BABYLON;
  43224. (function (BABYLON) {
  43225. var ShaderMaterial = (function (_super) {
  43226. __extends(ShaderMaterial, _super);
  43227. function ShaderMaterial(name, scene, shaderPath, options) {
  43228. var _this = _super.call(this, name, scene) || this;
  43229. _this._textures = {};
  43230. _this._textureArrays = {};
  43231. _this._floats = {};
  43232. _this._floatsArrays = {};
  43233. _this._colors3 = {};
  43234. _this._colors3Arrays = {};
  43235. _this._colors4 = {};
  43236. _this._vectors2 = {};
  43237. _this._vectors3 = {};
  43238. _this._vectors4 = {};
  43239. _this._matrices = {};
  43240. _this._matrices3x3 = {};
  43241. _this._matrices2x2 = {};
  43242. _this._vectors3Arrays = {};
  43243. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  43244. _this._shaderPath = shaderPath;
  43245. options.needAlphaBlending = options.needAlphaBlending || false;
  43246. options.needAlphaTesting = options.needAlphaTesting || false;
  43247. options.attributes = options.attributes || ["position", "normal", "uv"];
  43248. options.uniforms = options.uniforms || ["worldViewProjection"];
  43249. options.uniformBuffers = options.uniformBuffers || [];
  43250. options.samplers = options.samplers || [];
  43251. options.defines = options.defines || [];
  43252. _this._options = options;
  43253. return _this;
  43254. }
  43255. ShaderMaterial.prototype.getClassName = function () {
  43256. return "ShaderMaterial";
  43257. };
  43258. ShaderMaterial.prototype.needAlphaBlending = function () {
  43259. return this._options.needAlphaBlending;
  43260. };
  43261. ShaderMaterial.prototype.needAlphaTesting = function () {
  43262. return this._options.needAlphaTesting;
  43263. };
  43264. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  43265. if (this._options.uniforms.indexOf(uniformName) === -1) {
  43266. this._options.uniforms.push(uniformName);
  43267. }
  43268. };
  43269. ShaderMaterial.prototype.setTexture = function (name, texture) {
  43270. if (this._options.samplers.indexOf(name) === -1) {
  43271. this._options.samplers.push(name);
  43272. }
  43273. this._textures[name] = texture;
  43274. return this;
  43275. };
  43276. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  43277. if (this._options.samplers.indexOf(name) === -1) {
  43278. this._options.samplers.push(name);
  43279. }
  43280. this._checkUniform(name);
  43281. this._textureArrays[name] = textures;
  43282. return this;
  43283. };
  43284. ShaderMaterial.prototype.setFloat = function (name, value) {
  43285. this._checkUniform(name);
  43286. this._floats[name] = value;
  43287. return this;
  43288. };
  43289. ShaderMaterial.prototype.setFloats = function (name, value) {
  43290. this._checkUniform(name);
  43291. this._floatsArrays[name] = value;
  43292. return this;
  43293. };
  43294. ShaderMaterial.prototype.setColor3 = function (name, value) {
  43295. this._checkUniform(name);
  43296. this._colors3[name] = value;
  43297. return this;
  43298. };
  43299. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  43300. this._checkUniform(name);
  43301. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  43302. color.toArray(arr, arr.length);
  43303. return arr;
  43304. }, []);
  43305. return this;
  43306. };
  43307. ShaderMaterial.prototype.setColor4 = function (name, value) {
  43308. this._checkUniform(name);
  43309. this._colors4[name] = value;
  43310. return this;
  43311. };
  43312. ShaderMaterial.prototype.setVector2 = function (name, value) {
  43313. this._checkUniform(name);
  43314. this._vectors2[name] = value;
  43315. return this;
  43316. };
  43317. ShaderMaterial.prototype.setVector3 = function (name, value) {
  43318. this._checkUniform(name);
  43319. this._vectors3[name] = value;
  43320. return this;
  43321. };
  43322. ShaderMaterial.prototype.setVector4 = function (name, value) {
  43323. this._checkUniform(name);
  43324. this._vectors4[name] = value;
  43325. return this;
  43326. };
  43327. ShaderMaterial.prototype.setMatrix = function (name, value) {
  43328. this._checkUniform(name);
  43329. this._matrices[name] = value;
  43330. return this;
  43331. };
  43332. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  43333. this._checkUniform(name);
  43334. this._matrices3x3[name] = value;
  43335. return this;
  43336. };
  43337. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  43338. this._checkUniform(name);
  43339. this._matrices2x2[name] = value;
  43340. return this;
  43341. };
  43342. ShaderMaterial.prototype.setArray3 = function (name, value) {
  43343. this._checkUniform(name);
  43344. this._vectors3Arrays[name] = value;
  43345. return this;
  43346. };
  43347. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  43348. if (!mesh) {
  43349. return true;
  43350. }
  43351. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  43352. return false;
  43353. }
  43354. return false;
  43355. };
  43356. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  43357. var scene = this.getScene();
  43358. var engine = scene.getEngine();
  43359. if (!this.checkReadyOnEveryCall) {
  43360. if (this._renderId === scene.getRenderId()) {
  43361. if (this._checkCache(scene, mesh, useInstances)) {
  43362. return true;
  43363. }
  43364. }
  43365. }
  43366. // Instances
  43367. var defines = [];
  43368. var attribs = [];
  43369. var fallbacks = new BABYLON.EffectFallbacks();
  43370. if (useInstances) {
  43371. defines.push("#define INSTANCES");
  43372. }
  43373. for (var index = 0; index < this._options.defines.length; index++) {
  43374. defines.push(this._options.defines[index]);
  43375. }
  43376. for (var index = 0; index < this._options.attributes.length; index++) {
  43377. attribs.push(this._options.attributes[index]);
  43378. }
  43379. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  43380. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43381. defines.push("#define VERTEXCOLOR");
  43382. }
  43383. // Bones
  43384. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  43385. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43386. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43387. if (mesh.numBoneInfluencers > 4) {
  43388. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43389. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43390. }
  43391. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43392. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43393. fallbacks.addCPUSkinningFallback(0, mesh);
  43394. if (this._options.uniforms.indexOf("mBones") === -1) {
  43395. this._options.uniforms.push("mBones");
  43396. }
  43397. }
  43398. else {
  43399. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43400. }
  43401. // Textures
  43402. for (var name in this._textures) {
  43403. if (!this._textures[name].isReady()) {
  43404. return false;
  43405. }
  43406. }
  43407. // Alpha test
  43408. if (engine.getAlphaTesting()) {
  43409. defines.push("#define ALPHATEST");
  43410. }
  43411. var previousEffect = this._effect;
  43412. var join = defines.join("\n");
  43413. this._effect = engine.createEffect(this._shaderPath, {
  43414. attributes: attribs,
  43415. uniformsNames: this._options.uniforms,
  43416. uniformBuffersNames: this._options.uniformBuffers,
  43417. samplers: this._options.samplers,
  43418. defines: join,
  43419. fallbacks: fallbacks,
  43420. onCompiled: this.onCompiled,
  43421. onError: this.onError
  43422. }, engine);
  43423. if (!this._effect.isReady()) {
  43424. return false;
  43425. }
  43426. if (previousEffect !== this._effect) {
  43427. scene.resetCachedMaterial();
  43428. }
  43429. this._renderId = scene.getRenderId();
  43430. return true;
  43431. };
  43432. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43433. var scene = this.getScene();
  43434. if (this._options.uniforms.indexOf("world") !== -1) {
  43435. this._effect.setMatrix("world", world);
  43436. }
  43437. if (this._options.uniforms.indexOf("worldView") !== -1) {
  43438. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  43439. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  43440. }
  43441. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  43442. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  43443. }
  43444. };
  43445. ShaderMaterial.prototype.bind = function (world, mesh) {
  43446. // Std values
  43447. this.bindOnlyWorldMatrix(world);
  43448. if (this.getScene().getCachedMaterial() !== this) {
  43449. if (this._options.uniforms.indexOf("view") !== -1) {
  43450. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  43451. }
  43452. if (this._options.uniforms.indexOf("projection") !== -1) {
  43453. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  43454. }
  43455. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  43456. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  43457. }
  43458. // Bones
  43459. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  43460. var name;
  43461. // Texture
  43462. for (name in this._textures) {
  43463. this._effect.setTexture(name, this._textures[name]);
  43464. }
  43465. // Texture arrays
  43466. for (name in this._textureArrays) {
  43467. this._effect.setTextureArray(name, this._textureArrays[name]);
  43468. }
  43469. // Float
  43470. for (name in this._floats) {
  43471. this._effect.setFloat(name, this._floats[name]);
  43472. }
  43473. // Float s
  43474. for (name in this._floatsArrays) {
  43475. this._effect.setArray(name, this._floatsArrays[name]);
  43476. }
  43477. // Color3
  43478. for (name in this._colors3) {
  43479. this._effect.setColor3(name, this._colors3[name]);
  43480. }
  43481. for (name in this._colors3Arrays) {
  43482. this._effect.setArray3(name, this._colors3Arrays[name]);
  43483. }
  43484. // Color4
  43485. for (name in this._colors4) {
  43486. var color = this._colors4[name];
  43487. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43488. }
  43489. // Vector2
  43490. for (name in this._vectors2) {
  43491. this._effect.setVector2(name, this._vectors2[name]);
  43492. }
  43493. // Vector3
  43494. for (name in this._vectors3) {
  43495. this._effect.setVector3(name, this._vectors3[name]);
  43496. }
  43497. // Vector4
  43498. for (name in this._vectors4) {
  43499. this._effect.setVector4(name, this._vectors4[name]);
  43500. }
  43501. // Matrix
  43502. for (name in this._matrices) {
  43503. this._effect.setMatrix(name, this._matrices[name]);
  43504. }
  43505. // Matrix 3x3
  43506. for (name in this._matrices3x3) {
  43507. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  43508. }
  43509. // Matrix 2x2
  43510. for (name in this._matrices2x2) {
  43511. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  43512. }
  43513. // Vector3Array
  43514. for (name in this._vectors3Arrays) {
  43515. this._effect.setArray3(name, this._vectors3Arrays[name]);
  43516. }
  43517. }
  43518. this._afterBind(mesh);
  43519. };
  43520. ShaderMaterial.prototype.getActiveTextures = function () {
  43521. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43522. for (var name in this._textures) {
  43523. activeTextures.push(this._textures[name]);
  43524. }
  43525. for (var name in this._textureArrays) {
  43526. var array = this._textureArrays[name];
  43527. for (var index = 0; index < array.length; index++) {
  43528. activeTextures.push(array[index]);
  43529. }
  43530. }
  43531. return activeTextures;
  43532. };
  43533. ShaderMaterial.prototype.hasTexture = function (texture) {
  43534. if (_super.prototype.hasTexture.call(this, texture)) {
  43535. return true;
  43536. }
  43537. for (var name in this._textures) {
  43538. if (this._textures[name] === texture) {
  43539. return true;
  43540. }
  43541. }
  43542. for (var name in this._textureArrays) {
  43543. var array = this._textureArrays[name];
  43544. for (var index = 0; index < array.length; index++) {
  43545. if (array[index] === texture) {
  43546. return true;
  43547. }
  43548. }
  43549. }
  43550. return false;
  43551. };
  43552. ShaderMaterial.prototype.clone = function (name) {
  43553. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  43554. return newShaderMaterial;
  43555. };
  43556. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43557. if (forceDisposeTextures) {
  43558. var name;
  43559. for (name in this._textures) {
  43560. this._textures[name].dispose();
  43561. }
  43562. for (name in this._textureArrays) {
  43563. var array = this._textureArrays[name];
  43564. for (var index = 0; index < array.length; index++) {
  43565. array[index].dispose();
  43566. }
  43567. }
  43568. }
  43569. this._textures = {};
  43570. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43571. };
  43572. ShaderMaterial.prototype.serialize = function () {
  43573. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43574. serializationObject.customType = "BABYLON.ShaderMaterial";
  43575. serializationObject.options = this._options;
  43576. serializationObject.shaderPath = this._shaderPath;
  43577. var name;
  43578. // Texture
  43579. serializationObject.textures = {};
  43580. for (name in this._textures) {
  43581. serializationObject.textures[name] = this._textures[name].serialize();
  43582. }
  43583. // Texture arrays
  43584. serializationObject.textureArrays = {};
  43585. for (name in this._textureArrays) {
  43586. serializationObject.textureArrays[name] = [];
  43587. var array = this._textureArrays[name];
  43588. for (var index = 0; index < array.length; index++) {
  43589. serializationObject.textureArrays[name].push(array[index].serialize());
  43590. }
  43591. }
  43592. // Float
  43593. serializationObject.floats = {};
  43594. for (name in this._floats) {
  43595. serializationObject.floats[name] = this._floats[name];
  43596. }
  43597. // Float s
  43598. serializationObject.floatArrays = {};
  43599. for (name in this._floatsArrays) {
  43600. serializationObject.floatArrays[name] = this._floatsArrays[name];
  43601. }
  43602. // Color3
  43603. serializationObject.colors3 = {};
  43604. for (name in this._colors3) {
  43605. serializationObject.colors3[name] = this._colors3[name].asArray();
  43606. }
  43607. // Color3 array
  43608. serializationObject.colors3Arrays = {};
  43609. for (name in this._colors3Arrays) {
  43610. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  43611. }
  43612. // Color4
  43613. serializationObject.colors4 = {};
  43614. for (name in this._colors4) {
  43615. serializationObject.colors4[name] = this._colors4[name].asArray();
  43616. }
  43617. // Vector2
  43618. serializationObject.vectors2 = {};
  43619. for (name in this._vectors2) {
  43620. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  43621. }
  43622. // Vector3
  43623. serializationObject.vectors3 = {};
  43624. for (name in this._vectors3) {
  43625. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  43626. }
  43627. // Vector4
  43628. serializationObject.vectors4 = {};
  43629. for (name in this._vectors4) {
  43630. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  43631. }
  43632. // Matrix
  43633. serializationObject.matrices = {};
  43634. for (name in this._matrices) {
  43635. serializationObject.matrices[name] = this._matrices[name].asArray();
  43636. }
  43637. // Matrix 3x3
  43638. serializationObject.matrices3x3 = {};
  43639. for (name in this._matrices3x3) {
  43640. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  43641. }
  43642. // Matrix 2x2
  43643. serializationObject.matrices2x2 = {};
  43644. for (name in this._matrices2x2) {
  43645. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  43646. }
  43647. // Vector3Array
  43648. serializationObject.vectors3Arrays = {};
  43649. for (name in this._vectors3Arrays) {
  43650. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  43651. }
  43652. return serializationObject;
  43653. };
  43654. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  43655. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  43656. var name;
  43657. // Texture
  43658. for (name in source.textures) {
  43659. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  43660. }
  43661. // Texture arrays
  43662. for (name in source.textureArrays) {
  43663. var array = source.textureArrays[name];
  43664. var textureArray = new Array();
  43665. for (var index = 0; index < array.length; index++) {
  43666. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  43667. }
  43668. material.setTextureArray(name, textureArray);
  43669. }
  43670. // Float
  43671. for (name in source.floats) {
  43672. material.setFloat(name, source.floats[name]);
  43673. }
  43674. // Float s
  43675. for (name in source.floatsArrays) {
  43676. material.setFloats(name, source.floatsArrays[name]);
  43677. }
  43678. // Color3
  43679. for (name in source.colors3) {
  43680. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  43681. }
  43682. // Color3 arrays
  43683. for (name in source.colors3Arrays) {
  43684. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  43685. if (i % 3 === 0) {
  43686. arr.push([num]);
  43687. }
  43688. else {
  43689. arr[arr.length - 1].push(num);
  43690. }
  43691. return arr;
  43692. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  43693. material.setColor3Array(name, colors);
  43694. }
  43695. // Color4
  43696. for (name in source.colors4) {
  43697. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  43698. }
  43699. // Vector2
  43700. for (name in source.vectors2) {
  43701. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  43702. }
  43703. // Vector3
  43704. for (name in source.vectors3) {
  43705. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  43706. }
  43707. // Vector4
  43708. for (name in source.vectors4) {
  43709. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  43710. }
  43711. // Matrix
  43712. for (name in source.matrices) {
  43713. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  43714. }
  43715. // Matrix 3x3
  43716. for (name in source.matrices3x3) {
  43717. material.setMatrix3x3(name, source.matrices3x3[name]);
  43718. }
  43719. // Matrix 2x2
  43720. for (name in source.matrices2x2) {
  43721. material.setMatrix2x2(name, source.matrices2x2[name]);
  43722. }
  43723. // Vector3Array
  43724. for (name in source.vectors3Arrays) {
  43725. material.setArray3(name, source.vectors3Arrays[name]);
  43726. }
  43727. return material;
  43728. };
  43729. return ShaderMaterial;
  43730. }(BABYLON.Material));
  43731. BABYLON.ShaderMaterial = ShaderMaterial;
  43732. })(BABYLON || (BABYLON = {}));
  43733. //# sourceMappingURL=babylon.shaderMaterial.js.map
  43734. var BABYLON;
  43735. (function (BABYLON) {
  43736. var MeshBuilder = (function () {
  43737. function MeshBuilder() {
  43738. }
  43739. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  43740. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  43741. return BABYLON.Mesh.DOUBLESIDE;
  43742. }
  43743. if (orientation === undefined || orientation === null) {
  43744. return BABYLON.Mesh.FRONTSIDE;
  43745. }
  43746. return orientation;
  43747. };
  43748. /**
  43749. * Creates a box mesh.
  43750. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  43751. * The parameter `size` sets the size (float) of each box side (default 1).
  43752. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  43753. * 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).
  43754. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  43755. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43756. * 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).
  43757. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43758. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43759. */
  43760. MeshBuilder.CreateBox = function (name, options, scene) {
  43761. var box = new BABYLON.Mesh(name, scene);
  43762. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43763. box.sideOrientation = options.sideOrientation;
  43764. var vertexData = BABYLON.VertexData.CreateBox(options);
  43765. vertexData.applyToMesh(box, options.updatable);
  43766. return box;
  43767. };
  43768. /**
  43769. * Creates a sphere mesh.
  43770. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  43771. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  43772. * 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`).
  43773. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  43774. * 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
  43775. * 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).
  43776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43777. * 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).
  43778. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43780. */
  43781. MeshBuilder.CreateSphere = function (name, options, scene) {
  43782. var sphere = new BABYLON.Mesh(name, scene);
  43783. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43784. sphere.sideOrientation = options.sideOrientation;
  43785. var vertexData = BABYLON.VertexData.CreateSphere(options);
  43786. vertexData.applyToMesh(sphere, options.updatable);
  43787. return sphere;
  43788. };
  43789. /**
  43790. * Creates a plane polygonal mesh. By default, this is a disc.
  43791. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  43792. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  43793. * 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.
  43794. * 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
  43795. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43796. * 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).
  43797. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43799. */
  43800. MeshBuilder.CreateDisc = function (name, options, scene) {
  43801. var disc = new BABYLON.Mesh(name, scene);
  43802. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43803. disc.sideOrientation = options.sideOrientation;
  43804. var vertexData = BABYLON.VertexData.CreateDisc(options);
  43805. vertexData.applyToMesh(disc, options.updatable);
  43806. return disc;
  43807. };
  43808. /**
  43809. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  43810. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  43811. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  43812. * 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`).
  43813. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  43814. * 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.
  43815. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43816. * 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).
  43817. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43819. */
  43820. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  43821. var sphere = new BABYLON.Mesh(name, scene);
  43822. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43823. sphere.sideOrientation = options.sideOrientation;
  43824. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  43825. vertexData.applyToMesh(sphere, options.updatable);
  43826. return sphere;
  43827. };
  43828. ;
  43829. /**
  43830. * Creates a ribbon mesh.
  43831. * 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.
  43832. *
  43833. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  43834. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  43835. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  43836. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  43837. * 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.
  43838. * 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.
  43839. * 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
  43840. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43841. * 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).
  43842. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43843. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43844. * 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.
  43845. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  43846. * 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
  43847. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  43848. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  43849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43850. */
  43851. MeshBuilder.CreateRibbon = function (name, options, scene) {
  43852. var pathArray = options.pathArray;
  43853. var closeArray = options.closeArray;
  43854. var closePath = options.closePath;
  43855. var offset = options.offset;
  43856. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43857. var instance = options.instance;
  43858. var updatable = options.updatable;
  43859. if (instance) {
  43860. // positionFunction : ribbon case
  43861. // only pathArray and sideOrientation parameters are taken into account for positions update
  43862. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  43863. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  43864. var positionFunction = function (positions) {
  43865. var minlg = pathArray[0].length;
  43866. var i = 0;
  43867. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  43868. for (var si = 1; si <= ns; si++) {
  43869. for (var p = 0; p < pathArray.length; p++) {
  43870. var path = pathArray[p];
  43871. var l = path.length;
  43872. minlg = (minlg < l) ? minlg : l;
  43873. var j = 0;
  43874. while (j < minlg) {
  43875. positions[i] = path[j].x;
  43876. positions[i + 1] = path[j].y;
  43877. positions[i + 2] = path[j].z;
  43878. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  43879. BABYLON.Tmp.Vector3[0].x = path[j].x;
  43880. }
  43881. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  43882. BABYLON.Tmp.Vector3[1].x = path[j].x;
  43883. }
  43884. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  43885. BABYLON.Tmp.Vector3[0].y = path[j].y;
  43886. }
  43887. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  43888. BABYLON.Tmp.Vector3[1].y = path[j].y;
  43889. }
  43890. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  43891. BABYLON.Tmp.Vector3[0].z = path[j].z;
  43892. }
  43893. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  43894. BABYLON.Tmp.Vector3[1].z = path[j].z;
  43895. }
  43896. j++;
  43897. i += 3;
  43898. }
  43899. if (instance._closePath) {
  43900. positions[i] = path[0].x;
  43901. positions[i + 1] = path[0].y;
  43902. positions[i + 2] = path[0].z;
  43903. i += 3;
  43904. }
  43905. }
  43906. }
  43907. };
  43908. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43909. positionFunction(positions);
  43910. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  43911. instance._boundingInfo.update(instance._worldMatrix);
  43912. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  43913. if (options.colors) {
  43914. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43915. for (var c = 0; c < options.colors.length; c++) {
  43916. colors[c * 4] = options.colors[c].r;
  43917. colors[c * 4 + 1] = options.colors[c].g;
  43918. colors[c * 4 + 2] = options.colors[c].b;
  43919. colors[c * 4 + 3] = options.colors[c].a;
  43920. }
  43921. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  43922. }
  43923. if (options.uvs) {
  43924. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43925. for (var i = 0; i < options.uvs.length; i++) {
  43926. uvs[i * 2] = options.uvs[i].x;
  43927. uvs[i * 2 + 1] = options.uvs[i].y;
  43928. }
  43929. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  43930. }
  43931. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  43932. var indices = instance.getIndices();
  43933. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43934. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  43935. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  43936. if (instance._closePath) {
  43937. var indexFirst = 0;
  43938. var indexLast = 0;
  43939. for (var p = 0; p < pathArray.length; p++) {
  43940. indexFirst = instance._idx[p] * 3;
  43941. if (p + 1 < pathArray.length) {
  43942. indexLast = (instance._idx[p + 1] - 1) * 3;
  43943. }
  43944. else {
  43945. indexLast = normals.length - 3;
  43946. }
  43947. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  43948. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  43949. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  43950. normals[indexLast] = normals[indexFirst];
  43951. normals[indexLast + 1] = normals[indexFirst + 1];
  43952. normals[indexLast + 2] = normals[indexFirst + 2];
  43953. }
  43954. }
  43955. if (!(instance.areNormalsFrozen)) {
  43956. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  43957. }
  43958. }
  43959. return instance;
  43960. }
  43961. else {
  43962. var ribbon = new BABYLON.Mesh(name, scene);
  43963. ribbon.sideOrientation = sideOrientation;
  43964. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  43965. if (closePath) {
  43966. ribbon._idx = vertexData._idx;
  43967. }
  43968. ribbon._closePath = closePath;
  43969. ribbon._closeArray = closeArray;
  43970. vertexData.applyToMesh(ribbon, updatable);
  43971. return ribbon;
  43972. }
  43973. };
  43974. /**
  43975. * Creates a cylinder or a cone mesh.
  43976. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  43977. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  43978. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  43979. * 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.
  43980. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  43981. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  43982. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  43983. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  43984. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  43985. * 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).
  43986. * 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
  43987. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  43988. * 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
  43989. * 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.
  43990. * If `enclose` is false, a ring surface is one element.
  43991. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  43992. * 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
  43993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43994. * 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).
  43995. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43997. */
  43998. MeshBuilder.CreateCylinder = function (name, options, scene) {
  43999. var cylinder = new BABYLON.Mesh(name, scene);
  44000. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44001. cylinder.sideOrientation = options.sideOrientation;
  44002. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  44003. vertexData.applyToMesh(cylinder, options.updatable);
  44004. return cylinder;
  44005. };
  44006. /**
  44007. * Creates a torus mesh.
  44008. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  44009. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  44010. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  44011. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  44012. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44013. * 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).
  44014. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44015. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44016. */
  44017. MeshBuilder.CreateTorus = function (name, options, scene) {
  44018. var torus = new BABYLON.Mesh(name, scene);
  44019. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44020. torus.sideOrientation = options.sideOrientation;
  44021. var vertexData = BABYLON.VertexData.CreateTorus(options);
  44022. vertexData.applyToMesh(torus, options.updatable);
  44023. return torus;
  44024. };
  44025. /**
  44026. * Creates a torus knot mesh.
  44027. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  44028. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  44029. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  44030. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  44031. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  44032. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44033. * 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).
  44034. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44035. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44036. */
  44037. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  44038. var torusKnot = new BABYLON.Mesh(name, scene);
  44039. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44040. torusKnot.sideOrientation = options.sideOrientation;
  44041. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  44042. vertexData.applyToMesh(torusKnot, options.updatable);
  44043. return torusKnot;
  44044. };
  44045. /**
  44046. * Creates a line system mesh.
  44047. * A line system is a pool of many lines gathered in a single mesh.
  44048. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  44049. * 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.
  44050. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  44051. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  44052. * 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
  44053. * 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
  44054. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  44055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44056. */
  44057. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  44058. var instance = options.instance;
  44059. var lines = options.lines;
  44060. if (instance) {
  44061. var positionFunction = function (positions) {
  44062. var i = 0;
  44063. for (var l = 0; l < lines.length; l++) {
  44064. var points = lines[l];
  44065. for (var p = 0; p < points.length; p++) {
  44066. positions[i] = points[p].x;
  44067. positions[i + 1] = points[p].y;
  44068. positions[i + 2] = points[p].z;
  44069. i += 3;
  44070. }
  44071. }
  44072. };
  44073. instance.updateMeshPositions(positionFunction, false);
  44074. return instance;
  44075. }
  44076. // line system creation
  44077. var lineSystem = new BABYLON.LinesMesh(name, scene);
  44078. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  44079. vertexData.applyToMesh(lineSystem, options.updatable);
  44080. return lineSystem;
  44081. };
  44082. /**
  44083. * Creates a line mesh.
  44084. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  44085. * 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.
  44086. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  44087. * The parameter `points` is an array successive Vector3.
  44088. * 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
  44089. * When updating an instance, remember that only point positions can change, not the number of points.
  44090. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44091. */
  44092. MeshBuilder.CreateLines = function (name, options, scene) {
  44093. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  44094. return lines;
  44095. };
  44096. /**
  44097. * Creates a dashed line mesh.
  44098. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  44099. * 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.
  44100. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  44101. * The parameter `points` is an array successive Vector3.
  44102. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  44103. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  44104. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  44105. * 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
  44106. * When updating an instance, remember that only point positions can change, not the number of points.
  44107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44108. */
  44109. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  44110. var points = options.points;
  44111. var instance = options.instance;
  44112. var gapSize = options.gapSize || 1;
  44113. var dashSize = options.dashSize || 3;
  44114. if (instance) {
  44115. var positionFunction = function (positions) {
  44116. var curvect = BABYLON.Vector3.Zero();
  44117. var nbSeg = positions.length / 6;
  44118. var lg = 0;
  44119. var nb = 0;
  44120. var shft = 0;
  44121. var dashshft = 0;
  44122. var curshft = 0;
  44123. var p = 0;
  44124. var i = 0;
  44125. var j = 0;
  44126. for (i = 0; i < points.length - 1; i++) {
  44127. points[i + 1].subtractToRef(points[i], curvect);
  44128. lg += curvect.length();
  44129. }
  44130. shft = lg / nbSeg;
  44131. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  44132. for (i = 0; i < points.length - 1; i++) {
  44133. points[i + 1].subtractToRef(points[i], curvect);
  44134. nb = Math.floor(curvect.length() / shft);
  44135. curvect.normalize();
  44136. j = 0;
  44137. while (j < nb && p < positions.length) {
  44138. curshft = shft * j;
  44139. positions[p] = points[i].x + curshft * curvect.x;
  44140. positions[p + 1] = points[i].y + curshft * curvect.y;
  44141. positions[p + 2] = points[i].z + curshft * curvect.z;
  44142. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  44143. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  44144. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  44145. p += 6;
  44146. j++;
  44147. }
  44148. }
  44149. while (p < positions.length) {
  44150. positions[p] = points[i].x;
  44151. positions[p + 1] = points[i].y;
  44152. positions[p + 2] = points[i].z;
  44153. p += 3;
  44154. }
  44155. };
  44156. instance.updateMeshPositions(positionFunction, false);
  44157. return instance;
  44158. }
  44159. // dashed lines creation
  44160. var dashedLines = new BABYLON.LinesMesh(name, scene);
  44161. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  44162. vertexData.applyToMesh(dashedLines, options.updatable);
  44163. dashedLines.dashSize = dashSize;
  44164. dashedLines.gapSize = gapSize;
  44165. return dashedLines;
  44166. };
  44167. /**
  44168. * Creates an extruded shape mesh.
  44169. * 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.
  44170. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  44171. *
  44172. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  44173. * 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
  44174. * extruded along the Z axis.
  44175. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  44176. * 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.
  44177. * The parameter `scale` (float, default 1) is the value to scale the shape.
  44178. * 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
  44179. * 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
  44180. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  44181. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44182. * 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).
  44183. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44184. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44185. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44186. */
  44187. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  44188. var path = options.path;
  44189. var shape = options.shape;
  44190. var scale = options.scale || 1;
  44191. var rotation = options.rotation || 0;
  44192. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  44193. var updatable = options.updatable;
  44194. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44195. var instance = options.instance;
  44196. var invertUV = options.invertUV || false;
  44197. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  44198. };
  44199. /**
  44200. * Creates an custom extruded shape mesh.
  44201. * 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.
  44202. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  44203. *
  44204. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  44205. * 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
  44206. * extruded along the Z axis.
  44207. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  44208. * 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
  44209. * and the distance of this point from the begining of the path :
  44210. * ```javascript
  44211. * var rotationFunction = function(i, distance) {
  44212. * // do things
  44213. * return rotationValue; }
  44214. * ```
  44215. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  44216. * 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
  44217. * and the distance of this point from the begining of the path :
  44218. * ```javascript
  44219. * var scaleFunction = function(i, distance) {
  44220. * // do things
  44221. * return scaleValue;}
  44222. * ```
  44223. * It must returns a float value that will be the scale value applied to the shape on each path point.
  44224. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  44225. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  44226. * 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
  44227. * 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
  44228. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  44229. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44230. * 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).
  44231. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44232. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44234. */
  44235. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  44236. var path = options.path;
  44237. var shape = options.shape;
  44238. var scaleFunction = options.scaleFunction || (function () { return 1; });
  44239. var rotationFunction = options.rotationFunction || (function () { return 0; });
  44240. var ribbonCloseArray = options.ribbonCloseArray || false;
  44241. var ribbonClosePath = options.ribbonClosePath || false;
  44242. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  44243. var updatable = options.updatable;
  44244. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44245. var instance = options.instance;
  44246. var invertUV = options.invertUV || false;
  44247. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  44248. };
  44249. /**
  44250. * Creates lathe mesh.
  44251. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  44252. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  44253. *
  44254. * 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
  44255. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  44256. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  44257. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  44258. * 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.
  44259. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  44260. * 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
  44261. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44262. * 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).
  44263. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44264. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44265. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44266. */
  44267. MeshBuilder.CreateLathe = function (name, options, scene) {
  44268. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  44269. var closed = (options.closed === undefined) ? true : options.closed;
  44270. var shape = options.shape;
  44271. var radius = options.radius || 1;
  44272. var tessellation = options.tessellation || 64;
  44273. var updatable = options.updatable;
  44274. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44275. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44276. var pi2 = Math.PI * 2;
  44277. var paths = new Array();
  44278. var invertUV = options.invertUV || false;
  44279. var i = 0;
  44280. var p = 0;
  44281. var step = pi2 / tessellation * arc;
  44282. var rotated;
  44283. var path = new Array();
  44284. ;
  44285. for (i = 0; i <= tessellation; i++) {
  44286. var path = [];
  44287. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  44288. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  44289. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  44290. }
  44291. for (p = 0; p < shape.length; p++) {
  44292. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  44293. path.push(rotated);
  44294. }
  44295. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  44296. 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));
  44297. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  44298. }
  44299. paths.push(path);
  44300. }
  44301. // lathe ribbon
  44302. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44303. return lathe;
  44304. };
  44305. /**
  44306. * Creates a plane mesh.
  44307. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  44308. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  44309. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  44310. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  44311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44312. * 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).
  44313. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44315. */
  44316. MeshBuilder.CreatePlane = function (name, options, scene) {
  44317. var plane = new BABYLON.Mesh(name, scene);
  44318. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44319. plane.sideOrientation = options.sideOrientation;
  44320. var vertexData = BABYLON.VertexData.CreatePlane(options);
  44321. vertexData.applyToMesh(plane, options.updatable);
  44322. if (options.sourcePlane) {
  44323. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  44324. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  44325. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  44326. plane.rotate(vectorProduct, product);
  44327. }
  44328. return plane;
  44329. };
  44330. /**
  44331. * Creates a ground mesh.
  44332. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  44333. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  44334. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  44335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44336. */
  44337. MeshBuilder.CreateGround = function (name, options, scene) {
  44338. var ground = new BABYLON.GroundMesh(name, scene);
  44339. ground._setReady(false);
  44340. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  44341. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  44342. ground._width = options.width || 1;
  44343. ground._height = options.height || 1;
  44344. ground._maxX = ground._width / 2;
  44345. ground._maxZ = ground._height / 2;
  44346. ground._minX = -ground._maxX;
  44347. ground._minZ = -ground._maxZ;
  44348. var vertexData = BABYLON.VertexData.CreateGround(options);
  44349. vertexData.applyToMesh(ground, options.updatable);
  44350. ground._setReady(true);
  44351. return ground;
  44352. };
  44353. /**
  44354. * Creates a tiled ground mesh.
  44355. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  44356. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  44357. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  44358. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  44359. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  44360. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  44361. * numbers of subdivisions on the ground width and height of each tile.
  44362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44363. */
  44364. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  44365. var tiledGround = new BABYLON.Mesh(name, scene);
  44366. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  44367. vertexData.applyToMesh(tiledGround, options.updatable);
  44368. return tiledGround;
  44369. };
  44370. /**
  44371. * Creates a ground mesh from a height map.
  44372. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  44373. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  44374. * The parameter `url` sets the URL of the height map image resource.
  44375. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  44376. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  44377. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  44378. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  44379. * 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.
  44380. * 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).
  44381. * This function is passed the newly built mesh :
  44382. * ```javascript
  44383. * function(mesh) { // do things
  44384. * return; }
  44385. * ```
  44386. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44387. */
  44388. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  44389. var width = options.width || 10.0;
  44390. var height = options.height || 10.0;
  44391. var subdivisions = options.subdivisions || 1 | 0;
  44392. var minHeight = options.minHeight || 0.0;
  44393. var maxHeight = options.maxHeight || 1.0;
  44394. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  44395. var updatable = options.updatable;
  44396. var onReady = options.onReady;
  44397. var ground = new BABYLON.GroundMesh(name, scene);
  44398. ground._subdivisionsX = subdivisions;
  44399. ground._subdivisionsY = subdivisions;
  44400. ground._width = width;
  44401. ground._height = height;
  44402. ground._maxX = ground._width / 2.0;
  44403. ground._maxZ = ground._height / 2.0;
  44404. ground._minX = -ground._maxX;
  44405. ground._minZ = -ground._maxZ;
  44406. ground._setReady(false);
  44407. var onload = function (img) {
  44408. // Getting height map data
  44409. var canvas = document.createElement("canvas");
  44410. var context = canvas.getContext("2d");
  44411. var bufferWidth = img.width;
  44412. var bufferHeight = img.height;
  44413. canvas.width = bufferWidth;
  44414. canvas.height = bufferHeight;
  44415. context.drawImage(img, 0, 0);
  44416. // Create VertexData from map data
  44417. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  44418. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  44419. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  44420. width: width, height: height,
  44421. subdivisions: subdivisions,
  44422. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  44423. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  44424. });
  44425. vertexData.applyToMesh(ground, updatable);
  44426. ground._setReady(true);
  44427. //execute ready callback, if set
  44428. if (onReady) {
  44429. onReady(ground);
  44430. }
  44431. };
  44432. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  44433. return ground;
  44434. };
  44435. /**
  44436. * Creates a polygon mesh.
  44437. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  44438. * 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.
  44439. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44440. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44441. * 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).
  44442. * Remember you can only change the shape positions, not their number when updating a polygon.
  44443. */
  44444. MeshBuilder.CreatePolygon = function (name, options, scene) {
  44445. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44446. var shape = options.shape;
  44447. var holes = options.holes || [];
  44448. var depth = options.depth || 0;
  44449. var contours = [];
  44450. var hole = [];
  44451. for (var i = 0; i < shape.length; i++) {
  44452. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  44453. }
  44454. var epsilon = 0.00000001;
  44455. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  44456. contours.pop();
  44457. }
  44458. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  44459. for (var hNb = 0; hNb < holes.length; hNb++) {
  44460. hole = [];
  44461. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  44462. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  44463. }
  44464. polygonTriangulation.addHole(hole);
  44465. }
  44466. var polygon = polygonTriangulation.build(options.updatable, depth);
  44467. polygon.sideOrientation = options.sideOrientation;
  44468. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  44469. vertexData.applyToMesh(polygon, options.updatable);
  44470. return polygon;
  44471. };
  44472. ;
  44473. /**
  44474. * Creates an extruded polygon mesh, with depth in the Y direction.
  44475. * 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).
  44476. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  44477. */
  44478. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  44479. return MeshBuilder.CreatePolygon(name, options, scene);
  44480. };
  44481. ;
  44482. /**
  44483. * Creates a tube mesh.
  44484. * 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.
  44485. *
  44486. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  44487. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  44488. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  44489. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  44490. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  44491. * 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.
  44492. * It must return a radius value (positive float) :
  44493. * ```javascript
  44494. * var radiusFunction = function(i, distance) {
  44495. * // do things
  44496. * return radius; }
  44497. * ```
  44498. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  44499. * 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
  44500. * 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
  44501. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44502. * 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).
  44503. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44504. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44506. */
  44507. MeshBuilder.CreateTube = function (name, options, scene) {
  44508. var path = options.path;
  44509. var radius = options.radius || 1.0;
  44510. var tessellation = options.tessellation || 64 | 0;
  44511. var radiusFunction = options.radiusFunction;
  44512. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44513. var invertUV = options.invertUV || false;
  44514. var updatable = options.updatable;
  44515. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44516. var instance = options.instance;
  44517. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  44518. // tube geometry
  44519. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  44520. var tangents = path3D.getTangents();
  44521. var normals = path3D.getNormals();
  44522. var distances = path3D.getDistances();
  44523. var pi2 = Math.PI * 2;
  44524. var step = pi2 / tessellation * arc;
  44525. var returnRadius = function () { return radius; };
  44526. var radiusFunctionFinal = radiusFunction || returnRadius;
  44527. var circlePath;
  44528. var rad;
  44529. var normal;
  44530. var rotated;
  44531. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44532. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44533. for (var i = 0; i < path.length; i++) {
  44534. rad = radiusFunctionFinal(i, distances[i]); // current radius
  44535. circlePath = Array(); // current circle array
  44536. normal = normals[i]; // current normal
  44537. for (var t = 0; t < tessellation; t++) {
  44538. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  44539. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  44540. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  44541. rotated.scaleInPlace(rad).addInPlace(path[i]);
  44542. circlePath[t] = rotated;
  44543. }
  44544. circlePaths[index] = circlePath;
  44545. index++;
  44546. }
  44547. // cap
  44548. var capPath = function (nbPoints, pathIndex) {
  44549. var pointCap = Array();
  44550. for (var i = 0; i < nbPoints; i++) {
  44551. pointCap.push(path[pathIndex]);
  44552. }
  44553. return pointCap;
  44554. };
  44555. switch (cap) {
  44556. case BABYLON.Mesh.NO_CAP:
  44557. break;
  44558. case BABYLON.Mesh.CAP_START:
  44559. circlePaths[0] = capPath(tessellation, 0);
  44560. circlePaths[1] = circlePaths[2].slice(0);
  44561. break;
  44562. case BABYLON.Mesh.CAP_END:
  44563. circlePaths[index] = circlePaths[index - 1].slice(0);
  44564. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44565. break;
  44566. case BABYLON.Mesh.CAP_ALL:
  44567. circlePaths[0] = capPath(tessellation, 0);
  44568. circlePaths[1] = circlePaths[2].slice(0);
  44569. circlePaths[index] = circlePaths[index - 1].slice(0);
  44570. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44571. break;
  44572. default:
  44573. break;
  44574. }
  44575. return circlePaths;
  44576. };
  44577. var path3D;
  44578. var pathArray;
  44579. if (instance) {
  44580. var arc = options.arc || instance.arc;
  44581. path3D = (instance.path3D).update(path);
  44582. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  44583. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  44584. instance.path3D = path3D;
  44585. instance.pathArray = pathArray;
  44586. instance.arc = arc;
  44587. return instance;
  44588. }
  44589. // tube creation
  44590. path3D = new BABYLON.Path3D(path);
  44591. var newPathArray = new Array();
  44592. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44593. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  44594. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44595. tube.pathArray = pathArray;
  44596. tube.path3D = path3D;
  44597. tube.tessellation = tessellation;
  44598. tube.cap = cap;
  44599. tube.arc = options.arc;
  44600. return tube;
  44601. };
  44602. /**
  44603. * Creates a polyhedron mesh.
  44604. *
  44605. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  44606. * 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
  44607. * to choose the wanted type.
  44608. * The parameter `size` (positive float, default 1) sets the polygon size.
  44609. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  44610. * 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`.
  44611. * 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
  44612. * 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)`).
  44613. * 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
  44614. * 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.
  44615. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44616. * 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).
  44617. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44618. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44619. */
  44620. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  44621. var polyhedron = new BABYLON.Mesh(name, scene);
  44622. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44623. polyhedron.sideOrientation = options.sideOrientation;
  44624. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  44625. vertexData.applyToMesh(polyhedron, options.updatable);
  44626. return polyhedron;
  44627. };
  44628. /**
  44629. * Creates a decal mesh.
  44630. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  44631. * 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.
  44632. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  44633. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  44634. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  44635. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  44636. */
  44637. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  44638. var indices = sourceMesh.getIndices();
  44639. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44640. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44641. var position = options.position || BABYLON.Vector3.Zero();
  44642. var normal = options.normal || BABYLON.Vector3.Up();
  44643. var size = options.size || BABYLON.Vector3.One();
  44644. var angle = options.angle || 0;
  44645. // Getting correct rotation
  44646. if (!normal) {
  44647. var target = new BABYLON.Vector3(0, 0, 1);
  44648. var camera = sourceMesh.getScene().activeCamera;
  44649. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  44650. normal = camera.globalPosition.subtract(cameraWorldTarget);
  44651. }
  44652. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  44653. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  44654. var pitch = Math.atan2(normal.y, len);
  44655. // Matrix
  44656. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  44657. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  44658. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  44659. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  44660. var vertexData = new BABYLON.VertexData();
  44661. vertexData.indices = [];
  44662. vertexData.positions = [];
  44663. vertexData.normals = [];
  44664. vertexData.uvs = [];
  44665. var currentVertexDataIndex = 0;
  44666. var extractDecalVector3 = function (indexId) {
  44667. var vertexId = indices[indexId];
  44668. var result = new BABYLON.PositionNormalVertex();
  44669. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  44670. // Send vector to decal local world
  44671. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  44672. // Get normal
  44673. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  44674. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  44675. return result;
  44676. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  44677. var clip = function (vertices, axis) {
  44678. if (vertices.length === 0) {
  44679. return vertices;
  44680. }
  44681. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  44682. var clipVertices = function (v0, v1) {
  44683. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  44684. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  44685. };
  44686. var result = new Array();
  44687. for (var index = 0; index < vertices.length; index += 3) {
  44688. var v1Out;
  44689. var v2Out;
  44690. var v3Out;
  44691. var total = 0;
  44692. var nV1, nV2, nV3, nV4;
  44693. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  44694. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  44695. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  44696. v1Out = d1 > 0;
  44697. v2Out = d2 > 0;
  44698. v3Out = d3 > 0;
  44699. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  44700. switch (total) {
  44701. case 0:
  44702. result.push(vertices[index]);
  44703. result.push(vertices[index + 1]);
  44704. result.push(vertices[index + 2]);
  44705. break;
  44706. case 1:
  44707. if (v1Out) {
  44708. nV1 = vertices[index + 1];
  44709. nV2 = vertices[index + 2];
  44710. nV3 = clipVertices(vertices[index], nV1);
  44711. nV4 = clipVertices(vertices[index], nV2);
  44712. }
  44713. if (v2Out) {
  44714. nV1 = vertices[index];
  44715. nV2 = vertices[index + 2];
  44716. nV3 = clipVertices(vertices[index + 1], nV1);
  44717. nV4 = clipVertices(vertices[index + 1], nV2);
  44718. result.push(nV3);
  44719. result.push(nV2.clone());
  44720. result.push(nV1.clone());
  44721. result.push(nV2.clone());
  44722. result.push(nV3.clone());
  44723. result.push(nV4);
  44724. break;
  44725. }
  44726. if (v3Out) {
  44727. nV1 = vertices[index];
  44728. nV2 = vertices[index + 1];
  44729. nV3 = clipVertices(vertices[index + 2], nV1);
  44730. nV4 = clipVertices(vertices[index + 2], nV2);
  44731. }
  44732. result.push(nV1.clone());
  44733. result.push(nV2.clone());
  44734. result.push(nV3);
  44735. result.push(nV4);
  44736. result.push(nV3.clone());
  44737. result.push(nV2.clone());
  44738. break;
  44739. case 2:
  44740. if (!v1Out) {
  44741. nV1 = vertices[index].clone();
  44742. nV2 = clipVertices(nV1, vertices[index + 1]);
  44743. nV3 = clipVertices(nV1, vertices[index + 2]);
  44744. result.push(nV1);
  44745. result.push(nV2);
  44746. result.push(nV3);
  44747. }
  44748. if (!v2Out) {
  44749. nV1 = vertices[index + 1].clone();
  44750. nV2 = clipVertices(nV1, vertices[index + 2]);
  44751. nV3 = clipVertices(nV1, vertices[index]);
  44752. result.push(nV1);
  44753. result.push(nV2);
  44754. result.push(nV3);
  44755. }
  44756. if (!v3Out) {
  44757. nV1 = vertices[index + 2].clone();
  44758. nV2 = clipVertices(nV1, vertices[index]);
  44759. nV3 = clipVertices(nV1, vertices[index + 1]);
  44760. result.push(nV1);
  44761. result.push(nV2);
  44762. result.push(nV3);
  44763. }
  44764. break;
  44765. case 3:
  44766. break;
  44767. }
  44768. }
  44769. return result;
  44770. };
  44771. for (var index = 0; index < indices.length; index += 3) {
  44772. var faceVertices = new Array();
  44773. faceVertices.push(extractDecalVector3(index));
  44774. faceVertices.push(extractDecalVector3(index + 1));
  44775. faceVertices.push(extractDecalVector3(index + 2));
  44776. // Clip
  44777. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  44778. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  44779. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  44780. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  44781. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  44782. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  44783. if (faceVertices.length === 0) {
  44784. continue;
  44785. }
  44786. // Add UVs and get back to world
  44787. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  44788. var vertex = faceVertices[vIndex];
  44789. //TODO check for Int32Array | Uint32Array | Uint16Array
  44790. vertexData.indices.push(currentVertexDataIndex);
  44791. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  44792. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  44793. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  44794. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  44795. currentVertexDataIndex++;
  44796. }
  44797. }
  44798. // Return mesh
  44799. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  44800. vertexData.applyToMesh(decal);
  44801. decal.position = position.clone();
  44802. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  44803. return decal;
  44804. };
  44805. // Privates
  44806. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  44807. // extrusion geometry
  44808. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  44809. var tangents = path3D.getTangents();
  44810. var normals = path3D.getNormals();
  44811. var binormals = path3D.getBinormals();
  44812. var distances = path3D.getDistances();
  44813. var angle = 0;
  44814. var returnScale = function () { return scale; };
  44815. var returnRotation = function () { return rotation; };
  44816. var rotate = custom ? rotateFunction : returnRotation;
  44817. var scl = custom ? scaleFunction : returnScale;
  44818. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44819. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44820. for (var i = 0; i < curve.length; i++) {
  44821. var shapePath = new Array();
  44822. var angleStep = rotate(i, distances[i]);
  44823. var scaleRatio = scl(i, distances[i]);
  44824. for (var p = 0; p < shape.length; p++) {
  44825. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  44826. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  44827. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  44828. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  44829. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  44830. shapePath[p] = rotated;
  44831. }
  44832. shapePaths[index] = shapePath;
  44833. angle += angleStep;
  44834. index++;
  44835. }
  44836. // cap
  44837. var capPath = function (shapePath) {
  44838. var pointCap = Array();
  44839. var barycenter = BABYLON.Vector3.Zero();
  44840. var i;
  44841. for (i = 0; i < shapePath.length; i++) {
  44842. barycenter.addInPlace(shapePath[i]);
  44843. }
  44844. barycenter.scaleInPlace(1.0 / shapePath.length);
  44845. for (i = 0; i < shapePath.length; i++) {
  44846. pointCap.push(barycenter);
  44847. }
  44848. return pointCap;
  44849. };
  44850. switch (cap) {
  44851. case BABYLON.Mesh.NO_CAP:
  44852. break;
  44853. case BABYLON.Mesh.CAP_START:
  44854. shapePaths[0] = capPath(shapePaths[2]);
  44855. shapePaths[1] = shapePaths[2];
  44856. break;
  44857. case BABYLON.Mesh.CAP_END:
  44858. shapePaths[index] = shapePaths[index - 1];
  44859. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44860. break;
  44861. case BABYLON.Mesh.CAP_ALL:
  44862. shapePaths[0] = capPath(shapePaths[2]);
  44863. shapePaths[1] = shapePaths[2];
  44864. shapePaths[index] = shapePaths[index - 1];
  44865. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44866. break;
  44867. default:
  44868. break;
  44869. }
  44870. return shapePaths;
  44871. };
  44872. var path3D;
  44873. var pathArray;
  44874. if (instance) {
  44875. path3D = (instance.path3D).update(curve);
  44876. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  44877. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  44878. return instance;
  44879. }
  44880. // extruded shape creation
  44881. path3D = new BABYLON.Path3D(curve);
  44882. var newShapePaths = new Array();
  44883. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44884. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  44885. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  44886. extrudedGeneric.pathArray = pathArray;
  44887. extrudedGeneric.path3D = path3D;
  44888. extrudedGeneric.cap = cap;
  44889. return extrudedGeneric;
  44890. };
  44891. return MeshBuilder;
  44892. }());
  44893. BABYLON.MeshBuilder = MeshBuilder;
  44894. })(BABYLON || (BABYLON = {}));
  44895. //# sourceMappingURL=babylon.meshBuilder.js.map
  44896. var BABYLON;
  44897. (function (BABYLON) {
  44898. var AudioEngine = (function () {
  44899. function AudioEngine() {
  44900. this._audioContext = null;
  44901. this._audioContextInitialized = false;
  44902. this.canUseWebAudio = false;
  44903. this.WarnedWebAudioUnsupported = false;
  44904. this.unlocked = false;
  44905. this.isMP3supported = false;
  44906. this.isOGGsupported = false;
  44907. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  44908. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  44909. this.canUseWebAudio = true;
  44910. }
  44911. var audioElem = document.createElement('audio');
  44912. try {
  44913. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  44914. this.isMP3supported = true;
  44915. }
  44916. }
  44917. catch (e) {
  44918. // protect error during capability check.
  44919. }
  44920. try {
  44921. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  44922. this.isOGGsupported = true;
  44923. }
  44924. }
  44925. catch (e) {
  44926. // protect error during capability check.
  44927. }
  44928. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  44929. this._unlockiOSaudio();
  44930. }
  44931. else {
  44932. this.unlocked = true;
  44933. }
  44934. }
  44935. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  44936. get: function () {
  44937. if (!this._audioContextInitialized) {
  44938. this._initializeAudioContext();
  44939. }
  44940. return this._audioContext;
  44941. },
  44942. enumerable: true,
  44943. configurable: true
  44944. });
  44945. AudioEngine.prototype._unlockiOSaudio = function () {
  44946. var _this = this;
  44947. var unlockaudio = function () {
  44948. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  44949. var source = _this.audioContext.createBufferSource();
  44950. source.buffer = buffer;
  44951. source.connect(_this.audioContext.destination);
  44952. source.start(0);
  44953. setTimeout(function () {
  44954. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  44955. _this.unlocked = true;
  44956. window.removeEventListener('touchend', unlockaudio, false);
  44957. if (_this.onAudioUnlocked) {
  44958. _this.onAudioUnlocked();
  44959. }
  44960. }
  44961. }, 0);
  44962. };
  44963. window.addEventListener('touchend', unlockaudio, false);
  44964. };
  44965. AudioEngine.prototype._initializeAudioContext = function () {
  44966. try {
  44967. if (this.canUseWebAudio) {
  44968. this._audioContext = new AudioContext();
  44969. // create a global volume gain node
  44970. this.masterGain = this._audioContext.createGain();
  44971. this.masterGain.gain.value = 1;
  44972. this.masterGain.connect(this._audioContext.destination);
  44973. this._audioContextInitialized = true;
  44974. }
  44975. }
  44976. catch (e) {
  44977. this.canUseWebAudio = false;
  44978. BABYLON.Tools.Error("Web Audio: " + e.message);
  44979. }
  44980. };
  44981. AudioEngine.prototype.dispose = function () {
  44982. if (this.canUseWebAudio && this._audioContextInitialized) {
  44983. if (this._connectedAnalyser) {
  44984. this._connectedAnalyser.stopDebugCanvas();
  44985. this._connectedAnalyser.dispose();
  44986. this.masterGain.disconnect();
  44987. this.masterGain.connect(this._audioContext.destination);
  44988. this._connectedAnalyser = null;
  44989. }
  44990. this.masterGain.gain.value = 1;
  44991. }
  44992. this.WarnedWebAudioUnsupported = false;
  44993. };
  44994. AudioEngine.prototype.getGlobalVolume = function () {
  44995. if (this.canUseWebAudio && this._audioContextInitialized) {
  44996. return this.masterGain.gain.value;
  44997. }
  44998. else {
  44999. return -1;
  45000. }
  45001. };
  45002. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  45003. if (this.canUseWebAudio && this._audioContextInitialized) {
  45004. this.masterGain.gain.value = newVolume;
  45005. }
  45006. };
  45007. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  45008. if (this._connectedAnalyser) {
  45009. this._connectedAnalyser.stopDebugCanvas();
  45010. }
  45011. if (this.canUseWebAudio && this._audioContextInitialized) {
  45012. this._connectedAnalyser = analyser;
  45013. this.masterGain.disconnect();
  45014. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  45015. }
  45016. };
  45017. return AudioEngine;
  45018. }());
  45019. BABYLON.AudioEngine = AudioEngine;
  45020. })(BABYLON || (BABYLON = {}));
  45021. //# sourceMappingURL=babylon.audioEngine.js.map
  45022. var BABYLON;
  45023. (function (BABYLON) {
  45024. var Sound = (function () {
  45025. /**
  45026. * Create a sound and attach it to a scene
  45027. * @param name Name of your sound
  45028. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  45029. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  45030. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  45031. */
  45032. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  45033. var _this = this;
  45034. this.autoplay = false;
  45035. this.loop = false;
  45036. this.useCustomAttenuation = false;
  45037. this.spatialSound = false;
  45038. this.refDistance = 1;
  45039. this.rolloffFactor = 1;
  45040. this.maxDistance = 100;
  45041. this.distanceModel = "linear";
  45042. this._panningModel = "equalpower";
  45043. this._playbackRate = 1;
  45044. this._streaming = false;
  45045. this._startTime = 0;
  45046. this._startOffset = 0;
  45047. this._position = BABYLON.Vector3.Zero();
  45048. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  45049. this._volume = 1;
  45050. this._isLoaded = false;
  45051. this._isReadyToPlay = false;
  45052. this.isPlaying = false;
  45053. this.isPaused = false;
  45054. this._isDirectional = false;
  45055. // Used if you'd like to create a directional sound.
  45056. // If not set, the sound will be omnidirectional
  45057. this._coneInnerAngle = 360;
  45058. this._coneOuterAngle = 360;
  45059. this._coneOuterGain = 0;
  45060. this._isOutputConnected = false;
  45061. this._urlType = "Unknown";
  45062. this.name = name;
  45063. this._scene = scene;
  45064. this._readyToPlayCallback = readyToPlayCallback;
  45065. // Default custom attenuation function is a linear attenuation
  45066. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  45067. if (currentDistance < maxDistance) {
  45068. return currentVolume * (1 - currentDistance / maxDistance);
  45069. }
  45070. else {
  45071. return 0;
  45072. }
  45073. };
  45074. if (options) {
  45075. this.autoplay = options.autoplay || false;
  45076. this.loop = options.loop || false;
  45077. // if volume === 0, we need another way to check this option
  45078. if (options.volume !== undefined) {
  45079. this._volume = options.volume;
  45080. }
  45081. this.spatialSound = options.spatialSound || false;
  45082. this.maxDistance = options.maxDistance || 100;
  45083. this.useCustomAttenuation = options.useCustomAttenuation || false;
  45084. this.rolloffFactor = options.rolloffFactor || 1;
  45085. this.refDistance = options.refDistance || 1;
  45086. this.distanceModel = options.distanceModel || "linear";
  45087. this._playbackRate = options.playbackRate || 1;
  45088. this._streaming = options.streaming || false;
  45089. }
  45090. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45091. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  45092. this._soundGain.gain.value = this._volume;
  45093. this._inputAudioNode = this._soundGain;
  45094. this._ouputAudioNode = this._soundGain;
  45095. if (this.spatialSound) {
  45096. this._createSpatialParameters();
  45097. }
  45098. this._scene.mainSoundTrack.AddSound(this);
  45099. var validParameter = true;
  45100. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  45101. if (urlOrArrayBuffer) {
  45102. if (typeof (urlOrArrayBuffer) === "string")
  45103. this._urlType = "String";
  45104. if (Array.isArray(urlOrArrayBuffer))
  45105. this._urlType = "Array";
  45106. if (urlOrArrayBuffer instanceof ArrayBuffer)
  45107. this._urlType = "ArrayBuffer";
  45108. var urls = [];
  45109. var codecSupportedFound = false;
  45110. switch (this._urlType) {
  45111. case "ArrayBuffer":
  45112. if (urlOrArrayBuffer.byteLength > 0) {
  45113. codecSupportedFound = true;
  45114. this._soundLoaded(urlOrArrayBuffer);
  45115. }
  45116. break;
  45117. case "String":
  45118. urls.push(urlOrArrayBuffer);
  45119. case "Array":
  45120. if (urls.length === 0)
  45121. urls = urlOrArrayBuffer;
  45122. // If we found a supported format, we load it immediately and stop the loop
  45123. for (var i = 0; i < urls.length; i++) {
  45124. var url = urls[i];
  45125. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  45126. codecSupportedFound = true;
  45127. }
  45128. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  45129. codecSupportedFound = true;
  45130. }
  45131. if (url.indexOf(".wav", url.length - 4) !== -1) {
  45132. codecSupportedFound = true;
  45133. }
  45134. if (url.indexOf("blob:") !== -1) {
  45135. codecSupportedFound = true;
  45136. }
  45137. if (codecSupportedFound) {
  45138. // Loading sound using XHR2
  45139. if (!this._streaming) {
  45140. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  45141. }
  45142. else {
  45143. this._htmlAudioElement = new Audio(url);
  45144. this._htmlAudioElement.controls = false;
  45145. this._htmlAudioElement.loop = this.loop;
  45146. this._htmlAudioElement.crossOrigin = "anonymous";
  45147. this._htmlAudioElement.preload = "auto";
  45148. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  45149. _this._isReadyToPlay = true;
  45150. if (_this.autoplay) {
  45151. _this.play();
  45152. }
  45153. if (_this._readyToPlayCallback) {
  45154. _this._readyToPlayCallback();
  45155. }
  45156. });
  45157. document.body.appendChild(this._htmlAudioElement);
  45158. }
  45159. break;
  45160. }
  45161. }
  45162. break;
  45163. default:
  45164. validParameter = false;
  45165. break;
  45166. }
  45167. if (!validParameter) {
  45168. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  45169. }
  45170. else {
  45171. if (!codecSupportedFound) {
  45172. this._isReadyToPlay = true;
  45173. // Simulating a ready to play event to avoid breaking code path
  45174. if (this._readyToPlayCallback) {
  45175. window.setTimeout(function () {
  45176. _this._readyToPlayCallback();
  45177. }, 1000);
  45178. }
  45179. }
  45180. }
  45181. }
  45182. }
  45183. else {
  45184. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  45185. this._scene.mainSoundTrack.AddSound(this);
  45186. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  45187. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  45188. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  45189. }
  45190. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  45191. if (this._readyToPlayCallback) {
  45192. window.setTimeout(function () {
  45193. _this._readyToPlayCallback();
  45194. }, 1000);
  45195. }
  45196. }
  45197. }
  45198. Sound.prototype.dispose = function () {
  45199. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  45200. if (this.isPlaying) {
  45201. this.stop();
  45202. }
  45203. this._isReadyToPlay = false;
  45204. if (this.soundTrackId === -1) {
  45205. this._scene.mainSoundTrack.RemoveSound(this);
  45206. }
  45207. else {
  45208. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  45209. }
  45210. if (this._soundGain) {
  45211. this._soundGain.disconnect();
  45212. this._soundGain = null;
  45213. }
  45214. if (this._soundPanner) {
  45215. this._soundPanner.disconnect();
  45216. this._soundPanner = null;
  45217. }
  45218. if (this._soundSource) {
  45219. this._soundSource.disconnect();
  45220. this._soundSource = null;
  45221. }
  45222. this._audioBuffer = null;
  45223. if (this._htmlAudioElement) {
  45224. this._htmlAudioElement.pause();
  45225. this._htmlAudioElement.src = "";
  45226. document.body.removeChild(this._htmlAudioElement);
  45227. }
  45228. if (this._connectedMesh) {
  45229. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45230. this._connectedMesh = null;
  45231. }
  45232. }
  45233. };
  45234. Sound.prototype.isReady = function () {
  45235. return this._isReadyToPlay;
  45236. };
  45237. Sound.prototype._soundLoaded = function (audioData) {
  45238. var _this = this;
  45239. this._isLoaded = true;
  45240. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  45241. _this._audioBuffer = buffer;
  45242. _this._isReadyToPlay = true;
  45243. if (_this.autoplay) {
  45244. _this.play();
  45245. }
  45246. if (_this._readyToPlayCallback) {
  45247. _this._readyToPlayCallback();
  45248. }
  45249. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  45250. };
  45251. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  45252. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45253. this._audioBuffer = audioBuffer;
  45254. this._isReadyToPlay = true;
  45255. }
  45256. };
  45257. Sound.prototype.updateOptions = function (options) {
  45258. if (options) {
  45259. this.loop = options.loop || this.loop;
  45260. this.maxDistance = options.maxDistance || this.maxDistance;
  45261. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  45262. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  45263. this.refDistance = options.refDistance || this.refDistance;
  45264. this.distanceModel = options.distanceModel || this.distanceModel;
  45265. this._playbackRate = options.playbackRate || this._playbackRate;
  45266. this._updateSpatialParameters();
  45267. if (this.isPlaying) {
  45268. if (this._streaming) {
  45269. this._htmlAudioElement.playbackRate = this._playbackRate;
  45270. }
  45271. else {
  45272. this._soundSource.playbackRate.value = this._playbackRate;
  45273. }
  45274. }
  45275. }
  45276. };
  45277. Sound.prototype._createSpatialParameters = function () {
  45278. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45279. if (this._scene.headphone) {
  45280. this._panningModel = "HRTF";
  45281. }
  45282. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  45283. this._updateSpatialParameters();
  45284. this._soundPanner.connect(this._ouputAudioNode);
  45285. this._inputAudioNode = this._soundPanner;
  45286. }
  45287. };
  45288. Sound.prototype._updateSpatialParameters = function () {
  45289. if (this.spatialSound) {
  45290. if (this.useCustomAttenuation) {
  45291. // Tricks to disable in a way embedded Web Audio attenuation
  45292. this._soundPanner.distanceModel = "linear";
  45293. this._soundPanner.maxDistance = Number.MAX_VALUE;
  45294. this._soundPanner.refDistance = 1;
  45295. this._soundPanner.rolloffFactor = 1;
  45296. this._soundPanner.panningModel = this._panningModel;
  45297. }
  45298. else {
  45299. this._soundPanner.distanceModel = this.distanceModel;
  45300. this._soundPanner.maxDistance = this.maxDistance;
  45301. this._soundPanner.refDistance = this.refDistance;
  45302. this._soundPanner.rolloffFactor = this.rolloffFactor;
  45303. this._soundPanner.panningModel = this._panningModel;
  45304. }
  45305. }
  45306. };
  45307. Sound.prototype.switchPanningModelToHRTF = function () {
  45308. this._panningModel = "HRTF";
  45309. this._switchPanningModel();
  45310. };
  45311. Sound.prototype.switchPanningModelToEqualPower = function () {
  45312. this._panningModel = "equalpower";
  45313. this._switchPanningModel();
  45314. };
  45315. Sound.prototype._switchPanningModel = function () {
  45316. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  45317. this._soundPanner.panningModel = this._panningModel;
  45318. }
  45319. };
  45320. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  45321. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45322. if (this._isOutputConnected) {
  45323. this._ouputAudioNode.disconnect();
  45324. }
  45325. this._ouputAudioNode.connect(soundTrackAudioNode);
  45326. this._isOutputConnected = true;
  45327. }
  45328. };
  45329. /**
  45330. * Transform this sound into a directional source
  45331. * @param coneInnerAngle Size of the inner cone in degree
  45332. * @param coneOuterAngle Size of the outer cone in degree
  45333. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  45334. */
  45335. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  45336. if (coneOuterAngle < coneInnerAngle) {
  45337. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  45338. return;
  45339. }
  45340. this._coneInnerAngle = coneInnerAngle;
  45341. this._coneOuterAngle = coneOuterAngle;
  45342. this._coneOuterGain = coneOuterGain;
  45343. this._isDirectional = true;
  45344. if (this.isPlaying && this.loop) {
  45345. this.stop();
  45346. this.play();
  45347. }
  45348. };
  45349. Sound.prototype.setPosition = function (newPosition) {
  45350. this._position = newPosition;
  45351. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  45352. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  45353. }
  45354. };
  45355. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  45356. this._localDirection = newLocalDirection;
  45357. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  45358. this._updateDirection();
  45359. }
  45360. };
  45361. Sound.prototype._updateDirection = function () {
  45362. var mat = this._connectedMesh.getWorldMatrix();
  45363. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  45364. direction.normalize();
  45365. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  45366. };
  45367. Sound.prototype.updateDistanceFromListener = function () {
  45368. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  45369. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  45370. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  45371. }
  45372. };
  45373. Sound.prototype.setAttenuationFunction = function (callback) {
  45374. this._customAttenuationFunction = callback;
  45375. };
  45376. /**
  45377. * Play the sound
  45378. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  45379. * @param offset (optional) Start the sound setting it at a specific time
  45380. */
  45381. Sound.prototype.play = function (time, offset) {
  45382. var _this = this;
  45383. if (this._isReadyToPlay && this._scene.audioEnabled) {
  45384. try {
  45385. if (this._startOffset < 0) {
  45386. time = -this._startOffset;
  45387. this._startOffset = 0;
  45388. }
  45389. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45390. if (!this._soundSource || !this._streamingSource) {
  45391. if (this.spatialSound) {
  45392. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  45393. if (this._isDirectional) {
  45394. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  45395. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  45396. this._soundPanner.coneOuterGain = this._coneOuterGain;
  45397. if (this._connectedMesh) {
  45398. this._updateDirection();
  45399. }
  45400. else {
  45401. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  45402. }
  45403. }
  45404. }
  45405. }
  45406. if (this._streaming) {
  45407. if (!this._streamingSource) {
  45408. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  45409. this._htmlAudioElement.onended = function () { _this._onended(); };
  45410. this._htmlAudioElement.playbackRate = this._playbackRate;
  45411. }
  45412. this._streamingSource.disconnect();
  45413. this._streamingSource.connect(this._inputAudioNode);
  45414. this._htmlAudioElement.play();
  45415. }
  45416. else {
  45417. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  45418. this._soundSource.buffer = this._audioBuffer;
  45419. this._soundSource.connect(this._inputAudioNode);
  45420. this._soundSource.loop = this.loop;
  45421. this._soundSource.playbackRate.value = this._playbackRate;
  45422. this._soundSource.onended = function () { _this._onended(); };
  45423. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  45424. }
  45425. this._startTime = startTime;
  45426. this.isPlaying = true;
  45427. this.isPaused = false;
  45428. }
  45429. catch (ex) {
  45430. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  45431. }
  45432. }
  45433. };
  45434. Sound.prototype._onended = function () {
  45435. this.isPlaying = false;
  45436. if (this.onended) {
  45437. this.onended();
  45438. }
  45439. };
  45440. /**
  45441. * Stop the sound
  45442. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  45443. */
  45444. Sound.prototype.stop = function (time) {
  45445. if (this.isPlaying) {
  45446. if (this._streaming) {
  45447. this._htmlAudioElement.pause();
  45448. // Test needed for Firefox or it will generate an Invalid State Error
  45449. if (this._htmlAudioElement.currentTime > 0) {
  45450. this._htmlAudioElement.currentTime = 0;
  45451. }
  45452. }
  45453. else {
  45454. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45455. this._soundSource.stop(stopTime);
  45456. this._soundSource.onended = null;
  45457. if (!this.isPaused) {
  45458. this._startOffset = 0;
  45459. }
  45460. }
  45461. this.isPlaying = false;
  45462. }
  45463. };
  45464. Sound.prototype.pause = function () {
  45465. if (this.isPlaying) {
  45466. this.isPaused = true;
  45467. if (this._streaming) {
  45468. this._htmlAudioElement.pause();
  45469. }
  45470. else {
  45471. this.stop(0);
  45472. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  45473. }
  45474. }
  45475. };
  45476. Sound.prototype.setVolume = function (newVolume, time) {
  45477. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45478. if (time) {
  45479. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  45480. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  45481. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  45482. }
  45483. else {
  45484. this._soundGain.gain.value = newVolume;
  45485. }
  45486. }
  45487. this._volume = newVolume;
  45488. };
  45489. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  45490. this._playbackRate = newPlaybackRate;
  45491. if (this.isPlaying) {
  45492. if (this._streaming) {
  45493. this._htmlAudioElement.playbackRate = this._playbackRate;
  45494. }
  45495. else {
  45496. this._soundSource.playbackRate.value = this._playbackRate;
  45497. }
  45498. }
  45499. };
  45500. Sound.prototype.getVolume = function () {
  45501. return this._volume;
  45502. };
  45503. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  45504. var _this = this;
  45505. if (this._connectedMesh) {
  45506. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45507. this._registerFunc = null;
  45508. }
  45509. this._connectedMesh = meshToConnectTo;
  45510. if (!this.spatialSound) {
  45511. this.spatialSound = true;
  45512. this._createSpatialParameters();
  45513. if (this.isPlaying && this.loop) {
  45514. this.stop();
  45515. this.play();
  45516. }
  45517. }
  45518. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  45519. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  45520. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  45521. };
  45522. Sound.prototype.detachFromMesh = function () {
  45523. if (this._connectedMesh) {
  45524. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45525. this._registerFunc = null;
  45526. this._connectedMesh = null;
  45527. }
  45528. };
  45529. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  45530. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  45531. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  45532. this._updateDirection();
  45533. }
  45534. };
  45535. Sound.prototype.clone = function () {
  45536. var _this = this;
  45537. if (!this._streaming) {
  45538. var setBufferAndRun = function () {
  45539. if (_this._isReadyToPlay) {
  45540. clonedSound._audioBuffer = _this.getAudioBuffer();
  45541. clonedSound._isReadyToPlay = true;
  45542. if (clonedSound.autoplay) {
  45543. clonedSound.play();
  45544. }
  45545. }
  45546. else {
  45547. window.setTimeout(setBufferAndRun, 300);
  45548. }
  45549. };
  45550. var currentOptions = {
  45551. autoplay: this.autoplay, loop: this.loop,
  45552. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  45553. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  45554. refDistance: this.refDistance, distanceModel: this.distanceModel
  45555. };
  45556. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  45557. if (this.useCustomAttenuation) {
  45558. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  45559. }
  45560. clonedSound.setPosition(this._position);
  45561. clonedSound.setPlaybackRate(this._playbackRate);
  45562. setBufferAndRun();
  45563. return clonedSound;
  45564. }
  45565. else {
  45566. return null;
  45567. }
  45568. };
  45569. Sound.prototype.getAudioBuffer = function () {
  45570. return this._audioBuffer;
  45571. };
  45572. Sound.prototype.serialize = function () {
  45573. var serializationObject = {
  45574. name: this.name,
  45575. url: this.name,
  45576. autoplay: this.autoplay,
  45577. loop: this.loop,
  45578. volume: this._volume,
  45579. spatialSound: this.spatialSound,
  45580. maxDistance: this.maxDistance,
  45581. rolloffFactor: this.rolloffFactor,
  45582. refDistance: this.refDistance,
  45583. distanceModel: this.distanceModel,
  45584. playbackRate: this._playbackRate,
  45585. panningModel: this._panningModel,
  45586. soundTrackId: this.soundTrackId
  45587. };
  45588. if (this.spatialSound) {
  45589. if (this._connectedMesh)
  45590. serializationObject.connectedMeshId = this._connectedMesh.id;
  45591. serializationObject.position = this._position.asArray();
  45592. serializationObject.refDistance = this.refDistance;
  45593. serializationObject.distanceModel = this.distanceModel;
  45594. serializationObject.isDirectional = this._isDirectional;
  45595. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  45596. serializationObject.coneInnerAngle = this._coneInnerAngle;
  45597. serializationObject.coneOuterAngle = this._coneOuterAngle;
  45598. serializationObject.coneOuterGain = this._coneOuterGain;
  45599. }
  45600. return serializationObject;
  45601. };
  45602. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  45603. var soundName = parsedSound.name;
  45604. var soundUrl;
  45605. if (parsedSound.url) {
  45606. soundUrl = rootUrl + parsedSound.url;
  45607. }
  45608. else {
  45609. soundUrl = rootUrl + soundName;
  45610. }
  45611. var options = {
  45612. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  45613. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  45614. rolloffFactor: parsedSound.rolloffFactor,
  45615. refDistance: parsedSound.refDistance,
  45616. distanceModel: parsedSound.distanceModel,
  45617. playbackRate: parsedSound.playbackRate
  45618. };
  45619. var newSound;
  45620. if (!sourceSound) {
  45621. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  45622. scene._addPendingData(newSound);
  45623. }
  45624. else {
  45625. var setBufferAndRun = function () {
  45626. if (sourceSound._isReadyToPlay) {
  45627. newSound._audioBuffer = sourceSound.getAudioBuffer();
  45628. newSound._isReadyToPlay = true;
  45629. if (newSound.autoplay) {
  45630. newSound.play();
  45631. }
  45632. }
  45633. else {
  45634. window.setTimeout(setBufferAndRun, 300);
  45635. }
  45636. };
  45637. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  45638. setBufferAndRun();
  45639. }
  45640. if (parsedSound.position) {
  45641. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  45642. newSound.setPosition(soundPosition);
  45643. }
  45644. if (parsedSound.isDirectional) {
  45645. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  45646. if (parsedSound.localDirectionToMesh) {
  45647. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  45648. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  45649. }
  45650. }
  45651. if (parsedSound.connectedMeshId) {
  45652. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  45653. if (connectedMesh) {
  45654. newSound.attachToMesh(connectedMesh);
  45655. }
  45656. }
  45657. return newSound;
  45658. };
  45659. return Sound;
  45660. }());
  45661. BABYLON.Sound = Sound;
  45662. })(BABYLON || (BABYLON = {}));
  45663. //# sourceMappingURL=babylon.sound.js.map
  45664. var BABYLON;
  45665. (function (BABYLON) {
  45666. var SoundTrack = (function () {
  45667. function SoundTrack(scene, options) {
  45668. this.id = -1;
  45669. this._isMainTrack = false;
  45670. this._isInitialized = false;
  45671. this._scene = scene;
  45672. this.soundCollection = new Array();
  45673. this._options = options;
  45674. if (!this._isMainTrack) {
  45675. this._scene.soundTracks.push(this);
  45676. this.id = this._scene.soundTracks.length - 1;
  45677. }
  45678. }
  45679. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  45680. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45681. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  45682. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  45683. if (this._options) {
  45684. if (this._options.volume) {
  45685. this._outputAudioNode.gain.value = this._options.volume;
  45686. }
  45687. if (this._options.mainTrack) {
  45688. this._isMainTrack = this._options.mainTrack;
  45689. }
  45690. }
  45691. this._isInitialized = true;
  45692. }
  45693. };
  45694. SoundTrack.prototype.dispose = function () {
  45695. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45696. if (this._connectedAnalyser) {
  45697. this._connectedAnalyser.stopDebugCanvas();
  45698. }
  45699. while (this.soundCollection.length) {
  45700. this.soundCollection[0].dispose();
  45701. }
  45702. if (this._outputAudioNode) {
  45703. this._outputAudioNode.disconnect();
  45704. }
  45705. this._outputAudioNode = null;
  45706. }
  45707. };
  45708. SoundTrack.prototype.AddSound = function (sound) {
  45709. if (!this._isInitialized) {
  45710. this._initializeSoundTrackAudioGraph();
  45711. }
  45712. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45713. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  45714. }
  45715. if (sound.soundTrackId) {
  45716. if (sound.soundTrackId === -1) {
  45717. this._scene.mainSoundTrack.RemoveSound(sound);
  45718. }
  45719. else {
  45720. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  45721. }
  45722. }
  45723. this.soundCollection.push(sound);
  45724. sound.soundTrackId = this.id;
  45725. };
  45726. SoundTrack.prototype.RemoveSound = function (sound) {
  45727. var index = this.soundCollection.indexOf(sound);
  45728. if (index !== -1) {
  45729. this.soundCollection.splice(index, 1);
  45730. }
  45731. };
  45732. SoundTrack.prototype.setVolume = function (newVolume) {
  45733. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45734. this._outputAudioNode.gain.value = newVolume;
  45735. }
  45736. };
  45737. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  45738. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45739. for (var i = 0; i < this.soundCollection.length; i++) {
  45740. this.soundCollection[i].switchPanningModelToHRTF();
  45741. }
  45742. }
  45743. };
  45744. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  45745. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45746. for (var i = 0; i < this.soundCollection.length; i++) {
  45747. this.soundCollection[i].switchPanningModelToEqualPower();
  45748. }
  45749. }
  45750. };
  45751. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  45752. if (this._connectedAnalyser) {
  45753. this._connectedAnalyser.stopDebugCanvas();
  45754. }
  45755. this._connectedAnalyser = analyser;
  45756. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45757. this._outputAudioNode.disconnect();
  45758. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  45759. }
  45760. };
  45761. return SoundTrack;
  45762. }());
  45763. BABYLON.SoundTrack = SoundTrack;
  45764. })(BABYLON || (BABYLON = {}));
  45765. //# sourceMappingURL=babylon.soundtrack.js.map
  45766. var BABYLON;
  45767. (function (BABYLON) {
  45768. var Analyser = (function () {
  45769. function Analyser(scene) {
  45770. this.SMOOTHING = 0.75;
  45771. this.FFT_SIZE = 512;
  45772. this.BARGRAPHAMPLITUDE = 256;
  45773. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45774. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45775. this._scene = scene;
  45776. this._audioEngine = BABYLON.Engine.audioEngine;
  45777. if (this._audioEngine.canUseWebAudio) {
  45778. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45779. this._webAudioAnalyser.minDecibels = -140;
  45780. this._webAudioAnalyser.maxDecibels = 0;
  45781. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45782. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45783. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45784. }
  45785. }
  45786. Analyser.prototype.getFrequencyBinCount = function () {
  45787. if (this._audioEngine.canUseWebAudio) {
  45788. return this._webAudioAnalyser.frequencyBinCount;
  45789. }
  45790. else {
  45791. return 0;
  45792. }
  45793. };
  45794. Analyser.prototype.getByteFrequencyData = function () {
  45795. if (this._audioEngine.canUseWebAudio) {
  45796. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45797. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45798. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45799. }
  45800. return this._byteFreqs;
  45801. };
  45802. Analyser.prototype.getByteTimeDomainData = function () {
  45803. if (this._audioEngine.canUseWebAudio) {
  45804. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45805. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45806. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45807. }
  45808. return this._byteTime;
  45809. };
  45810. Analyser.prototype.getFloatFrequencyData = function () {
  45811. if (this._audioEngine.canUseWebAudio) {
  45812. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45813. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45814. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  45815. }
  45816. return this._floatFreqs;
  45817. };
  45818. Analyser.prototype.drawDebugCanvas = function () {
  45819. var _this = this;
  45820. if (this._audioEngine.canUseWebAudio) {
  45821. if (!this._debugCanvas) {
  45822. this._debugCanvas = document.createElement("canvas");
  45823. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  45824. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  45825. this._debugCanvas.style.position = "absolute";
  45826. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  45827. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  45828. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  45829. document.body.appendChild(this._debugCanvas);
  45830. this._registerFunc = function () {
  45831. _this.drawDebugCanvas();
  45832. };
  45833. this._scene.registerBeforeRender(this._registerFunc);
  45834. }
  45835. if (this._registerFunc) {
  45836. var workingArray = this.getByteFrequencyData();
  45837. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  45838. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  45839. // Draw the frequency domain chart.
  45840. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  45841. var value = workingArray[i];
  45842. var percent = value / this.BARGRAPHAMPLITUDE;
  45843. var height = this.DEBUGCANVASSIZE.height * percent;
  45844. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  45845. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  45846. var hue = i / this.getFrequencyBinCount() * 360;
  45847. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  45848. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  45849. }
  45850. }
  45851. }
  45852. };
  45853. Analyser.prototype.stopDebugCanvas = function () {
  45854. if (this._debugCanvas) {
  45855. this._scene.unregisterBeforeRender(this._registerFunc);
  45856. this._registerFunc = null;
  45857. document.body.removeChild(this._debugCanvas);
  45858. this._debugCanvas = null;
  45859. this._debugCanvasContext = null;
  45860. }
  45861. };
  45862. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45863. if (this._audioEngine.canUseWebAudio) {
  45864. inputAudioNode.connect(this._webAudioAnalyser);
  45865. this._webAudioAnalyser.connect(outputAudioNode);
  45866. }
  45867. };
  45868. Analyser.prototype.dispose = function () {
  45869. if (this._audioEngine.canUseWebAudio) {
  45870. this._webAudioAnalyser.disconnect();
  45871. }
  45872. };
  45873. return Analyser;
  45874. }());
  45875. BABYLON.Analyser = Analyser;
  45876. })(BABYLON || (BABYLON = {}));
  45877. //# sourceMappingURL=babylon.analyser.js.map
  45878. var BABYLON;
  45879. (function (BABYLON) {
  45880. var CubeTexture = (function (_super) {
  45881. __extends(CubeTexture, _super);
  45882. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  45883. if (onLoad === void 0) { onLoad = null; }
  45884. if (onError === void 0) { onError = null; }
  45885. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45886. if (prefiltered === void 0) { prefiltered = false; }
  45887. if (forcedExtension === void 0) { forcedExtension = null; }
  45888. var _this = _super.call(this, scene) || this;
  45889. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  45890. _this.name = rootUrl;
  45891. _this.url = rootUrl;
  45892. _this._noMipmap = noMipmap;
  45893. _this.hasAlpha = false;
  45894. _this._format = format;
  45895. _this._prefiltered = prefiltered;
  45896. _this.isCube = true;
  45897. _this._textureMatrix = BABYLON.Matrix.Identity();
  45898. if (prefiltered) {
  45899. _this.gammaSpace = false;
  45900. }
  45901. if (!rootUrl && !files) {
  45902. return _this;
  45903. }
  45904. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  45905. if (!files) {
  45906. if (!extensions) {
  45907. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  45908. }
  45909. files = [];
  45910. for (var index = 0; index < extensions.length; index++) {
  45911. files.push(rootUrl + extensions[index]);
  45912. }
  45913. _this._extensions = extensions;
  45914. }
  45915. _this._files = files;
  45916. if (!_this._texture) {
  45917. if (!scene.useDelayedTextureLoading) {
  45918. if (prefiltered) {
  45919. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  45920. }
  45921. else {
  45922. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  45923. }
  45924. }
  45925. else {
  45926. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  45927. }
  45928. }
  45929. else if (onLoad) {
  45930. if (_this._texture.isReady) {
  45931. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  45932. }
  45933. else {
  45934. _this._texture.onLoadedObservable.add(onLoad);
  45935. }
  45936. }
  45937. return _this;
  45938. }
  45939. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  45940. return new CubeTexture("", scene, null, noMipmap, files);
  45941. };
  45942. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  45943. if (forcedExtension === void 0) { forcedExtension = null; }
  45944. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  45945. };
  45946. // Methods
  45947. CubeTexture.prototype.delayLoad = function () {
  45948. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  45949. return;
  45950. }
  45951. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  45952. this._texture = this._getFromCache(this.url, this._noMipmap);
  45953. if (!this._texture) {
  45954. if (this._prefiltered) {
  45955. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  45956. }
  45957. else {
  45958. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  45959. }
  45960. }
  45961. };
  45962. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  45963. return this._textureMatrix;
  45964. };
  45965. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  45966. this._textureMatrix = value;
  45967. };
  45968. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  45969. var texture = BABYLON.SerializationHelper.Parse(function () {
  45970. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  45971. }, parsedTexture, scene);
  45972. // Animations
  45973. if (parsedTexture.animations) {
  45974. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  45975. var parsedAnimation = parsedTexture.animations[animationIndex];
  45976. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45977. }
  45978. }
  45979. return texture;
  45980. };
  45981. CubeTexture.prototype.clone = function () {
  45982. var _this = this;
  45983. return BABYLON.SerializationHelper.Clone(function () {
  45984. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  45985. }, this);
  45986. };
  45987. return CubeTexture;
  45988. }(BABYLON.BaseTexture));
  45989. BABYLON.CubeTexture = CubeTexture;
  45990. })(BABYLON || (BABYLON = {}));
  45991. //# sourceMappingURL=babylon.cubeTexture.js.map
  45992. var BABYLON;
  45993. (function (BABYLON) {
  45994. var RenderTargetTexture = (function (_super) {
  45995. __extends(RenderTargetTexture, _super);
  45996. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  45997. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  45998. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45999. if (isCube === void 0) { isCube = false; }
  46000. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46001. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  46002. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  46003. if (isMulti === void 0) { isMulti = false; }
  46004. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  46005. _this.isCube = isCube;
  46006. /**
  46007. * Use this list to define the list of mesh you want to render.
  46008. */
  46009. _this.renderList = new Array();
  46010. _this.renderParticles = true;
  46011. _this.renderSprites = false;
  46012. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  46013. _this.ignoreCameraViewport = false;
  46014. // Events
  46015. /**
  46016. * An event triggered when the texture is unbind.
  46017. * @type {BABYLON.Observable}
  46018. */
  46019. _this.onBeforeBindObservable = new BABYLON.Observable();
  46020. /**
  46021. * An event triggered when the texture is unbind.
  46022. * @type {BABYLON.Observable}
  46023. */
  46024. _this.onAfterUnbindObservable = new BABYLON.Observable();
  46025. /**
  46026. * An event triggered before rendering the texture
  46027. * @type {BABYLON.Observable}
  46028. */
  46029. _this.onBeforeRenderObservable = new BABYLON.Observable();
  46030. /**
  46031. * An event triggered after rendering the texture
  46032. * @type {BABYLON.Observable}
  46033. */
  46034. _this.onAfterRenderObservable = new BABYLON.Observable();
  46035. /**
  46036. * An event triggered after the texture clear
  46037. * @type {BABYLON.Observable}
  46038. */
  46039. _this.onClearObservable = new BABYLON.Observable();
  46040. _this._currentRefreshId = -1;
  46041. _this._refreshRate = 1;
  46042. _this._samples = 1;
  46043. scene = _this.getScene();
  46044. _this.name = name;
  46045. _this.isRenderTarget = true;
  46046. _this._size = size;
  46047. _this._generateMipMaps = generateMipMaps;
  46048. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  46049. // Rendering groups
  46050. _this._renderingManager = new BABYLON.RenderingManager(scene);
  46051. if (isMulti) {
  46052. return _this;
  46053. }
  46054. _this._renderTargetOptions = {
  46055. generateMipMaps: generateMipMaps,
  46056. type: type,
  46057. samplingMode: samplingMode,
  46058. generateDepthBuffer: generateDepthBuffer,
  46059. generateStencilBuffer: generateStencilBuffer
  46060. };
  46061. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  46062. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46063. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46064. }
  46065. if (isCube) {
  46066. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  46067. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  46068. _this._textureMatrix = BABYLON.Matrix.Identity();
  46069. }
  46070. else {
  46071. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  46072. }
  46073. return _this;
  46074. }
  46075. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  46076. get: function () {
  46077. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  46078. },
  46079. enumerable: true,
  46080. configurable: true
  46081. });
  46082. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  46083. get: function () {
  46084. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  46085. },
  46086. enumerable: true,
  46087. configurable: true
  46088. });
  46089. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  46090. get: function () {
  46091. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  46092. },
  46093. enumerable: true,
  46094. configurable: true
  46095. });
  46096. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  46097. set: function (callback) {
  46098. if (this._onAfterUnbindObserver) {
  46099. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  46100. }
  46101. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  46102. },
  46103. enumerable: true,
  46104. configurable: true
  46105. });
  46106. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  46107. set: function (callback) {
  46108. if (this._onBeforeRenderObserver) {
  46109. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  46110. }
  46111. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  46112. },
  46113. enumerable: true,
  46114. configurable: true
  46115. });
  46116. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  46117. set: function (callback) {
  46118. if (this._onAfterRenderObserver) {
  46119. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  46120. }
  46121. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  46122. },
  46123. enumerable: true,
  46124. configurable: true
  46125. });
  46126. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  46127. set: function (callback) {
  46128. if (this._onClearObserver) {
  46129. this.onClearObservable.remove(this._onClearObserver);
  46130. }
  46131. this._onClearObserver = this.onClearObservable.add(callback);
  46132. },
  46133. enumerable: true,
  46134. configurable: true
  46135. });
  46136. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  46137. get: function () {
  46138. return this._renderTargetOptions;
  46139. },
  46140. enumerable: true,
  46141. configurable: true
  46142. });
  46143. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  46144. get: function () {
  46145. return this._samples;
  46146. },
  46147. set: function (value) {
  46148. if (this._samples === value) {
  46149. return;
  46150. }
  46151. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  46152. },
  46153. enumerable: true,
  46154. configurable: true
  46155. });
  46156. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  46157. this._currentRefreshId = -1;
  46158. };
  46159. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  46160. get: function () {
  46161. return this._refreshRate;
  46162. },
  46163. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  46164. set: function (value) {
  46165. this._refreshRate = value;
  46166. this.resetRefreshCounter();
  46167. },
  46168. enumerable: true,
  46169. configurable: true
  46170. });
  46171. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  46172. if (!this._postProcessManager) {
  46173. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  46174. this._postProcesses = new Array();
  46175. }
  46176. this._postProcesses.push(postProcess);
  46177. this._postProcesses[0].autoClear = false;
  46178. };
  46179. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  46180. if (!this._postProcesses) {
  46181. return;
  46182. }
  46183. if (dispose) {
  46184. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  46185. var postProcess = _a[_i];
  46186. postProcess.dispose();
  46187. postProcess = null;
  46188. }
  46189. }
  46190. this._postProcesses = [];
  46191. };
  46192. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  46193. if (!this._postProcesses) {
  46194. return;
  46195. }
  46196. var index = this._postProcesses.indexOf(postProcess);
  46197. if (index === -1) {
  46198. return;
  46199. }
  46200. this._postProcesses.splice(index, 1);
  46201. if (this._postProcesses.length > 0) {
  46202. this._postProcesses[0].autoClear = false;
  46203. }
  46204. };
  46205. RenderTargetTexture.prototype._shouldRender = function () {
  46206. if (this._currentRefreshId === -1) {
  46207. this._currentRefreshId = 1;
  46208. return true;
  46209. }
  46210. if (this.refreshRate === this._currentRefreshId) {
  46211. this._currentRefreshId = 1;
  46212. return true;
  46213. }
  46214. this._currentRefreshId++;
  46215. return false;
  46216. };
  46217. RenderTargetTexture.prototype.getRenderSize = function () {
  46218. return this._size;
  46219. };
  46220. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  46221. get: function () {
  46222. return true;
  46223. },
  46224. enumerable: true,
  46225. configurable: true
  46226. });
  46227. RenderTargetTexture.prototype.scale = function (ratio) {
  46228. var newSize = this._size * ratio;
  46229. this.resize(newSize);
  46230. };
  46231. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  46232. if (this.isCube) {
  46233. return this._textureMatrix;
  46234. }
  46235. return _super.prototype.getReflectionTextureMatrix.call(this);
  46236. };
  46237. RenderTargetTexture.prototype.resize = function (size) {
  46238. this.releaseInternalTexture();
  46239. if (this.isCube) {
  46240. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  46241. }
  46242. else {
  46243. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  46244. }
  46245. };
  46246. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  46247. var scene = this.getScene();
  46248. var engine = scene.getEngine();
  46249. if (this.useCameraPostProcesses !== undefined) {
  46250. useCameraPostProcess = this.useCameraPostProcesses;
  46251. }
  46252. if (this._waitingRenderList) {
  46253. this.renderList = [];
  46254. for (var index = 0; index < this._waitingRenderList.length; index++) {
  46255. var id = this._waitingRenderList[index];
  46256. this.renderList.push(scene.getMeshByID(id));
  46257. }
  46258. delete this._waitingRenderList;
  46259. }
  46260. // Is predicate defined?
  46261. if (this.renderListPredicate) {
  46262. this.renderList.splice(0); // Clear previous renderList
  46263. var sceneMeshes = this.getScene().meshes;
  46264. for (var index = 0; index < sceneMeshes.length; index++) {
  46265. var mesh = sceneMeshes[index];
  46266. if (this.renderListPredicate(mesh)) {
  46267. this.renderList.push(mesh);
  46268. }
  46269. }
  46270. }
  46271. if (this.renderList && this.renderList.length === 0) {
  46272. return;
  46273. }
  46274. this.onBeforeBindObservable.notifyObservers(this);
  46275. // Set custom projection.
  46276. // Needs to be before binding to prevent changing the aspect ratio.
  46277. var camera;
  46278. if (this.activeCamera) {
  46279. camera = this.activeCamera;
  46280. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  46281. if (this.activeCamera !== scene.activeCamera) {
  46282. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  46283. }
  46284. }
  46285. else {
  46286. camera = scene.activeCamera;
  46287. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  46288. }
  46289. // Prepare renderingManager
  46290. this._renderingManager.reset();
  46291. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  46292. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  46293. var sceneRenderId = scene.getRenderId();
  46294. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  46295. var mesh = currentRenderList[meshIndex];
  46296. if (mesh) {
  46297. if (!mesh.isReady()) {
  46298. // Reset _currentRefreshId
  46299. this.resetRefreshCounter();
  46300. continue;
  46301. }
  46302. mesh._preActivateForIntermediateRendering(sceneRenderId);
  46303. var isMasked = void 0;
  46304. if (!this.renderList) {
  46305. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  46306. }
  46307. else {
  46308. isMasked = false;
  46309. }
  46310. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  46311. mesh._activate(sceneRenderId);
  46312. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  46313. var subMesh = mesh.subMeshes[subIndex];
  46314. scene._activeIndices.addCount(subMesh.indexCount, false);
  46315. this._renderingManager.dispatch(subMesh);
  46316. }
  46317. }
  46318. }
  46319. }
  46320. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  46321. var particleSystem = scene.particleSystems[particleIndex];
  46322. var emitter = particleSystem.emitter;
  46323. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  46324. continue;
  46325. }
  46326. if (currentRenderList.indexOf(emitter) >= 0) {
  46327. this._renderingManager.dispatchParticles(particleSystem);
  46328. }
  46329. }
  46330. if (this.isCube) {
  46331. for (var face = 0; face < 6; face++) {
  46332. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  46333. scene.incrementRenderId();
  46334. scene.resetCachedMaterial();
  46335. }
  46336. }
  46337. else {
  46338. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  46339. }
  46340. this.onAfterUnbindObservable.notifyObservers(this);
  46341. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  46342. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  46343. }
  46344. engine.setViewport(scene.activeCamera.viewport);
  46345. scene.resetCachedMaterial();
  46346. };
  46347. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  46348. var _this = this;
  46349. var scene = this.getScene();
  46350. var engine = scene.getEngine();
  46351. // Bind
  46352. if (this._postProcessManager) {
  46353. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  46354. }
  46355. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  46356. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  46357. }
  46358. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  46359. // Clear
  46360. if (this.onClearObservable.hasObservers()) {
  46361. this.onClearObservable.notifyObservers(engine);
  46362. }
  46363. else {
  46364. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  46365. }
  46366. if (!this._doNotChangeAspectRatio) {
  46367. scene.updateTransformMatrix(true);
  46368. }
  46369. // Render
  46370. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  46371. if (this._postProcessManager) {
  46372. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  46373. }
  46374. else if (useCameraPostProcess) {
  46375. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  46376. }
  46377. if (!this._doNotChangeAspectRatio) {
  46378. scene.updateTransformMatrix(true);
  46379. }
  46380. // Dump ?
  46381. if (dumpForDebug) {
  46382. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  46383. }
  46384. // Unbind
  46385. if (!this.isCube || faceIndex === 5) {
  46386. if (this.isCube) {
  46387. if (faceIndex === 5) {
  46388. engine.generateMipMapsForCubemap(this._texture);
  46389. }
  46390. }
  46391. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  46392. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  46393. });
  46394. }
  46395. else {
  46396. this.onAfterRenderObservable.notifyObservers(faceIndex);
  46397. }
  46398. };
  46399. /**
  46400. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  46401. * This allowed control for front to back rendering or reversly depending of the special needs.
  46402. *
  46403. * @param renderingGroupId The rendering group id corresponding to its index
  46404. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  46405. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  46406. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  46407. */
  46408. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  46409. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  46410. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  46411. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  46412. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  46413. };
  46414. /**
  46415. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  46416. *
  46417. * @param renderingGroupId The rendering group id corresponding to its index
  46418. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  46419. */
  46420. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  46421. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  46422. };
  46423. RenderTargetTexture.prototype.clone = function () {
  46424. var textureSize = this.getSize();
  46425. 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);
  46426. // Base texture
  46427. newTexture.hasAlpha = this.hasAlpha;
  46428. newTexture.level = this.level;
  46429. // RenderTarget Texture
  46430. newTexture.coordinatesMode = this.coordinatesMode;
  46431. newTexture.renderList = this.renderList.slice(0);
  46432. return newTexture;
  46433. };
  46434. RenderTargetTexture.prototype.serialize = function () {
  46435. if (!this.name) {
  46436. return null;
  46437. }
  46438. var serializationObject = _super.prototype.serialize.call(this);
  46439. serializationObject.renderTargetSize = this.getRenderSize();
  46440. serializationObject.renderList = [];
  46441. for (var index = 0; index < this.renderList.length; index++) {
  46442. serializationObject.renderList.push(this.renderList[index].id);
  46443. }
  46444. return serializationObject;
  46445. };
  46446. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  46447. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  46448. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  46449. };
  46450. RenderTargetTexture.prototype.dispose = function () {
  46451. if (this._postProcessManager) {
  46452. this._postProcessManager.dispose();
  46453. this._postProcessManager = null;
  46454. }
  46455. this.clearPostProcesses(true);
  46456. this.renderList = null;
  46457. // Remove from custom render targets
  46458. var scene = this.getScene();
  46459. var index = scene.customRenderTargets.indexOf(this);
  46460. if (index >= 0) {
  46461. scene.customRenderTargets.splice(index, 1);
  46462. }
  46463. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  46464. var camera = _a[_i];
  46465. index = camera.customRenderTargets.indexOf(this);
  46466. if (index >= 0) {
  46467. camera.customRenderTargets.splice(index, 1);
  46468. }
  46469. }
  46470. _super.prototype.dispose.call(this);
  46471. };
  46472. RenderTargetTexture.prototype._rebuild = function () {
  46473. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  46474. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  46475. }
  46476. if (this._postProcessManager) {
  46477. this._postProcessManager._rebuild();
  46478. }
  46479. };
  46480. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  46481. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  46482. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  46483. return RenderTargetTexture;
  46484. }(BABYLON.Texture));
  46485. BABYLON.RenderTargetTexture = RenderTargetTexture;
  46486. })(BABYLON || (BABYLON = {}));
  46487. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  46488. var BABYLON;
  46489. (function (BABYLON) {
  46490. ;
  46491. var MultiRenderTarget = (function (_super) {
  46492. __extends(MultiRenderTarget, _super);
  46493. function MultiRenderTarget(name, size, count, scene, options) {
  46494. var _this = this;
  46495. options = options || {};
  46496. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  46497. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  46498. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  46499. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  46500. if (!_this.isSupported) {
  46501. _this.dispose();
  46502. return;
  46503. }
  46504. var types = [];
  46505. var samplingModes = [];
  46506. for (var i = 0; i < count; i++) {
  46507. if (options.types && options.types[i]) {
  46508. types.push(options.types[i]);
  46509. }
  46510. else {
  46511. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  46512. }
  46513. if (options.samplingModes && options.samplingModes[i]) {
  46514. samplingModes.push(options.samplingModes[i]);
  46515. }
  46516. else {
  46517. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46518. }
  46519. }
  46520. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  46521. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  46522. _this._count = count;
  46523. _this._size = size;
  46524. _this._multiRenderTargetOptions = {
  46525. samplingModes: samplingModes,
  46526. generateMipMaps: generateMipMaps,
  46527. generateDepthBuffer: generateDepthBuffer,
  46528. generateStencilBuffer: generateStencilBuffer,
  46529. generateDepthTexture: generateDepthTexture,
  46530. types: types,
  46531. textureCount: count
  46532. };
  46533. _this._createInternalTextures();
  46534. _this._createTextures();
  46535. return _this;
  46536. }
  46537. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  46538. get: function () {
  46539. var engine = this.getScene().getEngine();
  46540. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  46541. },
  46542. enumerable: true,
  46543. configurable: true
  46544. });
  46545. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  46546. get: function () {
  46547. return this._textures;
  46548. },
  46549. enumerable: true,
  46550. configurable: true
  46551. });
  46552. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  46553. get: function () {
  46554. return this._textures[this._textures.length - 1];
  46555. },
  46556. enumerable: true,
  46557. configurable: true
  46558. });
  46559. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  46560. set: function (wrap) {
  46561. if (this._textures) {
  46562. for (var i = 0; i < this._textures.length; i++) {
  46563. this._textures[i].wrapU = wrap;
  46564. }
  46565. }
  46566. },
  46567. enumerable: true,
  46568. configurable: true
  46569. });
  46570. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  46571. set: function (wrap) {
  46572. if (this._textures) {
  46573. for (var i = 0; i < this._textures.length; i++) {
  46574. this._textures[i].wrapV = wrap;
  46575. }
  46576. }
  46577. },
  46578. enumerable: true,
  46579. configurable: true
  46580. });
  46581. MultiRenderTarget.prototype._rebuild = function () {
  46582. this.releaseInternalTextures();
  46583. this._createInternalTextures();
  46584. for (var i = 0; i < this._internalTextures.length; i++) {
  46585. var texture = this._textures[i];
  46586. texture._texture = this._internalTextures[i];
  46587. }
  46588. // Keeps references to frame buffer and stencil/depth buffer
  46589. this._texture = this._internalTextures[0];
  46590. };
  46591. MultiRenderTarget.prototype._createInternalTextures = function () {
  46592. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  46593. };
  46594. MultiRenderTarget.prototype._createTextures = function () {
  46595. this._textures = [];
  46596. for (var i = 0; i < this._internalTextures.length; i++) {
  46597. var texture = new BABYLON.Texture(null, this.getScene());
  46598. texture._texture = this._internalTextures[i];
  46599. this._textures.push(texture);
  46600. }
  46601. // Keeps references to frame buffer and stencil/depth buffer
  46602. this._texture = this._internalTextures[0];
  46603. };
  46604. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  46605. get: function () {
  46606. return this._samples;
  46607. },
  46608. set: function (value) {
  46609. if (this._samples === value) {
  46610. return;
  46611. }
  46612. for (var i = 0; i < this._internalTextures.length; i++) {
  46613. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  46614. }
  46615. },
  46616. enumerable: true,
  46617. configurable: true
  46618. });
  46619. MultiRenderTarget.prototype.resize = function (size) {
  46620. this.releaseInternalTextures();
  46621. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  46622. this._createInternalTextures();
  46623. };
  46624. MultiRenderTarget.prototype.dispose = function () {
  46625. this.releaseInternalTextures();
  46626. _super.prototype.dispose.call(this);
  46627. };
  46628. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  46629. if (!this._internalTextures) {
  46630. return;
  46631. }
  46632. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  46633. if (this._internalTextures[i] !== undefined) {
  46634. this._internalTextures[i].dispose();
  46635. this._internalTextures.splice(i, 1);
  46636. }
  46637. }
  46638. };
  46639. return MultiRenderTarget;
  46640. }(BABYLON.RenderTargetTexture));
  46641. BABYLON.MultiRenderTarget = MultiRenderTarget;
  46642. })(BABYLON || (BABYLON = {}));
  46643. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  46644. /// <reference path="babylon.renderTargetTexture.ts" />
  46645. var BABYLON;
  46646. (function (BABYLON) {
  46647. var MirrorTexture = (function (_super) {
  46648. __extends(MirrorTexture, _super);
  46649. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  46650. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46651. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46652. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  46653. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  46654. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  46655. _this._transformMatrix = BABYLON.Matrix.Zero();
  46656. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  46657. _this._blurKernelX = 0;
  46658. _this._blurKernelY = 0;
  46659. _this._blurRatio = 1.0;
  46660. _this.ignoreCameraViewport = true;
  46661. _this.onBeforeRenderObservable.add(function () {
  46662. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  46663. _this._savedViewMatrix = scene.getViewMatrix();
  46664. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  46665. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  46666. scene.clipPlane = _this.mirrorPlane;
  46667. scene.getEngine().cullBackFaces = false;
  46668. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  46669. });
  46670. _this.onAfterRenderObservable.add(function () {
  46671. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  46672. scene.getEngine().cullBackFaces = true;
  46673. scene._mirroredCameraPosition = null;
  46674. delete scene.clipPlane;
  46675. });
  46676. return _this;
  46677. }
  46678. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  46679. get: function () {
  46680. return this._blurRatio;
  46681. },
  46682. set: function (value) {
  46683. if (this._blurRatio === value) {
  46684. return;
  46685. }
  46686. this._blurRatio = value;
  46687. this._preparePostProcesses();
  46688. },
  46689. enumerable: true,
  46690. configurable: true
  46691. });
  46692. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  46693. set: function (value) {
  46694. this.blurKernelX = value;
  46695. this.blurKernelY = value;
  46696. },
  46697. enumerable: true,
  46698. configurable: true
  46699. });
  46700. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  46701. get: function () {
  46702. return this._blurKernelX;
  46703. },
  46704. set: function (value) {
  46705. if (this._blurKernelX === value) {
  46706. return;
  46707. }
  46708. this._blurKernelX = value;
  46709. this._preparePostProcesses();
  46710. },
  46711. enumerable: true,
  46712. configurable: true
  46713. });
  46714. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  46715. get: function () {
  46716. return this._blurKernelY;
  46717. },
  46718. set: function (value) {
  46719. if (this._blurKernelY === value) {
  46720. return;
  46721. }
  46722. this._blurKernelY = value;
  46723. this._preparePostProcesses();
  46724. },
  46725. enumerable: true,
  46726. configurable: true
  46727. });
  46728. MirrorTexture.prototype._preparePostProcesses = function () {
  46729. this.clearPostProcesses(true);
  46730. if (this._blurKernelX && this._blurKernelY) {
  46731. var engine = this.getScene().getEngine();
  46732. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46733. 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);
  46734. this._blurX.autoClear = false;
  46735. if (this._blurRatio === 1 && this.samples < 2) {
  46736. this._blurX.outputTexture = this._texture;
  46737. }
  46738. else {
  46739. this._blurX.alwaysForcePOT = true;
  46740. }
  46741. 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);
  46742. this._blurY.autoClear = false;
  46743. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  46744. this.addPostProcess(this._blurX);
  46745. this.addPostProcess(this._blurY);
  46746. }
  46747. };
  46748. MirrorTexture.prototype.clone = function () {
  46749. var textureSize = this.getSize();
  46750. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  46751. // Base texture
  46752. newTexture.hasAlpha = this.hasAlpha;
  46753. newTexture.level = this.level;
  46754. // Mirror Texture
  46755. newTexture.mirrorPlane = this.mirrorPlane.clone();
  46756. newTexture.renderList = this.renderList.slice(0);
  46757. return newTexture;
  46758. };
  46759. MirrorTexture.prototype.serialize = function () {
  46760. if (!this.name) {
  46761. return null;
  46762. }
  46763. var serializationObject = _super.prototype.serialize.call(this);
  46764. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  46765. return serializationObject;
  46766. };
  46767. return MirrorTexture;
  46768. }(BABYLON.RenderTargetTexture));
  46769. BABYLON.MirrorTexture = MirrorTexture;
  46770. })(BABYLON || (BABYLON = {}));
  46771. //# sourceMappingURL=babylon.mirrorTexture.js.map
  46772. /// <reference path="babylon.renderTargetTexture.ts" />
  46773. var BABYLON;
  46774. (function (BABYLON) {
  46775. /**
  46776. * Creates a refraction texture used by refraction channel of the standard material.
  46777. * @param name the texture name
  46778. * @param size size of the underlying texture
  46779. * @param scene root scene
  46780. */
  46781. var RefractionTexture = (function (_super) {
  46782. __extends(RefractionTexture, _super);
  46783. function RefractionTexture(name, size, scene, generateMipMaps) {
  46784. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  46785. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  46786. _this.depth = 2.0;
  46787. _this.onBeforeRenderObservable.add(function () {
  46788. scene.clipPlane = _this.refractionPlane;
  46789. });
  46790. _this.onAfterRenderObservable.add(function () {
  46791. delete scene.clipPlane;
  46792. });
  46793. return _this;
  46794. }
  46795. RefractionTexture.prototype.clone = function () {
  46796. var textureSize = this.getSize();
  46797. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  46798. // Base texture
  46799. newTexture.hasAlpha = this.hasAlpha;
  46800. newTexture.level = this.level;
  46801. // Refraction Texture
  46802. newTexture.refractionPlane = this.refractionPlane.clone();
  46803. newTexture.renderList = this.renderList.slice(0);
  46804. newTexture.depth = this.depth;
  46805. return newTexture;
  46806. };
  46807. RefractionTexture.prototype.serialize = function () {
  46808. if (!this.name) {
  46809. return null;
  46810. }
  46811. var serializationObject = _super.prototype.serialize.call(this);
  46812. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  46813. serializationObject.depth = this.depth;
  46814. return serializationObject;
  46815. };
  46816. return RefractionTexture;
  46817. }(BABYLON.RenderTargetTexture));
  46818. BABYLON.RefractionTexture = RefractionTexture;
  46819. })(BABYLON || (BABYLON = {}));
  46820. //# sourceMappingURL=babylon.refractionTexture.js.map
  46821. /// <reference path="babylon.texture.ts" />
  46822. var BABYLON;
  46823. (function (BABYLON) {
  46824. var DynamicTexture = (function (_super) {
  46825. __extends(DynamicTexture, _super);
  46826. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  46827. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46828. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  46829. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  46830. _this.name = name;
  46831. var engine = _this.getScene().getEngine();
  46832. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46833. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46834. _this._generateMipMaps = generateMipMaps;
  46835. if (options.getContext) {
  46836. _this._canvas = options;
  46837. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  46838. }
  46839. else {
  46840. _this._canvas = document.createElement("canvas");
  46841. if (options.width) {
  46842. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  46843. }
  46844. else {
  46845. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  46846. }
  46847. }
  46848. var textureSize = _this.getSize();
  46849. _this._canvas.width = textureSize.width;
  46850. _this._canvas.height = textureSize.height;
  46851. _this._context = _this._canvas.getContext("2d");
  46852. return _this;
  46853. }
  46854. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  46855. get: function () {
  46856. return true;
  46857. },
  46858. enumerable: true,
  46859. configurable: true
  46860. });
  46861. DynamicTexture.prototype._recreate = function (textureSize) {
  46862. this._canvas.width = textureSize.width;
  46863. this._canvas.height = textureSize.height;
  46864. this.releaseInternalTexture();
  46865. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  46866. };
  46867. DynamicTexture.prototype.scale = function (ratio) {
  46868. var textureSize = this.getSize();
  46869. textureSize.width *= ratio;
  46870. textureSize.height *= ratio;
  46871. this._recreate(textureSize);
  46872. };
  46873. DynamicTexture.prototype.scaleTo = function (width, height) {
  46874. var textureSize = this.getSize();
  46875. textureSize.width = width;
  46876. textureSize.height = height;
  46877. this._recreate(textureSize);
  46878. };
  46879. DynamicTexture.prototype.getContext = function () {
  46880. return this._context;
  46881. };
  46882. DynamicTexture.prototype.clear = function () {
  46883. var size = this.getSize();
  46884. this._context.fillRect(0, 0, size.width, size.height);
  46885. };
  46886. DynamicTexture.prototype.update = function (invertY) {
  46887. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  46888. };
  46889. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  46890. if (update === void 0) { update = true; }
  46891. var size = this.getSize();
  46892. if (clearColor) {
  46893. this._context.fillStyle = clearColor;
  46894. this._context.fillRect(0, 0, size.width, size.height);
  46895. }
  46896. this._context.font = font;
  46897. if (x === null || x === undefined) {
  46898. var textSize = this._context.measureText(text);
  46899. x = (size.width - textSize.width) / 2;
  46900. }
  46901. if (y === null || y === undefined) {
  46902. var fontSize = parseInt((font.replace(/\D/g, '')));
  46903. ;
  46904. y = (size.height / 2) + (fontSize / 3.65);
  46905. }
  46906. this._context.fillStyle = color;
  46907. this._context.fillText(text, x, y);
  46908. if (update) {
  46909. this.update(invertY);
  46910. }
  46911. };
  46912. DynamicTexture.prototype.clone = function () {
  46913. var textureSize = this.getSize();
  46914. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  46915. // Base texture
  46916. newTexture.hasAlpha = this.hasAlpha;
  46917. newTexture.level = this.level;
  46918. // Dynamic Texture
  46919. newTexture.wrapU = this.wrapU;
  46920. newTexture.wrapV = this.wrapV;
  46921. return newTexture;
  46922. };
  46923. DynamicTexture.prototype._rebuild = function () {
  46924. this.update();
  46925. };
  46926. return DynamicTexture;
  46927. }(BABYLON.Texture));
  46928. BABYLON.DynamicTexture = DynamicTexture;
  46929. })(BABYLON || (BABYLON = {}));
  46930. //# sourceMappingURL=babylon.dynamicTexture.js.map
  46931. var BABYLON;
  46932. (function (BABYLON) {
  46933. var VideoTexture = (function (_super) {
  46934. __extends(VideoTexture, _super);
  46935. /**
  46936. * Creates a video texture.
  46937. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  46938. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  46939. * @param {BABYLON.Scene} scene is obviously the current scene.
  46940. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  46941. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  46942. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  46943. */
  46944. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  46945. if (generateMipMaps === void 0) { generateMipMaps = false; }
  46946. if (invertY === void 0) { invertY = false; }
  46947. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46948. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46949. _this._autoLaunch = true;
  46950. var urls;
  46951. _this.name = name;
  46952. if (urlsOrVideo instanceof HTMLVideoElement) {
  46953. _this.video = urlsOrVideo;
  46954. }
  46955. else {
  46956. urls = urlsOrVideo;
  46957. _this.video = document.createElement("video");
  46958. _this.video.autoplay = false;
  46959. _this.video.loop = true;
  46960. }
  46961. _this._generateMipMaps = generateMipMaps;
  46962. _this._samplingMode = samplingMode;
  46963. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  46964. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46965. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46966. }
  46967. else {
  46968. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46969. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46970. _this._generateMipMaps = false;
  46971. }
  46972. if (urls) {
  46973. _this.video.addEventListener("canplay", function () {
  46974. _this._createTexture();
  46975. });
  46976. urls.forEach(function (url) {
  46977. var source = document.createElement("source");
  46978. source.src = url;
  46979. _this.video.appendChild(source);
  46980. });
  46981. }
  46982. else {
  46983. _this._createTexture();
  46984. }
  46985. _this._lastUpdate = BABYLON.Tools.Now;
  46986. return _this;
  46987. }
  46988. VideoTexture.prototype.__setTextureReady = function () {
  46989. this._texture.isReady = true;
  46990. };
  46991. VideoTexture.prototype._createTexture = function () {
  46992. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  46993. if (this._autoLaunch) {
  46994. this._autoLaunch = false;
  46995. this.video.play();
  46996. }
  46997. this._setTextureReady = this.__setTextureReady.bind(this);
  46998. this.video.addEventListener("playing", this._setTextureReady);
  46999. };
  47000. VideoTexture.prototype._rebuild = function () {
  47001. this.update();
  47002. };
  47003. VideoTexture.prototype.update = function () {
  47004. var now = BABYLON.Tools.Now;
  47005. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  47006. return false;
  47007. }
  47008. this._lastUpdate = now;
  47009. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  47010. return true;
  47011. };
  47012. VideoTexture.prototype.dispose = function () {
  47013. _super.prototype.dispose.call(this);
  47014. this.video.removeEventListener("playing", this._setTextureReady);
  47015. };
  47016. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  47017. var video = document.createElement("video");
  47018. var constraintsDeviceId;
  47019. if (constraints && constraints.deviceId) {
  47020. constraintsDeviceId = {
  47021. exact: constraints.deviceId
  47022. };
  47023. }
  47024. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  47025. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  47026. if (navigator.getUserMedia) {
  47027. navigator.getUserMedia({
  47028. video: {
  47029. deviceId: constraintsDeviceId,
  47030. width: {
  47031. min: (constraints && constraints.minWidth) || 256,
  47032. max: (constraints && constraints.maxWidth) || 640
  47033. },
  47034. height: {
  47035. min: (constraints && constraints.minHeight) || 256,
  47036. max: (constraints && constraints.maxHeight) || 480
  47037. }
  47038. }
  47039. }, function (stream) {
  47040. if (video.mozSrcObject !== undefined) {
  47041. video.mozSrcObject = stream;
  47042. }
  47043. else {
  47044. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  47045. }
  47046. video.play();
  47047. if (onReady) {
  47048. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  47049. }
  47050. }, function (e) {
  47051. BABYLON.Tools.Error(e.name);
  47052. });
  47053. }
  47054. };
  47055. return VideoTexture;
  47056. }(BABYLON.Texture));
  47057. BABYLON.VideoTexture = VideoTexture;
  47058. })(BABYLON || (BABYLON = {}));
  47059. //# sourceMappingURL=babylon.videoTexture.js.map
  47060. var BABYLON;
  47061. (function (BABYLON) {
  47062. var RawTexture = (function (_super) {
  47063. __extends(RawTexture, _super);
  47064. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  47065. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47066. if (invertY === void 0) { invertY = false; }
  47067. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47068. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  47069. _this.format = format;
  47070. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  47071. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47072. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47073. return _this;
  47074. }
  47075. RawTexture.prototype.update = function (data) {
  47076. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  47077. };
  47078. // Statics
  47079. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47080. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47081. if (invertY === void 0) { invertY = false; }
  47082. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47083. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  47084. };
  47085. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47086. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47087. if (invertY === void 0) { invertY = false; }
  47088. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47089. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  47090. };
  47091. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47092. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47093. if (invertY === void 0) { invertY = false; }
  47094. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47095. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  47096. };
  47097. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47098. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47099. if (invertY === void 0) { invertY = false; }
  47100. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47101. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  47102. };
  47103. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47104. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47105. if (invertY === void 0) { invertY = false; }
  47106. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47107. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  47108. };
  47109. return RawTexture;
  47110. }(BABYLON.Texture));
  47111. BABYLON.RawTexture = RawTexture;
  47112. })(BABYLON || (BABYLON = {}));
  47113. //# sourceMappingURL=babylon.rawTexture.js.map
  47114. var BABYLON;
  47115. (function (BABYLON) {
  47116. var PostProcess = (function () {
  47117. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  47118. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  47119. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47120. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  47121. if (blockCompilation === void 0) { blockCompilation = false; }
  47122. this.name = name;
  47123. this.width = -1;
  47124. this.height = -1;
  47125. this.autoClear = true;
  47126. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  47127. /*
  47128. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  47129. Can only be used on a single postprocess or on the last one of a chain.
  47130. */
  47131. this.enablePixelPerfectMode = false;
  47132. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  47133. this.alwaysForcePOT = false;
  47134. this.samples = 1;
  47135. this.adaptScaleToCurrentViewport = false;
  47136. this._reusable = false;
  47137. this._textures = new BABYLON.SmartArray(2);
  47138. this._currentRenderTextureInd = 0;
  47139. this._scaleRatio = new BABYLON.Vector2(1, 1);
  47140. this._texelSize = BABYLON.Vector2.Zero();
  47141. // Events
  47142. /**
  47143. * An event triggered when the postprocess is activated.
  47144. * @type {BABYLON.Observable}
  47145. */
  47146. this.onActivateObservable = new BABYLON.Observable();
  47147. /**
  47148. * An event triggered when the postprocess changes its size.
  47149. * @type {BABYLON.Observable}
  47150. */
  47151. this.onSizeChangedObservable = new BABYLON.Observable();
  47152. /**
  47153. * An event triggered when the postprocess applies its effect.
  47154. * @type {BABYLON.Observable}
  47155. */
  47156. this.onApplyObservable = new BABYLON.Observable();
  47157. /**
  47158. * An event triggered before rendering the postprocess
  47159. * @type {BABYLON.Observable}
  47160. */
  47161. this.onBeforeRenderObservable = new BABYLON.Observable();
  47162. /**
  47163. * An event triggered after rendering the postprocess
  47164. * @type {BABYLON.Observable}
  47165. */
  47166. this.onAfterRenderObservable = new BABYLON.Observable();
  47167. if (camera != null) {
  47168. this._camera = camera;
  47169. this._scene = camera.getScene();
  47170. camera.attachPostProcess(this);
  47171. this._engine = this._scene.getEngine();
  47172. this._scene.postProcesses.push(this);
  47173. }
  47174. else {
  47175. this._engine = engine;
  47176. this._engine.postProcesses.push(this);
  47177. }
  47178. this._options = options;
  47179. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  47180. this._reusable = reusable || false;
  47181. this._textureType = textureType;
  47182. this._samplers = samplers || [];
  47183. this._samplers.push("textureSampler");
  47184. this._fragmentUrl = fragmentUrl;
  47185. this._vertexUrl = vertexUrl;
  47186. this._parameters = parameters || [];
  47187. this._parameters.push("scale");
  47188. this._indexParameters = indexParameters;
  47189. if (!blockCompilation) {
  47190. this.updateEffect(defines);
  47191. }
  47192. }
  47193. Object.defineProperty(PostProcess.prototype, "onActivate", {
  47194. set: function (callback) {
  47195. if (this._onActivateObserver) {
  47196. this.onActivateObservable.remove(this._onActivateObserver);
  47197. }
  47198. this._onActivateObserver = this.onActivateObservable.add(callback);
  47199. },
  47200. enumerable: true,
  47201. configurable: true
  47202. });
  47203. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  47204. set: function (callback) {
  47205. if (this._onSizeChangedObserver) {
  47206. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  47207. }
  47208. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  47209. },
  47210. enumerable: true,
  47211. configurable: true
  47212. });
  47213. Object.defineProperty(PostProcess.prototype, "onApply", {
  47214. set: function (callback) {
  47215. if (this._onApplyObserver) {
  47216. this.onApplyObservable.remove(this._onApplyObserver);
  47217. }
  47218. this._onApplyObserver = this.onApplyObservable.add(callback);
  47219. },
  47220. enumerable: true,
  47221. configurable: true
  47222. });
  47223. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  47224. set: function (callback) {
  47225. if (this._onBeforeRenderObserver) {
  47226. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  47227. }
  47228. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  47229. },
  47230. enumerable: true,
  47231. configurable: true
  47232. });
  47233. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  47234. set: function (callback) {
  47235. if (this._onAfterRenderObserver) {
  47236. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  47237. }
  47238. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  47239. },
  47240. enumerable: true,
  47241. configurable: true
  47242. });
  47243. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  47244. get: function () {
  47245. return this._textures.data[this._currentRenderTextureInd];
  47246. },
  47247. set: function (value) {
  47248. this._forcedOutputTexture = value;
  47249. },
  47250. enumerable: true,
  47251. configurable: true
  47252. });
  47253. PostProcess.prototype.getCamera = function () {
  47254. return this._camera;
  47255. };
  47256. Object.defineProperty(PostProcess.prototype, "texelSize", {
  47257. get: function () {
  47258. if (this._shareOutputWithPostProcess) {
  47259. return this._shareOutputWithPostProcess.texelSize;
  47260. }
  47261. if (this._forcedOutputTexture) {
  47262. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  47263. }
  47264. return this._texelSize;
  47265. },
  47266. enumerable: true,
  47267. configurable: true
  47268. });
  47269. PostProcess.prototype.getEngine = function () {
  47270. return this._engine;
  47271. };
  47272. PostProcess.prototype.getEffect = function () {
  47273. return this._effect;
  47274. };
  47275. PostProcess.prototype.shareOutputWith = function (postProcess) {
  47276. this._disposeTextures();
  47277. this._shareOutputWithPostProcess = postProcess;
  47278. return this;
  47279. };
  47280. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  47281. 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);
  47282. };
  47283. PostProcess.prototype.isReusable = function () {
  47284. return this._reusable;
  47285. };
  47286. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  47287. PostProcess.prototype.markTextureDirty = function () {
  47288. this.width = -1;
  47289. };
  47290. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  47291. var _this = this;
  47292. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  47293. camera = camera || this._camera;
  47294. var scene = camera.getScene();
  47295. var engine = scene.getEngine();
  47296. var maxSize = engine.getCaps().maxTextureSize;
  47297. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  47298. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  47299. var desiredWidth = (this._options.width || requiredWidth);
  47300. var desiredHeight = this._options.height || requiredHeight;
  47301. if (this.adaptScaleToCurrentViewport) {
  47302. var currentViewport = engine.currentViewport;
  47303. if (currentViewport) {
  47304. desiredWidth *= currentViewport.width;
  47305. desiredHeight *= currentViewport.height;
  47306. }
  47307. }
  47308. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  47309. if (!this._options.width) {
  47310. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  47311. }
  47312. if (!this._options.height) {
  47313. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  47314. }
  47315. }
  47316. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  47317. if (this._textures.length > 0) {
  47318. for (var i = 0; i < this._textures.length; i++) {
  47319. this._engine._releaseTexture(this._textures.data[i]);
  47320. }
  47321. this._textures.reset();
  47322. }
  47323. this.width = desiredWidth;
  47324. this.height = desiredHeight;
  47325. var textureSize = { width: this.width, height: this.height };
  47326. var textureOptions = {
  47327. generateMipMaps: false,
  47328. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  47329. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  47330. samplingMode: this.renderTargetSamplingMode,
  47331. type: this._textureType
  47332. };
  47333. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  47334. if (this._reusable) {
  47335. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  47336. }
  47337. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  47338. this.onSizeChangedObservable.notifyObservers(this);
  47339. }
  47340. this._textures.forEach(function (texture) {
  47341. if (texture.samples !== _this.samples) {
  47342. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  47343. }
  47344. });
  47345. }
  47346. var target;
  47347. if (this._shareOutputWithPostProcess) {
  47348. target = this._shareOutputWithPostProcess.outputTexture;
  47349. }
  47350. else if (this._forcedOutputTexture) {
  47351. target = this._forcedOutputTexture;
  47352. this.width = this._forcedOutputTexture.width;
  47353. this.height = this._forcedOutputTexture.height;
  47354. }
  47355. else {
  47356. target = this.outputTexture;
  47357. }
  47358. if (this.enablePixelPerfectMode) {
  47359. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  47360. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  47361. }
  47362. else {
  47363. this._scaleRatio.copyFromFloats(1, 1);
  47364. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  47365. }
  47366. this.onActivateObservable.notifyObservers(camera);
  47367. // Clear
  47368. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  47369. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  47370. }
  47371. if (this._reusable) {
  47372. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  47373. }
  47374. };
  47375. Object.defineProperty(PostProcess.prototype, "isSupported", {
  47376. get: function () {
  47377. return this._effect.isSupported;
  47378. },
  47379. enumerable: true,
  47380. configurable: true
  47381. });
  47382. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  47383. get: function () {
  47384. if (this._shareOutputWithPostProcess) {
  47385. return this._shareOutputWithPostProcess.aspectRatio;
  47386. }
  47387. if (this._forcedOutputTexture) {
  47388. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  47389. }
  47390. return this.width / this.height;
  47391. },
  47392. enumerable: true,
  47393. configurable: true
  47394. });
  47395. PostProcess.prototype.apply = function () {
  47396. // Check
  47397. if (!this._effect || !this._effect.isReady())
  47398. return null;
  47399. // States
  47400. this._engine.enableEffect(this._effect);
  47401. this._engine.setState(false);
  47402. this._engine.setDepthBuffer(false);
  47403. this._engine.setDepthWrite(false);
  47404. // Alpha
  47405. this._engine.setAlphaMode(this.alphaMode);
  47406. if (this.alphaConstants) {
  47407. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  47408. }
  47409. // Texture
  47410. var source;
  47411. if (this._shareOutputWithPostProcess) {
  47412. source = this._shareOutputWithPostProcess.outputTexture;
  47413. }
  47414. else if (this._forcedOutputTexture) {
  47415. source = this._forcedOutputTexture;
  47416. }
  47417. else {
  47418. source = this.outputTexture;
  47419. }
  47420. this._effect._bindTexture("textureSampler", source);
  47421. // Parameters
  47422. this._effect.setVector2("scale", this._scaleRatio);
  47423. this.onApplyObservable.notifyObservers(this._effect);
  47424. return this._effect;
  47425. };
  47426. PostProcess.prototype._disposeTextures = function () {
  47427. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  47428. return;
  47429. }
  47430. if (this._textures.length > 0) {
  47431. for (var i = 0; i < this._textures.length; i++) {
  47432. this._engine._releaseTexture(this._textures.data[i]);
  47433. }
  47434. }
  47435. this._textures.dispose();
  47436. };
  47437. PostProcess.prototype.dispose = function (camera) {
  47438. camera = camera || this._camera;
  47439. this._disposeTextures();
  47440. if (this._scene) {
  47441. var index_1 = this._scene.postProcesses.indexOf(this);
  47442. if (index_1 !== -1) {
  47443. this._scene.postProcesses.splice(index_1, 1);
  47444. }
  47445. }
  47446. else {
  47447. var index_2 = this._engine.postProcesses.indexOf(this);
  47448. if (index_2 !== -1) {
  47449. this._engine.postProcesses.splice(index_2, 1);
  47450. }
  47451. }
  47452. if (!camera) {
  47453. return;
  47454. }
  47455. camera.detachPostProcess(this);
  47456. var index = camera._postProcesses.indexOf(this);
  47457. if (index === 0 && camera._postProcesses.length > 0) {
  47458. this._camera._postProcesses[0].markTextureDirty();
  47459. }
  47460. this.onActivateObservable.clear();
  47461. this.onAfterRenderObservable.clear();
  47462. this.onApplyObservable.clear();
  47463. this.onBeforeRenderObservable.clear();
  47464. this.onSizeChangedObservable.clear();
  47465. };
  47466. return PostProcess;
  47467. }());
  47468. BABYLON.PostProcess = PostProcess;
  47469. })(BABYLON || (BABYLON = {}));
  47470. //# sourceMappingURL=babylon.postProcess.js.map
  47471. var BABYLON;
  47472. (function (BABYLON) {
  47473. var PassPostProcess = (function (_super) {
  47474. __extends(PassPostProcess, _super);
  47475. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  47476. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47477. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  47478. }
  47479. return PassPostProcess;
  47480. }(BABYLON.PostProcess));
  47481. BABYLON.PassPostProcess = PassPostProcess;
  47482. })(BABYLON || (BABYLON = {}));
  47483. //# sourceMappingURL=babylon.passPostProcess.js.map
  47484. var BABYLON;
  47485. (function (BABYLON) {
  47486. var ShadowGenerator = (function () {
  47487. /**
  47488. * Creates a ShadowGenerator object.
  47489. * A ShadowGenerator is the required tool to use the shadows.
  47490. * Each light casting shadows needs to use its own ShadowGenerator.
  47491. * Required parameters :
  47492. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  47493. * - `light`: the light object generating the shadows.
  47494. * - `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.
  47495. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  47496. */
  47497. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  47498. // Members
  47499. this._bias = 0.00005;
  47500. this._blurBoxOffset = 1;
  47501. this._blurScale = 2;
  47502. this._blurKernel = 1;
  47503. this._useKernelBlur = false;
  47504. this._filter = ShadowGenerator.FILTER_NONE;
  47505. this._darkness = 0;
  47506. this._transparencyShadow = false;
  47507. /**
  47508. * Controls the extent to which the shadows fade out at the edge of the frustum
  47509. * Used only by directionals and spots
  47510. */
  47511. this.frustumEdgeFalloff = 0;
  47512. this.forceBackFacesOnly = false;
  47513. this._lightDirection = BABYLON.Vector3.Zero();
  47514. this._viewMatrix = BABYLON.Matrix.Zero();
  47515. this._projectionMatrix = BABYLON.Matrix.Zero();
  47516. this._transformMatrix = BABYLON.Matrix.Zero();
  47517. this._worldViewProjection = BABYLON.Matrix.Zero();
  47518. this._currentFaceIndex = 0;
  47519. this._currentFaceIndexCache = 0;
  47520. this._isCube = false;
  47521. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  47522. this._mapSize = mapSize;
  47523. this._light = light;
  47524. this._scene = light.getScene();
  47525. light._shadowGenerator = this;
  47526. // Texture type fallback from float to int if not supported.
  47527. var caps = this._scene.getEngine().getCaps();
  47528. if (!useFullFloatFirst) {
  47529. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47530. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47531. }
  47532. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47533. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47534. }
  47535. else {
  47536. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47537. }
  47538. }
  47539. else {
  47540. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47541. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47542. }
  47543. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47544. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47545. }
  47546. else {
  47547. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47548. }
  47549. }
  47550. this._initializeGenerator();
  47551. }
  47552. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  47553. // Static
  47554. get: function () {
  47555. return ShadowGenerator._FILTER_NONE;
  47556. },
  47557. enumerable: true,
  47558. configurable: true
  47559. });
  47560. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  47561. get: function () {
  47562. return ShadowGenerator._FILTER_POISSONSAMPLING;
  47563. },
  47564. enumerable: true,
  47565. configurable: true
  47566. });
  47567. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  47568. get: function () {
  47569. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  47570. },
  47571. enumerable: true,
  47572. configurable: true
  47573. });
  47574. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  47575. get: function () {
  47576. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  47577. },
  47578. enumerable: true,
  47579. configurable: true
  47580. });
  47581. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  47582. get: function () {
  47583. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47584. },
  47585. enumerable: true,
  47586. configurable: true
  47587. });
  47588. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  47589. get: function () {
  47590. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47591. },
  47592. enumerable: true,
  47593. configurable: true
  47594. });
  47595. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  47596. get: function () {
  47597. return this._bias;
  47598. },
  47599. set: function (bias) {
  47600. this._bias = bias;
  47601. },
  47602. enumerable: true,
  47603. configurable: true
  47604. });
  47605. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  47606. get: function () {
  47607. return this._blurBoxOffset;
  47608. },
  47609. set: function (value) {
  47610. if (this._blurBoxOffset === value) {
  47611. return;
  47612. }
  47613. this._blurBoxOffset = value;
  47614. this._disposeBlurPostProcesses();
  47615. },
  47616. enumerable: true,
  47617. configurable: true
  47618. });
  47619. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  47620. get: function () {
  47621. return this._blurScale;
  47622. },
  47623. set: function (value) {
  47624. if (this._blurScale === value) {
  47625. return;
  47626. }
  47627. this._blurScale = value;
  47628. this._disposeBlurPostProcesses();
  47629. },
  47630. enumerable: true,
  47631. configurable: true
  47632. });
  47633. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  47634. get: function () {
  47635. return this._blurKernel;
  47636. },
  47637. set: function (value) {
  47638. if (this._blurKernel === value) {
  47639. return;
  47640. }
  47641. this._blurKernel = value;
  47642. this._disposeBlurPostProcesses();
  47643. },
  47644. enumerable: true,
  47645. configurable: true
  47646. });
  47647. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  47648. get: function () {
  47649. return this._useKernelBlur;
  47650. },
  47651. set: function (value) {
  47652. if (this._useKernelBlur === value) {
  47653. return;
  47654. }
  47655. this._useKernelBlur = value;
  47656. this._disposeBlurPostProcesses();
  47657. },
  47658. enumerable: true,
  47659. configurable: true
  47660. });
  47661. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  47662. get: function () {
  47663. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  47664. },
  47665. set: function (value) {
  47666. this._depthScale = value;
  47667. },
  47668. enumerable: true,
  47669. configurable: true
  47670. });
  47671. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  47672. get: function () {
  47673. return this._filter;
  47674. },
  47675. set: function (value) {
  47676. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  47677. if (this._light.needCube()) {
  47678. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47679. this.useExponentialShadowMap = true;
  47680. return;
  47681. }
  47682. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47683. this.useCloseExponentialShadowMap = true;
  47684. return;
  47685. }
  47686. }
  47687. if (this._filter === value) {
  47688. return;
  47689. }
  47690. this._filter = value;
  47691. this._disposeBlurPostProcesses();
  47692. this._applyFilterValues();
  47693. this._light._markMeshesAsLightDirty();
  47694. },
  47695. enumerable: true,
  47696. configurable: true
  47697. });
  47698. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  47699. get: function () {
  47700. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  47701. },
  47702. set: function (value) {
  47703. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  47704. return;
  47705. }
  47706. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  47707. },
  47708. enumerable: true,
  47709. configurable: true
  47710. });
  47711. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  47712. get: function () {
  47713. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47714. return this.useExponentialShadowMap;
  47715. },
  47716. set: function (value) {
  47717. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47718. this.useExponentialShadowMap = value;
  47719. },
  47720. enumerable: true,
  47721. configurable: true
  47722. });
  47723. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  47724. get: function () {
  47725. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47726. return this.useBlurExponentialShadowMap;
  47727. },
  47728. set: function (value) {
  47729. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47730. this.useBlurExponentialShadowMap = value;
  47731. },
  47732. enumerable: true,
  47733. configurable: true
  47734. });
  47735. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  47736. get: function () {
  47737. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  47738. },
  47739. set: function (value) {
  47740. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  47741. return;
  47742. }
  47743. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47744. },
  47745. enumerable: true,
  47746. configurable: true
  47747. });
  47748. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  47749. get: function () {
  47750. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  47751. },
  47752. set: function (value) {
  47753. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47754. return;
  47755. }
  47756. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47757. },
  47758. enumerable: true,
  47759. configurable: true
  47760. });
  47761. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  47762. get: function () {
  47763. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47764. },
  47765. set: function (value) {
  47766. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  47767. return;
  47768. }
  47769. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47770. },
  47771. enumerable: true,
  47772. configurable: true
  47773. });
  47774. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  47775. get: function () {
  47776. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47777. },
  47778. set: function (value) {
  47779. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47780. return;
  47781. }
  47782. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47783. },
  47784. enumerable: true,
  47785. configurable: true
  47786. });
  47787. /**
  47788. * Returns the darkness value (float).
  47789. */
  47790. ShadowGenerator.prototype.getDarkness = function () {
  47791. return this._darkness;
  47792. };
  47793. /**
  47794. * Sets the ShadowGenerator darkness value (float <= 1.0).
  47795. * Returns the ShadowGenerator.
  47796. */
  47797. ShadowGenerator.prototype.setDarkness = function (darkness) {
  47798. if (darkness >= 1.0)
  47799. this._darkness = 1.0;
  47800. else if (darkness <= 0.0)
  47801. this._darkness = 0.0;
  47802. else
  47803. this._darkness = darkness;
  47804. return this;
  47805. };
  47806. /**
  47807. * Sets the ability to have transparent shadow (boolean).
  47808. * Returns the ShadowGenerator.
  47809. */
  47810. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  47811. this._transparencyShadow = hasShadow;
  47812. return this;
  47813. };
  47814. /**
  47815. * Returns a RenderTargetTexture object : the shadow map texture.
  47816. */
  47817. ShadowGenerator.prototype.getShadowMap = function () {
  47818. return this._shadowMap;
  47819. };
  47820. /**
  47821. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  47822. */
  47823. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  47824. if (this._shadowMap2) {
  47825. return this._shadowMap2;
  47826. }
  47827. return this._shadowMap;
  47828. };
  47829. /**
  47830. * Returns the associated light object.
  47831. */
  47832. ShadowGenerator.prototype.getLight = function () {
  47833. return this._light;
  47834. };
  47835. ShadowGenerator.prototype._initializeGenerator = function () {
  47836. this._light._markMeshesAsLightDirty();
  47837. this._initializeShadowMap();
  47838. };
  47839. ShadowGenerator.prototype._initializeShadowMap = function () {
  47840. var _this = this;
  47841. // Render target
  47842. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  47843. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47844. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47845. this._shadowMap.anisotropicFilteringLevel = 1;
  47846. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47847. this._shadowMap.renderParticles = false;
  47848. this._shadowMap.ignoreCameraViewport = true;
  47849. // Record Face Index before render.
  47850. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  47851. _this._currentFaceIndex = faceIndex;
  47852. });
  47853. // Custom render function.
  47854. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  47855. // Blur if required afer render.
  47856. this._shadowMap.onAfterUnbindObservable.add(function () {
  47857. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  47858. return;
  47859. }
  47860. if (!_this._blurPostProcesses) {
  47861. _this._initializeBlurRTTAndPostProcesses();
  47862. }
  47863. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture(), true);
  47864. });
  47865. // Clear according to the chosen filter.
  47866. this._shadowMap.onClearObservable.add(function (engine) {
  47867. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  47868. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  47869. }
  47870. else {
  47871. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47872. }
  47873. });
  47874. };
  47875. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  47876. var _this = this;
  47877. var engine = this._scene.getEngine();
  47878. var targetSize = this._mapSize / this.blurScale;
  47879. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  47880. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  47881. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47882. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47883. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47884. }
  47885. if (this.useKernelBlur) {
  47886. 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);
  47887. this._kernelBlurXPostprocess.width = targetSize;
  47888. this._kernelBlurXPostprocess.height = targetSize;
  47889. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  47890. effect.setTexture("textureSampler", _this._shadowMap);
  47891. });
  47892. 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);
  47893. this._kernelBlurXPostprocess.autoClear = false;
  47894. this._kernelBlurYPostprocess.autoClear = false;
  47895. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47896. this._kernelBlurXPostprocess.packedFloat = true;
  47897. this._kernelBlurYPostprocess.packedFloat = true;
  47898. }
  47899. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  47900. }
  47901. else {
  47902. 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);
  47903. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  47904. effect.setFloat2("screenSize", targetSize, targetSize);
  47905. effect.setTexture("textureSampler", _this._shadowMap);
  47906. });
  47907. this._boxBlurPostprocess.autoClear = false;
  47908. this._blurPostProcesses = [this._boxBlurPostprocess];
  47909. }
  47910. };
  47911. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  47912. var index;
  47913. var engine = this._scene.getEngine();
  47914. if (depthOnlySubMeshes.length) {
  47915. engine.setColorWrite(false);
  47916. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  47917. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  47918. }
  47919. engine.setColorWrite(true);
  47920. }
  47921. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47922. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  47923. }
  47924. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47925. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  47926. }
  47927. if (this._transparencyShadow) {
  47928. for (index = 0; index < transparentSubMeshes.length; index++) {
  47929. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  47930. }
  47931. }
  47932. };
  47933. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  47934. var _this = this;
  47935. var mesh = subMesh.getRenderingMesh();
  47936. var scene = this._scene;
  47937. var engine = scene.getEngine();
  47938. // Culling
  47939. engine.setState(subMesh.getMaterial().backFaceCulling);
  47940. // Managing instances
  47941. var batch = mesh._getInstancesRenderList(subMesh._id);
  47942. if (batch.mustReturn) {
  47943. return;
  47944. }
  47945. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  47946. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  47947. engine.enableEffect(this._effect);
  47948. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  47949. var material = subMesh.getMaterial();
  47950. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  47951. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  47952. this._effect.setVector3("lightPosition", this.getLight().position);
  47953. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  47954. // Alpha test
  47955. if (material && material.needAlphaTesting()) {
  47956. var alphaTexture = material.getAlphaTestTexture();
  47957. if (alphaTexture) {
  47958. this._effect.setTexture("diffuseSampler", alphaTexture);
  47959. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  47960. }
  47961. }
  47962. // Bones
  47963. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47964. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47965. }
  47966. if (this.forceBackFacesOnly) {
  47967. engine.setState(true, 0, false, true);
  47968. }
  47969. // Draw
  47970. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47971. if (this.forceBackFacesOnly) {
  47972. engine.setState(true, 0, false, false);
  47973. }
  47974. }
  47975. else {
  47976. // Need to reset refresh rate of the shadowMap
  47977. this._shadowMap.resetRefreshCounter();
  47978. }
  47979. };
  47980. ShadowGenerator.prototype._applyFilterValues = function () {
  47981. if (this.filter === ShadowGenerator.FILTER_NONE) {
  47982. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  47983. }
  47984. else {
  47985. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47986. }
  47987. };
  47988. /**
  47989. * Force shader compilation including textures ready check
  47990. */
  47991. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  47992. var _this = this;
  47993. var scene = this._scene;
  47994. var engine = scene.getEngine();
  47995. var subMeshes = new Array();
  47996. var currentIndex = 0;
  47997. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  47998. var mesh = _a[_i];
  47999. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  48000. }
  48001. var checkReady = function () {
  48002. if (!_this._scene || !_this._scene.getEngine()) {
  48003. return;
  48004. }
  48005. var subMesh = subMeshes[currentIndex];
  48006. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  48007. currentIndex++;
  48008. if (currentIndex >= subMeshes.length) {
  48009. if (onCompiled) {
  48010. onCompiled(_this);
  48011. }
  48012. return;
  48013. }
  48014. }
  48015. setTimeout(checkReady, 16);
  48016. };
  48017. if (subMeshes.length > 0) {
  48018. checkReady();
  48019. }
  48020. };
  48021. /**
  48022. * Boolean : true when the ShadowGenerator is finally computed.
  48023. */
  48024. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  48025. var defines = [];
  48026. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48027. defines.push("#define FLOAT");
  48028. }
  48029. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  48030. defines.push("#define ESM");
  48031. }
  48032. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48033. var mesh = subMesh.getMesh();
  48034. var material = subMesh.getMaterial();
  48035. // Alpha test
  48036. if (material && material.needAlphaTesting()) {
  48037. var alphaTexture = material.getAlphaTestTexture();
  48038. if (alphaTexture) {
  48039. defines.push("#define ALPHATEST");
  48040. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48041. attribs.push(BABYLON.VertexBuffer.UVKind);
  48042. defines.push("#define UV1");
  48043. }
  48044. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48045. if (alphaTexture.coordinatesIndex === 1) {
  48046. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48047. defines.push("#define UV2");
  48048. }
  48049. }
  48050. }
  48051. }
  48052. // Bones
  48053. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48054. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48055. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48056. if (mesh.numBoneInfluencers > 4) {
  48057. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48058. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48059. }
  48060. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48061. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48062. }
  48063. else {
  48064. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48065. }
  48066. // Instances
  48067. if (useInstances) {
  48068. defines.push("#define INSTANCES");
  48069. attribs.push("world0");
  48070. attribs.push("world1");
  48071. attribs.push("world2");
  48072. attribs.push("world3");
  48073. }
  48074. // Get correct effect
  48075. var join = defines.join("\n");
  48076. if (this._cachedDefines !== join) {
  48077. this._cachedDefines = join;
  48078. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  48079. }
  48080. return this._effect.isReady();
  48081. };
  48082. /**
  48083. * This creates the defines related to the standard BJS materials.
  48084. */
  48085. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  48086. var scene = this._scene;
  48087. var light = this._light;
  48088. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  48089. return;
  48090. }
  48091. defines["SHADOW" + lightIndex] = true;
  48092. if (this.usePoissonSampling) {
  48093. defines["SHADOWPCF" + lightIndex] = true;
  48094. }
  48095. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  48096. defines["SHADOWESM" + lightIndex] = true;
  48097. }
  48098. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  48099. defines["SHADOWCLOSEESM" + lightIndex] = true;
  48100. }
  48101. if (light.needCube()) {
  48102. defines["SHADOWCUBE" + lightIndex] = true;
  48103. }
  48104. };
  48105. /**
  48106. * This binds shadow lights related to the standard BJS materials.
  48107. * It implies the unifroms available on the materials are the standard BJS ones.
  48108. */
  48109. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  48110. var light = this._light;
  48111. var scene = this._scene;
  48112. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  48113. return;
  48114. }
  48115. if (!light.needCube()) {
  48116. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  48117. }
  48118. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  48119. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  48120. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  48121. };
  48122. // Methods
  48123. /**
  48124. * Returns a Matrix object : the updated transformation matrix.
  48125. */
  48126. ShadowGenerator.prototype.getTransformMatrix = function () {
  48127. var scene = this._scene;
  48128. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  48129. return this._transformMatrix;
  48130. }
  48131. this._currentRenderID = scene.getRenderId();
  48132. this._currentFaceIndexCache = this._currentFaceIndex;
  48133. var lightPosition = this._light.position;
  48134. if (this._light.computeTransformedInformation()) {
  48135. lightPosition = this._light.transformedPosition;
  48136. }
  48137. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  48138. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  48139. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  48140. }
  48141. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  48142. this._cachedPosition = lightPosition.clone();
  48143. this._cachedDirection = this._lightDirection.clone();
  48144. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  48145. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  48146. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  48147. }
  48148. return this._transformMatrix;
  48149. };
  48150. ShadowGenerator.prototype.recreateShadowMap = function () {
  48151. // Track render list.
  48152. var renderList = this._shadowMap.renderList;
  48153. // Clean up existing data.
  48154. this._disposeRTTandPostProcesses();
  48155. // Reinitializes.
  48156. this._initializeGenerator();
  48157. // Reaffect the filter to ensure a correct fallback if necessary.
  48158. this.filter = this.filter;
  48159. // Reaffect the filter.
  48160. this._applyFilterValues();
  48161. // Reaffect Render List.
  48162. this._shadowMap.renderList = renderList;
  48163. };
  48164. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  48165. if (this._shadowMap2) {
  48166. this._shadowMap2.dispose();
  48167. this._shadowMap2 = null;
  48168. }
  48169. if (this._downSamplePostprocess) {
  48170. this._downSamplePostprocess.dispose();
  48171. this._downSamplePostprocess = null;
  48172. }
  48173. if (this._boxBlurPostprocess) {
  48174. this._boxBlurPostprocess.dispose();
  48175. this._boxBlurPostprocess = null;
  48176. }
  48177. if (this._kernelBlurXPostprocess) {
  48178. this._kernelBlurXPostprocess.dispose();
  48179. this._kernelBlurXPostprocess = null;
  48180. }
  48181. if (this._kernelBlurYPostprocess) {
  48182. this._kernelBlurYPostprocess.dispose();
  48183. this._kernelBlurYPostprocess = null;
  48184. }
  48185. this._blurPostProcesses = null;
  48186. };
  48187. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  48188. if (this._shadowMap) {
  48189. this._shadowMap.dispose();
  48190. this._shadowMap = null;
  48191. }
  48192. this._disposeBlurPostProcesses();
  48193. };
  48194. /**
  48195. * Disposes the ShadowGenerator.
  48196. * Returns nothing.
  48197. */
  48198. ShadowGenerator.prototype.dispose = function () {
  48199. this._disposeRTTandPostProcesses();
  48200. this._light._shadowGenerator = null;
  48201. this._light._markMeshesAsLightDirty();
  48202. };
  48203. /**
  48204. * Serializes the ShadowGenerator and returns a serializationObject.
  48205. */
  48206. ShadowGenerator.prototype.serialize = function () {
  48207. var serializationObject = {};
  48208. var shadowMap = this.getShadowMap();
  48209. serializationObject.lightId = this._light.id;
  48210. serializationObject.mapSize = shadowMap.getRenderSize();
  48211. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  48212. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  48213. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  48214. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  48215. serializationObject.usePoissonSampling = this.usePoissonSampling;
  48216. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  48217. serializationObject.depthScale = this.depthScale;
  48218. serializationObject.darkness = this.getDarkness();
  48219. serializationObject.blurBoxOffset = this.blurBoxOffset;
  48220. serializationObject.blurKernel = this.blurKernel;
  48221. serializationObject.blurScale = this.blurScale;
  48222. serializationObject.useKernelBlur = this.useKernelBlur;
  48223. serializationObject.transparencyShadow = this._transparencyShadow;
  48224. serializationObject.renderList = [];
  48225. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  48226. var mesh = shadowMap.renderList[meshIndex];
  48227. serializationObject.renderList.push(mesh.id);
  48228. }
  48229. return serializationObject;
  48230. };
  48231. /**
  48232. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  48233. */
  48234. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  48235. //casting to point light, as light is missing the position attr and typescript complains.
  48236. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  48237. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  48238. var shadowMap = shadowGenerator.getShadowMap();
  48239. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  48240. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  48241. meshes.forEach(function (mesh) {
  48242. shadowMap.renderList.push(mesh);
  48243. });
  48244. }
  48245. if (parsedShadowGenerator.usePoissonSampling) {
  48246. shadowGenerator.usePoissonSampling = true;
  48247. }
  48248. else if (parsedShadowGenerator.useExponentialShadowMap) {
  48249. shadowGenerator.useExponentialShadowMap = true;
  48250. }
  48251. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  48252. shadowGenerator.useBlurExponentialShadowMap = true;
  48253. }
  48254. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  48255. shadowGenerator.useCloseExponentialShadowMap = true;
  48256. }
  48257. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  48258. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  48259. }
  48260. else if (parsedShadowGenerator.useVarianceShadowMap) {
  48261. shadowGenerator.useExponentialShadowMap = true;
  48262. }
  48263. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  48264. shadowGenerator.useBlurExponentialShadowMap = true;
  48265. }
  48266. if (parsedShadowGenerator.depthScale) {
  48267. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  48268. }
  48269. if (parsedShadowGenerator.blurScale) {
  48270. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  48271. }
  48272. if (parsedShadowGenerator.blurBoxOffset) {
  48273. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  48274. }
  48275. if (parsedShadowGenerator.useKernelBlur) {
  48276. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  48277. }
  48278. if (parsedShadowGenerator.blurKernel) {
  48279. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  48280. }
  48281. if (parsedShadowGenerator.bias !== undefined) {
  48282. shadowGenerator.bias = parsedShadowGenerator.bias;
  48283. }
  48284. if (parsedShadowGenerator.darkness) {
  48285. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  48286. }
  48287. if (parsedShadowGenerator.transparencyShadow) {
  48288. shadowGenerator.setTransparencyShadow(true);
  48289. }
  48290. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  48291. return shadowGenerator;
  48292. };
  48293. ShadowGenerator._FILTER_NONE = 0;
  48294. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  48295. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  48296. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  48297. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  48298. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  48299. return ShadowGenerator;
  48300. }());
  48301. BABYLON.ShadowGenerator = ShadowGenerator;
  48302. })(BABYLON || (BABYLON = {}));
  48303. //# sourceMappingURL=babylon.shadowGenerator.js.map
  48304. var BABYLON;
  48305. (function (BABYLON) {
  48306. var DefaultLoadingScreen = (function () {
  48307. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  48308. if (_loadingText === void 0) { _loadingText = ""; }
  48309. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  48310. var _this = this;
  48311. this._renderingCanvas = _renderingCanvas;
  48312. this._loadingText = _loadingText;
  48313. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  48314. // Resize
  48315. this._resizeLoadingUI = function () {
  48316. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  48317. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  48318. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  48319. _this._loadingDiv.style.left = canvasRect.left + "px";
  48320. _this._loadingDiv.style.top = canvasRect.top + "px";
  48321. _this._loadingDiv.style.width = canvasRect.width + "px";
  48322. _this._loadingDiv.style.height = canvasRect.height + "px";
  48323. };
  48324. }
  48325. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  48326. if (this._loadingDiv) {
  48327. // Do not add a loading screen if there is already one
  48328. return;
  48329. }
  48330. this._loadingDiv = document.createElement("div");
  48331. this._loadingDiv.id = "babylonjsLoadingDiv";
  48332. this._loadingDiv.style.opacity = "0";
  48333. this._loadingDiv.style.transition = "opacity 1.5s ease";
  48334. this._loadingDiv.style.pointerEvents = "none";
  48335. // Loading text
  48336. this._loadingTextDiv = document.createElement("div");
  48337. this._loadingTextDiv.style.position = "absolute";
  48338. this._loadingTextDiv.style.left = "0";
  48339. this._loadingTextDiv.style.top = "50%";
  48340. this._loadingTextDiv.style.marginTop = "80px";
  48341. this._loadingTextDiv.style.width = "100%";
  48342. this._loadingTextDiv.style.height = "20px";
  48343. this._loadingTextDiv.style.fontFamily = "Arial";
  48344. this._loadingTextDiv.style.fontSize = "14px";
  48345. this._loadingTextDiv.style.color = "white";
  48346. this._loadingTextDiv.style.textAlign = "center";
  48347. this._loadingTextDiv.innerHTML = "Loading";
  48348. this._loadingDiv.appendChild(this._loadingTextDiv);
  48349. //set the predefined text
  48350. this._loadingTextDiv.innerHTML = this._loadingText;
  48351. // Generating keyframes
  48352. var style = document.createElement('style');
  48353. style.type = 'text/css';
  48354. 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 }";
  48355. style.innerHTML = keyFrames;
  48356. document.getElementsByTagName('head')[0].appendChild(style);
  48357. // Loading img
  48358. var imgBack = new Image();
  48359. 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";
  48360. imgBack.style.position = "absolute";
  48361. imgBack.style.left = "50%";
  48362. imgBack.style.top = "50%";
  48363. imgBack.style.marginLeft = "-60px";
  48364. imgBack.style.marginTop = "-60px";
  48365. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  48366. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  48367. imgBack.style.transformOrigin = "50% 50%";
  48368. imgBack.style.webkitTransformOrigin = "50% 50%";
  48369. this._loadingDiv.appendChild(imgBack);
  48370. this._resizeLoadingUI();
  48371. window.addEventListener("resize", this._resizeLoadingUI);
  48372. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48373. document.body.appendChild(this._loadingDiv);
  48374. this._loadingDiv.style.opacity = "1";
  48375. };
  48376. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  48377. var _this = this;
  48378. if (!this._loadingDiv) {
  48379. return;
  48380. }
  48381. var onTransitionEnd = function () {
  48382. if (!_this._loadingDiv) {
  48383. return;
  48384. }
  48385. document.body.removeChild(_this._loadingDiv);
  48386. window.removeEventListener("resize", _this._resizeLoadingUI);
  48387. _this._loadingDiv = null;
  48388. };
  48389. this._loadingDiv.style.opacity = "0";
  48390. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  48391. };
  48392. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  48393. set: function (text) {
  48394. this._loadingText = text;
  48395. if (this._loadingTextDiv) {
  48396. this._loadingTextDiv.innerHTML = this._loadingText;
  48397. }
  48398. },
  48399. enumerable: true,
  48400. configurable: true
  48401. });
  48402. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  48403. get: function () {
  48404. return this._loadingDivBackgroundColor;
  48405. },
  48406. set: function (color) {
  48407. this._loadingDivBackgroundColor = color;
  48408. if (!this._loadingDiv) {
  48409. return;
  48410. }
  48411. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48412. },
  48413. enumerable: true,
  48414. configurable: true
  48415. });
  48416. return DefaultLoadingScreen;
  48417. }());
  48418. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  48419. })(BABYLON || (BABYLON = {}));
  48420. //# sourceMappingURL=babylon.loadingScreen.js.map
  48421. var BABYLON;
  48422. (function (BABYLON) {
  48423. var SceneLoader = (function () {
  48424. function SceneLoader() {
  48425. }
  48426. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  48427. get: function () {
  48428. return 0;
  48429. },
  48430. enumerable: true,
  48431. configurable: true
  48432. });
  48433. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  48434. get: function () {
  48435. return 1;
  48436. },
  48437. enumerable: true,
  48438. configurable: true
  48439. });
  48440. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  48441. get: function () {
  48442. return 2;
  48443. },
  48444. enumerable: true,
  48445. configurable: true
  48446. });
  48447. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  48448. get: function () {
  48449. return 3;
  48450. },
  48451. enumerable: true,
  48452. configurable: true
  48453. });
  48454. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  48455. get: function () {
  48456. return SceneLoader._ForceFullSceneLoadingForIncremental;
  48457. },
  48458. set: function (value) {
  48459. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  48460. },
  48461. enumerable: true,
  48462. configurable: true
  48463. });
  48464. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  48465. get: function () {
  48466. return SceneLoader._ShowLoadingScreen;
  48467. },
  48468. set: function (value) {
  48469. SceneLoader._ShowLoadingScreen = value;
  48470. },
  48471. enumerable: true,
  48472. configurable: true
  48473. });
  48474. Object.defineProperty(SceneLoader, "loggingLevel", {
  48475. get: function () {
  48476. return SceneLoader._loggingLevel;
  48477. },
  48478. set: function (value) {
  48479. SceneLoader._loggingLevel = value;
  48480. },
  48481. enumerable: true,
  48482. configurable: true
  48483. });
  48484. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  48485. get: function () {
  48486. return SceneLoader._CleanBoneMatrixWeights;
  48487. },
  48488. set: function (value) {
  48489. SceneLoader._CleanBoneMatrixWeights = value;
  48490. },
  48491. enumerable: true,
  48492. configurable: true
  48493. });
  48494. SceneLoader._getDefaultPlugin = function () {
  48495. return SceneLoader._registeredPlugins[".babylon"];
  48496. };
  48497. SceneLoader._getPluginForExtension = function (extension) {
  48498. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  48499. if (registeredPlugin) {
  48500. return registeredPlugin;
  48501. }
  48502. return SceneLoader._getDefaultPlugin();
  48503. };
  48504. SceneLoader._getPluginForDirectLoad = function (data) {
  48505. for (var extension in SceneLoader._registeredPlugins) {
  48506. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  48507. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  48508. return SceneLoader._registeredPlugins[extension];
  48509. }
  48510. }
  48511. return SceneLoader._getDefaultPlugin();
  48512. };
  48513. SceneLoader._getPluginForFilename = function (sceneFilename) {
  48514. if (sceneFilename.name) {
  48515. sceneFilename = sceneFilename.name;
  48516. }
  48517. var dotPosition = sceneFilename.lastIndexOf(".");
  48518. var queryStringPosition = sceneFilename.indexOf("?");
  48519. if (queryStringPosition === -1) {
  48520. queryStringPosition = sceneFilename.length;
  48521. }
  48522. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  48523. return SceneLoader._getPluginForExtension(extension);
  48524. };
  48525. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  48526. SceneLoader._getDirectLoad = function (sceneFilename) {
  48527. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  48528. return sceneFilename.substr(5);
  48529. }
  48530. return null;
  48531. };
  48532. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48533. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  48534. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  48535. var plugin = registeredPlugin.plugin;
  48536. var useArrayBuffer = registeredPlugin.isBinary;
  48537. var database;
  48538. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  48539. var dataCallback = function (data) {
  48540. if (scene.isDisposed) {
  48541. onError("Scene has been disposed");
  48542. return;
  48543. }
  48544. scene.database = database;
  48545. try {
  48546. onSuccess(plugin, data);
  48547. }
  48548. catch (e) {
  48549. onError(null, e);
  48550. }
  48551. };
  48552. var manifestChecked = function (success) {
  48553. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  48554. onError(request.status + " " + request.statusText);
  48555. });
  48556. };
  48557. if (directLoad) {
  48558. dataCallback(directLoad);
  48559. return;
  48560. }
  48561. if (rootUrl.indexOf("file:") === -1) {
  48562. if (scene.getEngine().enableOfflineSupport) {
  48563. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  48564. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  48565. }
  48566. else {
  48567. manifestChecked(true);
  48568. }
  48569. }
  48570. else {
  48571. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  48572. }
  48573. };
  48574. // Public functions
  48575. SceneLoader.GetPluginForExtension = function (extension) {
  48576. return SceneLoader._getPluginForExtension(extension).plugin;
  48577. };
  48578. SceneLoader.RegisterPlugin = function (plugin) {
  48579. if (typeof plugin.extensions === "string") {
  48580. var extension = plugin.extensions;
  48581. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48582. plugin: plugin,
  48583. isBinary: false
  48584. };
  48585. }
  48586. else {
  48587. var extensions = plugin.extensions;
  48588. Object.keys(extensions).forEach(function (extension) {
  48589. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48590. plugin: plugin,
  48591. isBinary: extensions[extension].isBinary
  48592. };
  48593. });
  48594. }
  48595. };
  48596. /**
  48597. * Import meshes into a scene
  48598. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  48599. * @param rootUrl a string that defines the root url for scene and resources
  48600. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48601. * @param scene the instance of BABYLON.Scene to append to
  48602. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  48603. * @param onProgress a callback with a progress event for each file being loaded
  48604. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48605. */
  48606. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48607. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48608. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48609. return;
  48610. }
  48611. var loadingToken = {};
  48612. scene._addPendingData(loadingToken);
  48613. var errorHandler = function (message, exception) {
  48614. if (onError) {
  48615. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48616. }
  48617. scene._removePendingData(loadingToken);
  48618. };
  48619. var progressHandler = function (event) {
  48620. if (onProgress) {
  48621. onProgress(event);
  48622. }
  48623. };
  48624. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48625. if (plugin.importMesh) {
  48626. var syncedPlugin = plugin;
  48627. var meshes = [];
  48628. var particleSystems = [];
  48629. var skeletons = [];
  48630. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  48631. return;
  48632. }
  48633. if (onSuccess) {
  48634. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48635. onSuccess(meshes, particleSystems, skeletons);
  48636. scene._removePendingData(loadingToken);
  48637. }
  48638. }
  48639. else {
  48640. var asyncedPlugin = plugin;
  48641. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  48642. if (onSuccess) {
  48643. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48644. onSuccess(meshes, particleSystems, skeletons);
  48645. scene._removePendingData(loadingToken);
  48646. }
  48647. }, progressHandler, errorHandler);
  48648. }
  48649. }, progressHandler, errorHandler);
  48650. };
  48651. /**
  48652. * Load a scene
  48653. * @param rootUrl a string that defines the root url for scene and resources
  48654. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48655. * @param engine is the instance of BABYLON.Engine to use to create the scene
  48656. * @param onSuccess a callback with the scene when import succeeds
  48657. * @param onProgress a callback with a progress event for each file being loaded
  48658. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48659. */
  48660. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  48661. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  48662. };
  48663. /**
  48664. * Append a scene
  48665. * @param rootUrl a string that defines the root url for scene and resources
  48666. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48667. * @param scene is the instance of BABYLON.Scene to append to
  48668. * @param onSuccess a callback with the scene when import succeeds
  48669. * @param onProgress a callback with a progress event for each file being loaded
  48670. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48671. */
  48672. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48673. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48674. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48675. return;
  48676. }
  48677. if (SceneLoader.ShowLoadingScreen) {
  48678. scene.getEngine().displayLoadingUI();
  48679. }
  48680. var loadingToken = {};
  48681. scene._addPendingData(loadingToken);
  48682. var errorHandler = function (message, exception) {
  48683. if (onError) {
  48684. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48685. }
  48686. scene._removePendingData(loadingToken);
  48687. scene.getEngine().hideLoadingUI();
  48688. };
  48689. var progressHandler = function (event) {
  48690. if (onProgress) {
  48691. onProgress(event);
  48692. }
  48693. };
  48694. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48695. if (plugin.load) {
  48696. var syncedPlugin = plugin;
  48697. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  48698. return;
  48699. }
  48700. if (onSuccess) {
  48701. onSuccess(scene);
  48702. }
  48703. scene.loadingPluginName = plugin.name;
  48704. scene._removePendingData(loadingToken);
  48705. }
  48706. else {
  48707. var asyncedPlugin = plugin;
  48708. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  48709. if (onSuccess) {
  48710. onSuccess(scene);
  48711. }
  48712. scene.loadingPluginName = plugin.name;
  48713. scene._removePendingData(loadingToken);
  48714. }, progressHandler, errorHandler);
  48715. }
  48716. if (SceneLoader.ShowLoadingScreen) {
  48717. scene.executeWhenReady(function () {
  48718. scene.getEngine().hideLoadingUI();
  48719. });
  48720. }
  48721. }, progressHandler, errorHandler);
  48722. };
  48723. // Flags
  48724. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  48725. SceneLoader._ShowLoadingScreen = true;
  48726. SceneLoader._CleanBoneMatrixWeights = false;
  48727. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  48728. // Members
  48729. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  48730. SceneLoader._registeredPlugins = {};
  48731. return SceneLoader;
  48732. }());
  48733. BABYLON.SceneLoader = SceneLoader;
  48734. ;
  48735. })(BABYLON || (BABYLON = {}));
  48736. //# sourceMappingURL=babylon.sceneLoader.js.map
  48737. var BABYLON;
  48738. (function (BABYLON) {
  48739. var Internals;
  48740. (function (Internals) {
  48741. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  48742. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48743. var parsedMaterial = parsedData.materials[index];
  48744. if (parsedMaterial.id === id) {
  48745. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48746. }
  48747. }
  48748. return null;
  48749. };
  48750. var isDescendantOf = function (mesh, names, hierarchyIds) {
  48751. for (var i in names) {
  48752. if (mesh.name === names[i]) {
  48753. hierarchyIds.push(mesh.id);
  48754. return true;
  48755. }
  48756. }
  48757. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  48758. hierarchyIds.push(mesh.id);
  48759. return true;
  48760. }
  48761. return false;
  48762. };
  48763. var logOperation = function (operation, producer) {
  48764. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  48765. };
  48766. BABYLON.SceneLoader.RegisterPlugin({
  48767. name: "babylon.js",
  48768. extensions: ".babylon",
  48769. canDirectLoad: function (data) {
  48770. if (data.indexOf("babylon") !== -1) {
  48771. return true;
  48772. }
  48773. return false;
  48774. },
  48775. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  48776. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48777. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48778. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48779. // and avoid problems with multiple concurrent .babylon loads.
  48780. var log = "importMesh has failed JSON parse";
  48781. try {
  48782. var parsedData = JSON.parse(data);
  48783. log = "";
  48784. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48785. if (!meshesNames) {
  48786. meshesNames = null;
  48787. }
  48788. else if (!Array.isArray(meshesNames)) {
  48789. meshesNames = [meshesNames];
  48790. }
  48791. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48792. var loadedSkeletonsIds = [];
  48793. var loadedMaterialsIds = [];
  48794. var hierarchyIds = [];
  48795. var index;
  48796. var cache;
  48797. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48798. var parsedMesh = parsedData.meshes[index];
  48799. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  48800. if (meshesNames !== null) {
  48801. // Remove found mesh name from list.
  48802. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  48803. }
  48804. //Geometry?
  48805. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  48806. //does the file contain geometries?
  48807. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  48808. //find the correct geometry and add it to the scene
  48809. var found = false;
  48810. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  48811. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  48812. return;
  48813. }
  48814. else {
  48815. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  48816. if (parsedGeometryData.id === parsedMesh.geometryId) {
  48817. switch (geometryType) {
  48818. case "boxes":
  48819. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  48820. break;
  48821. case "spheres":
  48822. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  48823. break;
  48824. case "cylinders":
  48825. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  48826. break;
  48827. case "toruses":
  48828. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  48829. break;
  48830. case "grounds":
  48831. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  48832. break;
  48833. case "planes":
  48834. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  48835. break;
  48836. case "torusKnots":
  48837. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  48838. break;
  48839. case "vertexData":
  48840. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  48841. break;
  48842. }
  48843. found = true;
  48844. }
  48845. });
  48846. }
  48847. });
  48848. if (found === false) {
  48849. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  48850. }
  48851. }
  48852. }
  48853. // Material ?
  48854. if (parsedMesh.materialId) {
  48855. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  48856. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48857. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  48858. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  48859. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  48860. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  48861. var subMatId = parsedMultiMaterial.materials[matIndex];
  48862. loadedMaterialsIds.push(subMatId);
  48863. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  48864. log += "\n\tMaterial " + mat.toString(fullDetails);
  48865. }
  48866. loadedMaterialsIds.push(parsedMultiMaterial.id);
  48867. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48868. materialFound = true;
  48869. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  48870. break;
  48871. }
  48872. }
  48873. }
  48874. if (materialFound === false) {
  48875. loadedMaterialsIds.push(parsedMesh.materialId);
  48876. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  48877. if (!mat) {
  48878. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  48879. }
  48880. else {
  48881. log += "\n\tMaterial " + mat.toString(fullDetails);
  48882. }
  48883. }
  48884. }
  48885. // Skeleton ?
  48886. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48887. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  48888. if (skeletonAlreadyLoaded === false) {
  48889. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  48890. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  48891. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  48892. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48893. skeletons.push(skeleton);
  48894. loadedSkeletonsIds.push(parsedSkeleton.id);
  48895. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  48896. }
  48897. }
  48898. }
  48899. }
  48900. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48901. meshes.push(mesh);
  48902. log += "\n\tMesh " + mesh.toString(fullDetails);
  48903. }
  48904. }
  48905. // Connecting parents
  48906. var currentMesh;
  48907. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48908. currentMesh = scene.meshes[index];
  48909. if (currentMesh._waitingParentId) {
  48910. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  48911. currentMesh._waitingParentId = undefined;
  48912. }
  48913. }
  48914. // freeze and compute world matrix application
  48915. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48916. currentMesh = scene.meshes[index];
  48917. if (currentMesh._waitingFreezeWorldMatrix) {
  48918. currentMesh.freezeWorldMatrix();
  48919. currentMesh._waitingFreezeWorldMatrix = undefined;
  48920. }
  48921. else {
  48922. currentMesh.computeWorldMatrix(true);
  48923. }
  48924. }
  48925. }
  48926. // Particles
  48927. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48928. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48929. var parsedParticleSystem = parsedData.particleSystems[index];
  48930. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  48931. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  48932. }
  48933. }
  48934. }
  48935. return true;
  48936. }
  48937. catch (err) {
  48938. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  48939. log = null;
  48940. throw err;
  48941. }
  48942. finally {
  48943. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48944. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48945. }
  48946. }
  48947. },
  48948. load: function (scene, data, rootUrl) {
  48949. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48950. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48951. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48952. // and avoid problems with multiple concurrent .babylon loads.
  48953. var log = "importScene has failed JSON parse";
  48954. try {
  48955. var parsedData = JSON.parse(data);
  48956. log = "";
  48957. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48958. // Scene
  48959. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  48960. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  48961. }
  48962. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  48963. scene.autoClear = parsedData.autoClear;
  48964. }
  48965. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  48966. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  48967. }
  48968. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  48969. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  48970. }
  48971. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  48972. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  48973. }
  48974. // Fog
  48975. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  48976. scene.fogMode = parsedData.fogMode;
  48977. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  48978. scene.fogStart = parsedData.fogStart;
  48979. scene.fogEnd = parsedData.fogEnd;
  48980. scene.fogDensity = parsedData.fogDensity;
  48981. log += "\tFog mode for scene: ";
  48982. switch (scene.fogMode) {
  48983. // getters not compiling, so using hardcoded
  48984. case 1:
  48985. log += "exp\n";
  48986. break;
  48987. case 2:
  48988. log += "exp2\n";
  48989. break;
  48990. case 3:
  48991. log += "linear\n";
  48992. break;
  48993. }
  48994. }
  48995. //Physics
  48996. if (parsedData.physicsEnabled) {
  48997. var physicsPlugin;
  48998. if (parsedData.physicsEngine === "cannon") {
  48999. physicsPlugin = new BABYLON.CannonJSPlugin();
  49000. }
  49001. else if (parsedData.physicsEngine === "oimo") {
  49002. physicsPlugin = new BABYLON.OimoJSPlugin();
  49003. }
  49004. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  49005. //else - default engine, which is currently oimo
  49006. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  49007. scene.enablePhysics(physicsGravity, physicsPlugin);
  49008. }
  49009. // Metadata
  49010. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  49011. scene.metadata = parsedData.metadata;
  49012. }
  49013. //collisions, if defined. otherwise, default is true
  49014. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  49015. scene.collisionsEnabled = parsedData.collisionsEnabled;
  49016. }
  49017. scene.workerCollisions = !!parsedData.workerCollisions;
  49018. var index;
  49019. var cache;
  49020. // Lights
  49021. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  49022. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  49023. var parsedLight = parsedData.lights[index];
  49024. var light = BABYLON.Light.Parse(parsedLight, scene);
  49025. log += (index === 0 ? "\n\tLights:" : "");
  49026. log += "\n\t\t" + light.toString(fullDetails);
  49027. }
  49028. }
  49029. // Animations
  49030. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  49031. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  49032. var parsedAnimation = parsedData.animations[index];
  49033. var animation = BABYLON.Animation.Parse(parsedAnimation);
  49034. scene.animations.push(animation);
  49035. log += (index === 0 ? "\n\tAnimations:" : "");
  49036. log += "\n\t\t" + animation.toString(fullDetails);
  49037. }
  49038. }
  49039. if (parsedData.autoAnimate) {
  49040. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  49041. }
  49042. // Materials
  49043. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  49044. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49045. var parsedMaterial = parsedData.materials[index];
  49046. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49047. log += (index === 0 ? "\n\tMaterials:" : "");
  49048. log += "\n\t\t" + mat.toString(fullDetails);
  49049. }
  49050. }
  49051. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49052. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  49053. var parsedMultiMaterial = parsedData.multiMaterials[index];
  49054. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49055. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  49056. log += "\n\t\t" + mmat.toString(fullDetails);
  49057. }
  49058. }
  49059. // Morph targets
  49060. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  49061. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  49062. var managerData = _a[_i];
  49063. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  49064. }
  49065. }
  49066. // Skeletons
  49067. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49068. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  49069. var parsedSkeleton = parsedData.skeletons[index];
  49070. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49071. log += (index === 0 ? "\n\tSkeletons:" : "");
  49072. log += "\n\t\t" + skeleton.toString(fullDetails);
  49073. }
  49074. }
  49075. // Geometries
  49076. var geometries = parsedData.geometries;
  49077. if (geometries !== undefined && geometries !== null) {
  49078. // Boxes
  49079. var boxes = geometries.boxes;
  49080. if (boxes !== undefined && boxes !== null) {
  49081. for (index = 0, cache = boxes.length; index < cache; index++) {
  49082. var parsedBox = boxes[index];
  49083. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  49084. }
  49085. }
  49086. // Spheres
  49087. var spheres = geometries.spheres;
  49088. if (spheres !== undefined && spheres !== null) {
  49089. for (index = 0, cache = spheres.length; index < cache; index++) {
  49090. var parsedSphere = spheres[index];
  49091. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  49092. }
  49093. }
  49094. // Cylinders
  49095. var cylinders = geometries.cylinders;
  49096. if (cylinders !== undefined && cylinders !== null) {
  49097. for (index = 0, cache = cylinders.length; index < cache; index++) {
  49098. var parsedCylinder = cylinders[index];
  49099. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  49100. }
  49101. }
  49102. // Toruses
  49103. var toruses = geometries.toruses;
  49104. if (toruses !== undefined && toruses !== null) {
  49105. for (index = 0, cache = toruses.length; index < cache; index++) {
  49106. var parsedTorus = toruses[index];
  49107. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  49108. }
  49109. }
  49110. // Grounds
  49111. var grounds = geometries.grounds;
  49112. if (grounds !== undefined && grounds !== null) {
  49113. for (index = 0, cache = grounds.length; index < cache; index++) {
  49114. var parsedGround = grounds[index];
  49115. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  49116. }
  49117. }
  49118. // Planes
  49119. var planes = geometries.planes;
  49120. if (planes !== undefined && planes !== null) {
  49121. for (index = 0, cache = planes.length; index < cache; index++) {
  49122. var parsedPlane = planes[index];
  49123. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  49124. }
  49125. }
  49126. // TorusKnots
  49127. var torusKnots = geometries.torusKnots;
  49128. if (torusKnots !== undefined && torusKnots !== null) {
  49129. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  49130. var parsedTorusKnot = torusKnots[index];
  49131. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  49132. }
  49133. }
  49134. // VertexData
  49135. var vertexData = geometries.vertexData;
  49136. if (vertexData !== undefined && vertexData !== null) {
  49137. for (index = 0, cache = vertexData.length; index < cache; index++) {
  49138. var parsedVertexData = vertexData[index];
  49139. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  49140. }
  49141. }
  49142. }
  49143. // Meshes
  49144. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49145. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49146. var parsedMesh = parsedData.meshes[index];
  49147. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49148. log += (index === 0 ? "\n\tMeshes:" : "");
  49149. log += "\n\t\t" + mesh.toString(fullDetails);
  49150. }
  49151. }
  49152. // Cameras
  49153. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  49154. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  49155. var parsedCamera = parsedData.cameras[index];
  49156. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  49157. log += (index === 0 ? "\n\tCameras:" : "");
  49158. log += "\n\t\t" + camera.toString(fullDetails);
  49159. }
  49160. }
  49161. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  49162. scene.setActiveCameraByID(parsedData.activeCameraID);
  49163. }
  49164. // Browsing all the graph to connect the dots
  49165. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  49166. var camera = scene.cameras[index];
  49167. if (camera._waitingParentId) {
  49168. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  49169. camera._waitingParentId = undefined;
  49170. }
  49171. }
  49172. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49173. var light = scene.lights[index];
  49174. if (light._waitingParentId) {
  49175. light.parent = scene.getLastEntryByID(light._waitingParentId);
  49176. light._waitingParentId = undefined;
  49177. }
  49178. }
  49179. // Sounds
  49180. var loadedSounds = [];
  49181. var loadedSound;
  49182. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  49183. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  49184. var parsedSound = parsedData.sounds[index];
  49185. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49186. if (!parsedSound.url)
  49187. parsedSound.url = parsedSound.name;
  49188. if (!loadedSounds[parsedSound.url]) {
  49189. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  49190. loadedSounds[parsedSound.url] = loadedSound;
  49191. }
  49192. else {
  49193. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  49194. }
  49195. }
  49196. else {
  49197. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  49198. }
  49199. }
  49200. }
  49201. loadedSounds = [];
  49202. // Connect parents & children and parse actions
  49203. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49204. var mesh = scene.meshes[index];
  49205. if (mesh._waitingParentId) {
  49206. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  49207. mesh._waitingParentId = undefined;
  49208. }
  49209. if (mesh._waitingActions) {
  49210. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  49211. mesh._waitingActions = undefined;
  49212. }
  49213. }
  49214. // freeze world matrix application
  49215. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49216. var currentMesh = scene.meshes[index];
  49217. if (currentMesh._waitingFreezeWorldMatrix) {
  49218. currentMesh.freezeWorldMatrix();
  49219. currentMesh._waitingFreezeWorldMatrix = undefined;
  49220. }
  49221. else {
  49222. currentMesh.computeWorldMatrix(true);
  49223. }
  49224. }
  49225. // Particles Systems
  49226. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49227. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49228. var parsedParticleSystem = parsedData.particleSystems[index];
  49229. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  49230. }
  49231. }
  49232. // Lens flares
  49233. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  49234. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  49235. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  49236. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  49237. }
  49238. }
  49239. // Shadows
  49240. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  49241. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  49242. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  49243. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  49244. }
  49245. }
  49246. // Lights exclusions / inclusions
  49247. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49248. var light = scene.lights[index];
  49249. // Excluded check
  49250. if (light._excludedMeshesIds.length > 0) {
  49251. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  49252. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  49253. if (excludedMesh) {
  49254. light.excludedMeshes.push(excludedMesh);
  49255. }
  49256. }
  49257. light._excludedMeshesIds = [];
  49258. }
  49259. // Included check
  49260. if (light._includedOnlyMeshesIds.length > 0) {
  49261. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  49262. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  49263. if (includedOnlyMesh) {
  49264. light.includedOnlyMeshes.push(includedOnlyMesh);
  49265. }
  49266. }
  49267. light._includedOnlyMeshesIds = [];
  49268. }
  49269. }
  49270. // Actions (scene)
  49271. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  49272. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  49273. }
  49274. // Finish
  49275. return true;
  49276. }
  49277. catch (err) {
  49278. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  49279. log = null;
  49280. throw err;
  49281. }
  49282. finally {
  49283. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49284. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49285. }
  49286. }
  49287. }
  49288. });
  49289. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49290. })(BABYLON || (BABYLON = {}));
  49291. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  49292. var BABYLON;
  49293. (function (BABYLON) {
  49294. var FilesInput = (function () {
  49295. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  49296. this.onProcessFileCallback = function () { return true; };
  49297. this._engine = engine;
  49298. this._currentScene = scene;
  49299. this._sceneLoadedCallback = sceneLoadedCallback;
  49300. this._progressCallback = progressCallback;
  49301. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  49302. this._textureLoadingCallback = textureLoadingCallback;
  49303. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  49304. this._onReloadCallback = onReloadCallback;
  49305. }
  49306. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  49307. var _this = this;
  49308. if (elementToMonitor) {
  49309. this._elementToMonitor = elementToMonitor;
  49310. this._dragEnterHandler = function (e) { _this.drag(e); };
  49311. this._dragOverHandler = function (e) { _this.drag(e); };
  49312. this._dropHandler = function (e) { _this.drop(e); };
  49313. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  49314. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  49315. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  49316. }
  49317. };
  49318. FilesInput.prototype.dispose = function () {
  49319. if (!this._elementToMonitor) {
  49320. return;
  49321. }
  49322. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  49323. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  49324. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  49325. };
  49326. FilesInput.prototype.renderFunction = function () {
  49327. if (this._additionalRenderLoopLogicCallback) {
  49328. this._additionalRenderLoopLogicCallback();
  49329. }
  49330. if (this._currentScene) {
  49331. if (this._textureLoadingCallback) {
  49332. var remaining = this._currentScene.getWaitingItemsCount();
  49333. if (remaining > 0) {
  49334. this._textureLoadingCallback(remaining);
  49335. }
  49336. }
  49337. this._currentScene.render();
  49338. }
  49339. };
  49340. FilesInput.prototype.drag = function (e) {
  49341. e.stopPropagation();
  49342. e.preventDefault();
  49343. };
  49344. FilesInput.prototype.drop = function (eventDrop) {
  49345. eventDrop.stopPropagation();
  49346. eventDrop.preventDefault();
  49347. this.loadFiles(eventDrop);
  49348. };
  49349. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  49350. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  49351. reader.readEntries(function (fileEntries) {
  49352. var remaining = fileEntries.length;
  49353. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  49354. var fileEntry = fileEntries_1[_i];
  49355. if (fileEntry.isFile) {
  49356. fileEntry.file(function (file) {
  49357. file.correctName = relativePath + file.name;
  49358. files.push(file);
  49359. remaining--;
  49360. if (remaining === 0) {
  49361. callback();
  49362. }
  49363. });
  49364. }
  49365. else {
  49366. remaining--;
  49367. if (remaining === 0) {
  49368. callback();
  49369. }
  49370. }
  49371. }
  49372. });
  49373. };
  49374. FilesInput.prototype._processFiles = function (files) {
  49375. var skippedFiles = 0;
  49376. for (var i = 0; i < files.length; i++) {
  49377. var name = files[i].correctName.toLowerCase();
  49378. var extension = name.split('.').pop();
  49379. if (!this.onProcessFileCallback(files[i], name, extension)) {
  49380. skippedFiles++;
  49381. continue;
  49382. }
  49383. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  49384. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  49385. this._sceneFileToLoad = files[i];
  49386. }
  49387. else {
  49388. FilesInput.FilesToLoad[name] = files[i];
  49389. }
  49390. }
  49391. if (this._onReloadCallback) {
  49392. this._onReloadCallback(this._sceneFileToLoad);
  49393. }
  49394. else if (skippedFiles < files.length) {
  49395. this.reload();
  49396. }
  49397. };
  49398. FilesInput.prototype.loadFiles = function (event) {
  49399. var _this = this;
  49400. if (this._startingProcessingFilesCallback)
  49401. this._startingProcessingFilesCallback();
  49402. // Handling data transfer via drag'n'drop
  49403. if (event && event.dataTransfer && event.dataTransfer.files) {
  49404. this._filesToLoad = event.dataTransfer.files;
  49405. }
  49406. // Handling files from input files
  49407. if (event && event.target && event.target.files) {
  49408. this._filesToLoad = event.target.files;
  49409. }
  49410. if (this._filesToLoad && this._filesToLoad.length > 0) {
  49411. var files_1 = [];
  49412. var folders = [];
  49413. var items = event.dataTransfer ? event.dataTransfer.items : null;
  49414. for (var i = 0; i < this._filesToLoad.length; i++) {
  49415. var fileToLoad = this._filesToLoad[i];
  49416. var name_1 = fileToLoad.name.toLowerCase();
  49417. var type = fileToLoad.type;
  49418. var entry = void 0;
  49419. fileToLoad.correctName = name_1;
  49420. if (items) {
  49421. var item = items[i];
  49422. if (item.getAsEntry) {
  49423. entry = item.getAsEntry();
  49424. }
  49425. else if (item.webkitGetAsEntry) {
  49426. entry = item.webkitGetAsEntry();
  49427. }
  49428. }
  49429. if (!entry) {
  49430. files_1.push(fileToLoad);
  49431. }
  49432. else {
  49433. if (entry.isDirectory) {
  49434. folders.push(entry);
  49435. }
  49436. else {
  49437. files_1.push(fileToLoad);
  49438. }
  49439. }
  49440. }
  49441. if (folders.length === 0) {
  49442. this._processFiles(files_1);
  49443. }
  49444. else {
  49445. var remaining = folders.length;
  49446. // Extract folder content
  49447. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  49448. var folder = folders_1[_i];
  49449. this._handleFolderDrop(folder, files_1, function () {
  49450. remaining--;
  49451. if (remaining === 0) {
  49452. _this._processFiles(files_1);
  49453. }
  49454. });
  49455. }
  49456. }
  49457. }
  49458. };
  49459. FilesInput.prototype.reload = function () {
  49460. var _this = this;
  49461. // If a ".babylon" file has been provided
  49462. if (this._sceneFileToLoad) {
  49463. if (this._currentScene) {
  49464. if (BABYLON.Tools.errorsCount > 0) {
  49465. BABYLON.Tools.ClearLogCache();
  49466. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  49467. }
  49468. this._engine.stopRenderLoop();
  49469. this._currentScene.dispose();
  49470. }
  49471. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  49472. _this._currentScene = newScene;
  49473. if (_this._sceneLoadedCallback) {
  49474. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  49475. }
  49476. // Wait for textures and shaders to be ready
  49477. _this._currentScene.executeWhenReady(function () {
  49478. _this._engine.runRenderLoop(function () {
  49479. _this.renderFunction();
  49480. });
  49481. });
  49482. }, function (progress) {
  49483. if (_this._progressCallback) {
  49484. _this._progressCallback(progress);
  49485. }
  49486. });
  49487. }
  49488. else {
  49489. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  49490. }
  49491. };
  49492. FilesInput.FilesToLoad = new Array();
  49493. return FilesInput;
  49494. }());
  49495. BABYLON.FilesInput = FilesInput;
  49496. })(BABYLON || (BABYLON = {}));
  49497. //# sourceMappingURL=babylon.filesInput.js.map
  49498. var BABYLON;
  49499. (function (BABYLON) {
  49500. /**
  49501. * This class implement a typical dictionary using a string as key and the generic type T as value.
  49502. * The underlying implementation relies on an associative array to ensure the best performances.
  49503. * The value can be anything including 'null' but except 'undefined'
  49504. */
  49505. var StringDictionary = (function () {
  49506. function StringDictionary() {
  49507. this._count = 0;
  49508. this._data = {};
  49509. }
  49510. /**
  49511. * This will clear this dictionary and copy the content from the 'source' one.
  49512. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  49513. * @param source the dictionary to take the content from and copy to this dictionary
  49514. */
  49515. StringDictionary.prototype.copyFrom = function (source) {
  49516. var _this = this;
  49517. this.clear();
  49518. source.forEach(function (t, v) { return _this.add(t, v); });
  49519. };
  49520. /**
  49521. * Get a value based from its key
  49522. * @param key the given key to get the matching value from
  49523. * @return the value if found, otherwise undefined is returned
  49524. */
  49525. StringDictionary.prototype.get = function (key) {
  49526. var val = this._data[key];
  49527. if (val !== undefined) {
  49528. return val;
  49529. }
  49530. return undefined;
  49531. };
  49532. /**
  49533. * Get a value from its key or add it if it doesn't exist.
  49534. * This method will ensure you that a given key/data will be present in the dictionary.
  49535. * @param key the given key to get the matching value from
  49536. * @param factory the factory that will create the value if the key is not present in the dictionary.
  49537. * The factory will only be invoked if there's no data for the given key.
  49538. * @return the value corresponding to the key.
  49539. */
  49540. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  49541. var val = this.get(key);
  49542. if (val !== undefined) {
  49543. return val;
  49544. }
  49545. val = factory(key);
  49546. if (val) {
  49547. this.add(key, val);
  49548. }
  49549. return val;
  49550. };
  49551. /**
  49552. * Get a value from its key if present in the dictionary otherwise add it
  49553. * @param key the key to get the value from
  49554. * @param val if there's no such key/value pair in the dictionary add it with this value
  49555. * @return the value corresponding to the key
  49556. */
  49557. StringDictionary.prototype.getOrAdd = function (key, val) {
  49558. var curVal = this.get(key);
  49559. if (curVal !== undefined) {
  49560. return curVal;
  49561. }
  49562. this.add(key, val);
  49563. return val;
  49564. };
  49565. /**
  49566. * Check if there's a given key in the dictionary
  49567. * @param key the key to check for
  49568. * @return true if the key is present, false otherwise
  49569. */
  49570. StringDictionary.prototype.contains = function (key) {
  49571. return this._data[key] !== undefined;
  49572. };
  49573. /**
  49574. * Add a new key and its corresponding value
  49575. * @param key the key to add
  49576. * @param value the value corresponding to the key
  49577. * @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
  49578. */
  49579. StringDictionary.prototype.add = function (key, value) {
  49580. if (this._data[key] !== undefined) {
  49581. return false;
  49582. }
  49583. this._data[key] = value;
  49584. ++this._count;
  49585. return true;
  49586. };
  49587. StringDictionary.prototype.set = function (key, value) {
  49588. if (this._data[key] === undefined) {
  49589. return false;
  49590. }
  49591. this._data[key] = value;
  49592. return true;
  49593. };
  49594. /**
  49595. * Get the element of the given key and remove it from the dictionary
  49596. * @param key
  49597. */
  49598. StringDictionary.prototype.getAndRemove = function (key) {
  49599. var val = this.get(key);
  49600. if (val !== undefined) {
  49601. delete this._data[key];
  49602. --this._count;
  49603. return val;
  49604. }
  49605. return null;
  49606. };
  49607. /**
  49608. * Remove a key/value from the dictionary.
  49609. * @param key the key to remove
  49610. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  49611. */
  49612. StringDictionary.prototype.remove = function (key) {
  49613. if (this.contains(key)) {
  49614. delete this._data[key];
  49615. --this._count;
  49616. return true;
  49617. }
  49618. return false;
  49619. };
  49620. /**
  49621. * Clear the whole content of the dictionary
  49622. */
  49623. StringDictionary.prototype.clear = function () {
  49624. this._data = {};
  49625. this._count = 0;
  49626. };
  49627. Object.defineProperty(StringDictionary.prototype, "count", {
  49628. get: function () {
  49629. return this._count;
  49630. },
  49631. enumerable: true,
  49632. configurable: true
  49633. });
  49634. /**
  49635. * Execute a callback on each key/val of the dictionary.
  49636. * Note that you can remove any element in this dictionary in the callback implementation
  49637. * @param callback the callback to execute on a given key/value pair
  49638. */
  49639. StringDictionary.prototype.forEach = function (callback) {
  49640. for (var cur in this._data) {
  49641. var val = this._data[cur];
  49642. callback(cur, val);
  49643. }
  49644. };
  49645. /**
  49646. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  49647. * If the callback returns null or undefined the method will iterate to the next key/value pair
  49648. * Note that you can remove any element in this dictionary in the callback implementation
  49649. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  49650. */
  49651. StringDictionary.prototype.first = function (callback) {
  49652. for (var cur in this._data) {
  49653. var val = this._data[cur];
  49654. var res = callback(cur, val);
  49655. if (res) {
  49656. return res;
  49657. }
  49658. }
  49659. return null;
  49660. };
  49661. return StringDictionary;
  49662. }());
  49663. BABYLON.StringDictionary = StringDictionary;
  49664. })(BABYLON || (BABYLON = {}));
  49665. //# sourceMappingURL=babylon.stringDictionary.js.map
  49666. var BABYLON;
  49667. (function (BABYLON) {
  49668. var Tags = (function () {
  49669. function Tags() {
  49670. }
  49671. Tags.EnableFor = function (obj) {
  49672. obj._tags = obj._tags || {};
  49673. obj.hasTags = function () {
  49674. return Tags.HasTags(obj);
  49675. };
  49676. obj.addTags = function (tagsString) {
  49677. return Tags.AddTagsTo(obj, tagsString);
  49678. };
  49679. obj.removeTags = function (tagsString) {
  49680. return Tags.RemoveTagsFrom(obj, tagsString);
  49681. };
  49682. obj.matchesTagsQuery = function (tagsQuery) {
  49683. return Tags.MatchesQuery(obj, tagsQuery);
  49684. };
  49685. };
  49686. Tags.DisableFor = function (obj) {
  49687. delete obj._tags;
  49688. delete obj.hasTags;
  49689. delete obj.addTags;
  49690. delete obj.removeTags;
  49691. delete obj.matchesTagsQuery;
  49692. };
  49693. Tags.HasTags = function (obj) {
  49694. if (!obj._tags) {
  49695. return false;
  49696. }
  49697. return !BABYLON.Tools.IsEmpty(obj._tags);
  49698. };
  49699. Tags.GetTags = function (obj, asString) {
  49700. if (asString === void 0) { asString = true; }
  49701. if (!obj._tags) {
  49702. return null;
  49703. }
  49704. if (asString) {
  49705. var tagsArray = [];
  49706. for (var tag in obj._tags) {
  49707. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  49708. tagsArray.push(tag);
  49709. }
  49710. }
  49711. return tagsArray.join(" ");
  49712. }
  49713. else {
  49714. return obj._tags;
  49715. }
  49716. };
  49717. // the tags 'true' and 'false' are reserved and cannot be used as tags
  49718. // a tag cannot start with '||', '&&', and '!'
  49719. // it cannot contain whitespaces
  49720. Tags.AddTagsTo = function (obj, tagsString) {
  49721. if (!tagsString) {
  49722. return;
  49723. }
  49724. if (typeof tagsString !== "string") {
  49725. return;
  49726. }
  49727. var tags = tagsString.split(" ");
  49728. tags.forEach(function (tag, index, array) {
  49729. Tags._AddTagTo(obj, tag);
  49730. });
  49731. };
  49732. Tags._AddTagTo = function (obj, tag) {
  49733. tag = tag.trim();
  49734. if (tag === "" || tag === "true" || tag === "false") {
  49735. return;
  49736. }
  49737. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  49738. return;
  49739. }
  49740. Tags.EnableFor(obj);
  49741. obj._tags[tag] = true;
  49742. };
  49743. Tags.RemoveTagsFrom = function (obj, tagsString) {
  49744. if (!Tags.HasTags(obj)) {
  49745. return;
  49746. }
  49747. var tags = tagsString.split(" ");
  49748. for (var t in tags) {
  49749. Tags._RemoveTagFrom(obj, tags[t]);
  49750. }
  49751. };
  49752. Tags._RemoveTagFrom = function (obj, tag) {
  49753. delete obj._tags[tag];
  49754. };
  49755. Tags.MatchesQuery = function (obj, tagsQuery) {
  49756. if (tagsQuery === undefined) {
  49757. return true;
  49758. }
  49759. if (tagsQuery === "") {
  49760. return Tags.HasTags(obj);
  49761. }
  49762. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  49763. };
  49764. return Tags;
  49765. }());
  49766. BABYLON.Tags = Tags;
  49767. })(BABYLON || (BABYLON = {}));
  49768. //# sourceMappingURL=babylon.tags.js.map
  49769. var BABYLON;
  49770. (function (BABYLON) {
  49771. var Internals;
  49772. (function (Internals) {
  49773. var AndOrNotEvaluator = (function () {
  49774. function AndOrNotEvaluator() {
  49775. }
  49776. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  49777. if (!query.match(/\([^\(\)]*\)/g)) {
  49778. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  49779. }
  49780. else {
  49781. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  49782. // remove parenthesis
  49783. r = r.slice(1, r.length - 1);
  49784. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  49785. });
  49786. }
  49787. if (query === "true") {
  49788. return true;
  49789. }
  49790. if (query === "false") {
  49791. return false;
  49792. }
  49793. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  49794. };
  49795. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  49796. evaluateCallback = evaluateCallback || (function (r) {
  49797. return r === "true" ? true : false;
  49798. });
  49799. var result;
  49800. var or = parenthesisContent.split("||");
  49801. for (var i in or) {
  49802. if (or.hasOwnProperty(i)) {
  49803. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  49804. var and = ori.split("&&");
  49805. if (and.length > 1) {
  49806. for (var j = 0; j < and.length; ++j) {
  49807. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  49808. if (andj !== "true" && andj !== "false") {
  49809. if (andj[0] === "!") {
  49810. result = !evaluateCallback(andj.substring(1));
  49811. }
  49812. else {
  49813. result = evaluateCallback(andj);
  49814. }
  49815. }
  49816. else {
  49817. result = andj === "true" ? true : false;
  49818. }
  49819. if (!result) {
  49820. ori = "false";
  49821. break;
  49822. }
  49823. }
  49824. }
  49825. if (result || ori === "true") {
  49826. result = true;
  49827. break;
  49828. }
  49829. // result equals false (or undefined)
  49830. if (ori !== "true" && ori !== "false") {
  49831. if (ori[0] === "!") {
  49832. result = !evaluateCallback(ori.substring(1));
  49833. }
  49834. else {
  49835. result = evaluateCallback(ori);
  49836. }
  49837. }
  49838. else {
  49839. result = ori === "true" ? true : false;
  49840. }
  49841. }
  49842. }
  49843. // the whole parenthesis scope is replaced by 'true' or 'false'
  49844. return result ? "true" : "false";
  49845. };
  49846. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  49847. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  49848. // remove whitespaces
  49849. r = r.replace(/[\s]/g, function () { return ""; });
  49850. return r.length % 2 ? "!" : "";
  49851. });
  49852. booleanString = booleanString.trim();
  49853. if (booleanString === "!true") {
  49854. booleanString = "false";
  49855. }
  49856. else if (booleanString === "!false") {
  49857. booleanString = "true";
  49858. }
  49859. return booleanString;
  49860. };
  49861. return AndOrNotEvaluator;
  49862. }());
  49863. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  49864. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49865. })(BABYLON || (BABYLON = {}));
  49866. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  49867. var BABYLON;
  49868. (function (BABYLON) {
  49869. var Database = (function () {
  49870. function Database(urlToScene, callbackManifestChecked) {
  49871. // Handling various flavors of prefixed version of IndexedDB
  49872. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  49873. this.callbackManifestChecked = callbackManifestChecked;
  49874. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  49875. this.db = null;
  49876. this.enableSceneOffline = false;
  49877. this.enableTexturesOffline = false;
  49878. this.manifestVersionFound = 0;
  49879. this.mustUpdateRessources = false;
  49880. this.hasReachedQuota = false;
  49881. if (!Database.IDBStorageEnabled) {
  49882. this.callbackManifestChecked(true);
  49883. }
  49884. else {
  49885. this.checkManifestFile();
  49886. }
  49887. }
  49888. Database.prototype.checkManifestFile = function () {
  49889. var _this = this;
  49890. function noManifestFile() {
  49891. that.enableSceneOffline = false;
  49892. that.enableTexturesOffline = false;
  49893. that.callbackManifestChecked(false);
  49894. }
  49895. var that = this;
  49896. var timeStampUsed = false;
  49897. var manifestURL = this.currentSceneUrl + ".manifest";
  49898. var xhr = new XMLHttpRequest();
  49899. if (navigator.onLine) {
  49900. // Adding a timestamp to by-pass browsers' cache
  49901. timeStampUsed = true;
  49902. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  49903. }
  49904. xhr.open("GET", manifestURL, true);
  49905. xhr.addEventListener("load", function () {
  49906. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  49907. try {
  49908. var manifestFile = JSON.parse(xhr.response);
  49909. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  49910. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  49911. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  49912. _this.manifestVersionFound = manifestFile.version;
  49913. }
  49914. if (_this.callbackManifestChecked) {
  49915. _this.callbackManifestChecked(true);
  49916. }
  49917. }
  49918. catch (ex) {
  49919. noManifestFile();
  49920. }
  49921. }
  49922. else {
  49923. noManifestFile();
  49924. }
  49925. }, false);
  49926. xhr.addEventListener("error", function (event) {
  49927. if (timeStampUsed) {
  49928. timeStampUsed = false;
  49929. // Let's retry without the timeStamp
  49930. // It could fail when coupled with HTML5 Offline API
  49931. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  49932. xhr.open("GET", retryManifestURL, true);
  49933. xhr.send();
  49934. }
  49935. else {
  49936. noManifestFile();
  49937. }
  49938. }, false);
  49939. try {
  49940. xhr.send();
  49941. }
  49942. catch (ex) {
  49943. BABYLON.Tools.Error("Error on XHR send request.");
  49944. that.callbackManifestChecked(false);
  49945. }
  49946. };
  49947. Database.prototype.openAsync = function (successCallback, errorCallback) {
  49948. var _this = this;
  49949. function handleError() {
  49950. that.isSupported = false;
  49951. if (errorCallback)
  49952. errorCallback();
  49953. }
  49954. var that = this;
  49955. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  49956. // Your browser doesn't support IndexedDB
  49957. this.isSupported = false;
  49958. if (errorCallback)
  49959. errorCallback();
  49960. }
  49961. else {
  49962. // If the DB hasn't been opened or created yet
  49963. if (!this.db) {
  49964. this.hasReachedQuota = false;
  49965. this.isSupported = true;
  49966. var request = this.idbFactory.open("babylonjs", 1);
  49967. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  49968. request.onerror = function (event) {
  49969. handleError();
  49970. };
  49971. // executes when a version change transaction cannot complete due to other active transactions
  49972. request.onblocked = function (event) {
  49973. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  49974. handleError();
  49975. };
  49976. // DB has been opened successfully
  49977. request.onsuccess = function (event) {
  49978. _this.db = request.result;
  49979. successCallback();
  49980. };
  49981. // Initialization of the DB. Creating Scenes & Textures stores
  49982. request.onupgradeneeded = function (event) {
  49983. _this.db = (event.target).result;
  49984. try {
  49985. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  49986. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  49987. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  49988. }
  49989. catch (ex) {
  49990. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  49991. handleError();
  49992. }
  49993. };
  49994. }
  49995. else {
  49996. if (successCallback)
  49997. successCallback();
  49998. }
  49999. }
  50000. };
  50001. Database.prototype.loadImageFromDB = function (url, image) {
  50002. var _this = this;
  50003. var completeURL = Database.ReturnFullUrlLocation(url);
  50004. var saveAndLoadImage = function () {
  50005. if (!_this.hasReachedQuota && _this.db !== null) {
  50006. // the texture is not yet in the DB, let's try to save it
  50007. _this._saveImageIntoDBAsync(completeURL, image);
  50008. }
  50009. else {
  50010. image.src = url;
  50011. }
  50012. };
  50013. if (!this.mustUpdateRessources) {
  50014. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  50015. }
  50016. else {
  50017. saveAndLoadImage();
  50018. }
  50019. };
  50020. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  50021. if (this.isSupported && this.db !== null) {
  50022. var texture;
  50023. var transaction = this.db.transaction(["textures"]);
  50024. transaction.onabort = function (event) {
  50025. image.src = url;
  50026. };
  50027. transaction.oncomplete = function (event) {
  50028. var blobTextureURL;
  50029. if (texture) {
  50030. var URL = window.URL || window.webkitURL;
  50031. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  50032. image.onerror = function () {
  50033. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  50034. image.src = url;
  50035. };
  50036. image.src = blobTextureURL;
  50037. }
  50038. else {
  50039. notInDBCallback();
  50040. }
  50041. };
  50042. var getRequest = transaction.objectStore("textures").get(url);
  50043. getRequest.onsuccess = function (event) {
  50044. texture = (event.target).result;
  50045. };
  50046. getRequest.onerror = function (event) {
  50047. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  50048. image.src = url;
  50049. };
  50050. }
  50051. else {
  50052. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50053. image.src = url;
  50054. }
  50055. };
  50056. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  50057. var _this = this;
  50058. if (this.isSupported) {
  50059. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  50060. var generateBlobUrl = function () {
  50061. var blobTextureURL;
  50062. if (blob) {
  50063. var URL = window.URL || window.webkitURL;
  50064. try {
  50065. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  50066. }
  50067. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  50068. catch (ex) {
  50069. blobTextureURL = URL.createObjectURL(blob);
  50070. }
  50071. }
  50072. image.src = blobTextureURL;
  50073. };
  50074. if (Database.IsUASupportingBlobStorage) {
  50075. var xhr = new XMLHttpRequest(), blob;
  50076. xhr.open("GET", url, true);
  50077. xhr.responseType = "blob";
  50078. xhr.addEventListener("load", function () {
  50079. if (xhr.status === 200) {
  50080. // Blob as response (XHR2)
  50081. blob = xhr.response;
  50082. var transaction = _this.db.transaction(["textures"], "readwrite");
  50083. // the transaction could abort because of a QuotaExceededError error
  50084. transaction.onabort = function (event) {
  50085. try {
  50086. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  50087. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50088. _this.hasReachedQuota = true;
  50089. }
  50090. }
  50091. catch (ex) { }
  50092. generateBlobUrl();
  50093. };
  50094. transaction.oncomplete = function (event) {
  50095. generateBlobUrl();
  50096. };
  50097. var newTexture = { textureUrl: url, data: blob };
  50098. try {
  50099. // Put the blob into the dabase
  50100. var addRequest = transaction.objectStore("textures").put(newTexture);
  50101. addRequest.onsuccess = function (event) {
  50102. };
  50103. addRequest.onerror = function (event) {
  50104. generateBlobUrl();
  50105. };
  50106. }
  50107. catch (ex) {
  50108. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  50109. if (ex.code === 25) {
  50110. Database.IsUASupportingBlobStorage = false;
  50111. }
  50112. image.src = url;
  50113. }
  50114. }
  50115. else {
  50116. image.src = url;
  50117. }
  50118. }, false);
  50119. xhr.addEventListener("error", function (event) {
  50120. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  50121. image.src = url;
  50122. }, false);
  50123. xhr.send();
  50124. }
  50125. else {
  50126. image.src = url;
  50127. }
  50128. }
  50129. else {
  50130. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50131. image.src = url;
  50132. }
  50133. };
  50134. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  50135. var _this = this;
  50136. var updateVersion = function (event) {
  50137. // the version is not yet in the DB or we need to update it
  50138. _this._saveVersionIntoDBAsync(url, versionLoaded);
  50139. };
  50140. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  50141. };
  50142. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  50143. var _this = this;
  50144. if (this.isSupported) {
  50145. var version;
  50146. try {
  50147. var transaction = this.db.transaction(["versions"]);
  50148. transaction.oncomplete = function (event) {
  50149. if (version) {
  50150. // If the version in the JSON file is > than the version in DB
  50151. if (_this.manifestVersionFound > version.data) {
  50152. _this.mustUpdateRessources = true;
  50153. updateInDBCallback();
  50154. }
  50155. else {
  50156. callback(version.data);
  50157. }
  50158. }
  50159. else {
  50160. _this.mustUpdateRessources = true;
  50161. updateInDBCallback();
  50162. }
  50163. };
  50164. transaction.onabort = function (event) {
  50165. callback(-1);
  50166. };
  50167. var getRequest = transaction.objectStore("versions").get(url);
  50168. getRequest.onsuccess = function (event) {
  50169. version = (event.target).result;
  50170. };
  50171. getRequest.onerror = function (event) {
  50172. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  50173. callback(-1);
  50174. };
  50175. }
  50176. catch (ex) {
  50177. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  50178. callback(-1);
  50179. }
  50180. }
  50181. else {
  50182. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50183. callback(-1);
  50184. }
  50185. };
  50186. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  50187. var _this = this;
  50188. if (this.isSupported && !this.hasReachedQuota) {
  50189. try {
  50190. // Open a transaction to the database
  50191. var transaction = this.db.transaction(["versions"], "readwrite");
  50192. // the transaction could abort because of a QuotaExceededError error
  50193. transaction.onabort = function (event) {
  50194. try {
  50195. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50196. _this.hasReachedQuota = true;
  50197. }
  50198. }
  50199. catch (ex) { }
  50200. callback(-1);
  50201. };
  50202. transaction.oncomplete = function (event) {
  50203. callback(_this.manifestVersionFound);
  50204. };
  50205. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  50206. // Put the scene into the database
  50207. var addRequest = transaction.objectStore("versions").put(newVersion);
  50208. addRequest.onsuccess = function (event) {
  50209. };
  50210. addRequest.onerror = function (event) {
  50211. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  50212. };
  50213. }
  50214. catch (ex) {
  50215. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  50216. callback(-1);
  50217. }
  50218. }
  50219. else {
  50220. callback(-1);
  50221. }
  50222. };
  50223. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  50224. var _this = this;
  50225. var completeUrl = Database.ReturnFullUrlLocation(url);
  50226. var saveAndLoadFile = function (event) {
  50227. // the scene is not yet in the DB, let's try to save it
  50228. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  50229. };
  50230. this._checkVersionFromDB(completeUrl, function (version) {
  50231. if (version !== -1) {
  50232. if (!_this.mustUpdateRessources) {
  50233. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  50234. }
  50235. else {
  50236. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  50237. }
  50238. }
  50239. else {
  50240. errorCallback();
  50241. }
  50242. });
  50243. };
  50244. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  50245. if (this.isSupported) {
  50246. var targetStore;
  50247. if (url.indexOf(".babylon") !== -1) {
  50248. targetStore = "scenes";
  50249. }
  50250. else {
  50251. targetStore = "textures";
  50252. }
  50253. var file;
  50254. var transaction = this.db.transaction([targetStore]);
  50255. transaction.oncomplete = function (event) {
  50256. if (file) {
  50257. callback(file.data);
  50258. }
  50259. else {
  50260. notInDBCallback();
  50261. }
  50262. };
  50263. transaction.onabort = function (event) {
  50264. notInDBCallback();
  50265. };
  50266. var getRequest = transaction.objectStore(targetStore).get(url);
  50267. getRequest.onsuccess = function (event) {
  50268. file = (event.target).result;
  50269. };
  50270. getRequest.onerror = function (event) {
  50271. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  50272. notInDBCallback();
  50273. };
  50274. }
  50275. else {
  50276. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50277. callback();
  50278. }
  50279. };
  50280. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  50281. var _this = this;
  50282. if (this.isSupported) {
  50283. var targetStore;
  50284. if (url.indexOf(".babylon") !== -1) {
  50285. targetStore = "scenes";
  50286. }
  50287. else {
  50288. targetStore = "textures";
  50289. }
  50290. // Create XHR
  50291. var xhr = new XMLHttpRequest(), fileData;
  50292. xhr.open("GET", url, true);
  50293. if (useArrayBuffer) {
  50294. xhr.responseType = "arraybuffer";
  50295. }
  50296. xhr.onprogress = progressCallback;
  50297. xhr.addEventListener("load", function () {
  50298. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  50299. // Blob as response (XHR2)
  50300. //fileData = xhr.responseText;
  50301. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  50302. if (!_this.hasReachedQuota) {
  50303. // Open a transaction to the database
  50304. var transaction = _this.db.transaction([targetStore], "readwrite");
  50305. // the transaction could abort because of a QuotaExceededError error
  50306. transaction.onabort = function (event) {
  50307. try {
  50308. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  50309. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50310. _this.hasReachedQuota = true;
  50311. }
  50312. }
  50313. catch (ex) { }
  50314. callback(fileData);
  50315. };
  50316. transaction.oncomplete = function (event) {
  50317. callback(fileData);
  50318. };
  50319. var newFile;
  50320. if (targetStore === "scenes") {
  50321. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  50322. }
  50323. else {
  50324. newFile = { textureUrl: url, data: fileData };
  50325. }
  50326. try {
  50327. // Put the scene into the database
  50328. var addRequest = transaction.objectStore(targetStore).put(newFile);
  50329. addRequest.onsuccess = function (event) {
  50330. };
  50331. addRequest.onerror = function (event) {
  50332. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  50333. };
  50334. }
  50335. catch (ex) {
  50336. callback(fileData);
  50337. }
  50338. }
  50339. else {
  50340. callback(fileData);
  50341. }
  50342. }
  50343. else {
  50344. callback();
  50345. }
  50346. }, false);
  50347. xhr.addEventListener("error", function (event) {
  50348. BABYLON.Tools.Error("error on XHR request.");
  50349. callback();
  50350. }, false);
  50351. xhr.send();
  50352. }
  50353. else {
  50354. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50355. callback();
  50356. }
  50357. };
  50358. Database.IsUASupportingBlobStorage = true;
  50359. Database.IDBStorageEnabled = true;
  50360. Database.parseURL = function (url) {
  50361. var a = document.createElement('a');
  50362. a.href = url;
  50363. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  50364. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  50365. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  50366. return absLocation;
  50367. };
  50368. Database.ReturnFullUrlLocation = function (url) {
  50369. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  50370. return (Database.parseURL(window.location.href) + url);
  50371. }
  50372. else {
  50373. return url;
  50374. }
  50375. };
  50376. return Database;
  50377. }());
  50378. BABYLON.Database = Database;
  50379. })(BABYLON || (BABYLON = {}));
  50380. //# sourceMappingURL=babylon.database.js.map
  50381. var BABYLON;
  50382. (function (BABYLON) {
  50383. var FresnelParameters = (function () {
  50384. function FresnelParameters() {
  50385. this._isEnabled = true;
  50386. this.leftColor = BABYLON.Color3.White();
  50387. this.rightColor = BABYLON.Color3.Black();
  50388. this.bias = 0;
  50389. this.power = 1;
  50390. }
  50391. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  50392. get: function () {
  50393. return this._isEnabled;
  50394. },
  50395. set: function (value) {
  50396. if (this._isEnabled === value) {
  50397. return;
  50398. }
  50399. this._isEnabled = value;
  50400. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  50401. },
  50402. enumerable: true,
  50403. configurable: true
  50404. });
  50405. FresnelParameters.prototype.clone = function () {
  50406. var newFresnelParameters = new FresnelParameters();
  50407. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  50408. return newFresnelParameters;
  50409. };
  50410. FresnelParameters.prototype.serialize = function () {
  50411. var serializationObject = {};
  50412. serializationObject.isEnabled = this.isEnabled;
  50413. serializationObject.leftColor = this.leftColor;
  50414. serializationObject.rightColor = this.rightColor;
  50415. serializationObject.bias = this.bias;
  50416. serializationObject.power = this.power;
  50417. return serializationObject;
  50418. };
  50419. FresnelParameters.Parse = function (parsedFresnelParameters) {
  50420. var fresnelParameters = new FresnelParameters();
  50421. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  50422. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  50423. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  50424. fresnelParameters.bias = parsedFresnelParameters.bias;
  50425. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  50426. return fresnelParameters;
  50427. };
  50428. return FresnelParameters;
  50429. }());
  50430. BABYLON.FresnelParameters = FresnelParameters;
  50431. })(BABYLON || (BABYLON = {}));
  50432. //# sourceMappingURL=babylon.fresnelParameters.js.map
  50433. var BABYLON;
  50434. (function (BABYLON) {
  50435. var MultiMaterial = (function (_super) {
  50436. __extends(MultiMaterial, _super);
  50437. function MultiMaterial(name, scene) {
  50438. var _this = _super.call(this, name, scene, true) || this;
  50439. scene.multiMaterials.push(_this);
  50440. _this.subMaterials = new Array();
  50441. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  50442. return _this;
  50443. }
  50444. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  50445. get: function () {
  50446. return this._subMaterials;
  50447. },
  50448. set: function (value) {
  50449. this._subMaterials = value;
  50450. this._hookArray(value);
  50451. },
  50452. enumerable: true,
  50453. configurable: true
  50454. });
  50455. MultiMaterial.prototype._hookArray = function (array) {
  50456. var _this = this;
  50457. var oldPush = array.push;
  50458. array.push = function () {
  50459. var items = [];
  50460. for (var _i = 0; _i < arguments.length; _i++) {
  50461. items[_i] = arguments[_i];
  50462. }
  50463. var result = oldPush.apply(array, items);
  50464. _this._markAllSubMeshesAsTexturesDirty();
  50465. return result;
  50466. };
  50467. var oldSplice = array.splice;
  50468. array.splice = function (index, deleteCount) {
  50469. var deleted = oldSplice.apply(array, [index, deleteCount]);
  50470. _this._markAllSubMeshesAsTexturesDirty();
  50471. return deleted;
  50472. };
  50473. };
  50474. // Properties
  50475. MultiMaterial.prototype.getSubMaterial = function (index) {
  50476. if (index < 0 || index >= this.subMaterials.length) {
  50477. return this.getScene().defaultMaterial;
  50478. }
  50479. return this.subMaterials[index];
  50480. };
  50481. MultiMaterial.prototype.getActiveTextures = function () {
  50482. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  50483. var _a;
  50484. };
  50485. // Methods
  50486. MultiMaterial.prototype.getClassName = function () {
  50487. return "MultiMaterial";
  50488. };
  50489. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  50490. for (var index = 0; index < this.subMaterials.length; index++) {
  50491. var subMaterial = this.subMaterials[index];
  50492. if (subMaterial) {
  50493. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  50494. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  50495. return false;
  50496. }
  50497. continue;
  50498. }
  50499. if (!this.subMaterials[index].isReady(mesh)) {
  50500. return false;
  50501. }
  50502. }
  50503. }
  50504. return true;
  50505. };
  50506. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  50507. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  50508. for (var index = 0; index < this.subMaterials.length; index++) {
  50509. var subMaterial = null;
  50510. if (cloneChildren) {
  50511. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  50512. }
  50513. else {
  50514. subMaterial = this.subMaterials[index];
  50515. }
  50516. newMultiMaterial.subMaterials.push(subMaterial);
  50517. }
  50518. return newMultiMaterial;
  50519. };
  50520. MultiMaterial.prototype.serialize = function () {
  50521. var serializationObject = {};
  50522. serializationObject.name = this.name;
  50523. serializationObject.id = this.id;
  50524. serializationObject.tags = BABYLON.Tags.GetTags(this);
  50525. serializationObject.materials = [];
  50526. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  50527. var subMat = this.subMaterials[matIndex];
  50528. if (subMat) {
  50529. serializationObject.materials.push(subMat.id);
  50530. }
  50531. else {
  50532. serializationObject.materials.push(null);
  50533. }
  50534. }
  50535. return serializationObject;
  50536. };
  50537. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50538. var scene = this.getScene();
  50539. if (!scene) {
  50540. return;
  50541. }
  50542. var index = scene.multiMaterials.indexOf(this);
  50543. if (index >= 0) {
  50544. scene.multiMaterials.splice(index, 1);
  50545. }
  50546. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50547. };
  50548. return MultiMaterial;
  50549. }(BABYLON.Material));
  50550. BABYLON.MultiMaterial = MultiMaterial;
  50551. })(BABYLON || (BABYLON = {}));
  50552. //# sourceMappingURL=babylon.multiMaterial.js.map
  50553. var BABYLON;
  50554. (function (BABYLON) {
  50555. var FreeCameraTouchInput = (function () {
  50556. function FreeCameraTouchInput() {
  50557. this._offsetX = null;
  50558. this._offsetY = null;
  50559. this._pointerCount = 0;
  50560. this._pointerPressed = [];
  50561. this.touchAngularSensibility = 200000.0;
  50562. this.touchMoveSensibility = 250.0;
  50563. }
  50564. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  50565. var _this = this;
  50566. var previousPosition;
  50567. if (this._pointerInput === undefined) {
  50568. this._onLostFocus = function (evt) {
  50569. _this._offsetX = null;
  50570. _this._offsetY = null;
  50571. };
  50572. this._pointerInput = function (p, s) {
  50573. var evt = p.event;
  50574. if (evt.pointerType === "mouse") {
  50575. return;
  50576. }
  50577. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50578. if (!noPreventDefault) {
  50579. evt.preventDefault();
  50580. }
  50581. _this._pointerPressed.push(evt.pointerId);
  50582. if (_this._pointerPressed.length !== 1) {
  50583. return;
  50584. }
  50585. previousPosition = {
  50586. x: evt.clientX,
  50587. y: evt.clientY
  50588. };
  50589. }
  50590. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  50591. if (!noPreventDefault) {
  50592. evt.preventDefault();
  50593. }
  50594. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50595. if (index === -1) {
  50596. return;
  50597. }
  50598. _this._pointerPressed.splice(index, 1);
  50599. if (index != 0) {
  50600. return;
  50601. }
  50602. previousPosition = null;
  50603. _this._offsetX = null;
  50604. _this._offsetY = null;
  50605. }
  50606. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50607. if (!noPreventDefault) {
  50608. evt.preventDefault();
  50609. }
  50610. if (!previousPosition) {
  50611. return;
  50612. }
  50613. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50614. if (index != 0) {
  50615. return;
  50616. }
  50617. _this._offsetX = evt.clientX - previousPosition.x;
  50618. _this._offsetY = -(evt.clientY - previousPosition.y);
  50619. }
  50620. };
  50621. }
  50622. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  50623. element.addEventListener("blur", this._onLostFocus);
  50624. };
  50625. FreeCameraTouchInput.prototype.detachControl = function (element) {
  50626. if (this._pointerInput && element) {
  50627. this.camera.getScene().onPointerObservable.remove(this._observer);
  50628. this._observer = null;
  50629. element.removeEventListener("blur", this._onLostFocus);
  50630. this._onLostFocus = null;
  50631. this._pointerPressed = [];
  50632. this._offsetX = null;
  50633. this._offsetY = null;
  50634. this._pointerCount = 0;
  50635. }
  50636. };
  50637. FreeCameraTouchInput.prototype.checkInputs = function () {
  50638. if (this._offsetX) {
  50639. var camera = this.camera;
  50640. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  50641. if (this._pointerPressed.length > 1) {
  50642. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  50643. }
  50644. else {
  50645. var speed = camera._computeLocalCameraSpeed();
  50646. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  50647. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  50648. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  50649. }
  50650. }
  50651. };
  50652. FreeCameraTouchInput.prototype.getClassName = function () {
  50653. return "FreeCameraTouchInput";
  50654. };
  50655. FreeCameraTouchInput.prototype.getSimpleName = function () {
  50656. return "touch";
  50657. };
  50658. __decorate([
  50659. BABYLON.serialize()
  50660. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  50661. __decorate([
  50662. BABYLON.serialize()
  50663. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  50664. return FreeCameraTouchInput;
  50665. }());
  50666. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  50667. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  50668. })(BABYLON || (BABYLON = {}));
  50669. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  50670. /// <reference path="babylon.freeCamera.ts" />
  50671. var BABYLON;
  50672. (function (BABYLON) {
  50673. // We're mainly based on the logic defined into the FreeCamera code
  50674. var TouchCamera = (function (_super) {
  50675. __extends(TouchCamera, _super);
  50676. //-- end properties for backward compatibility for inputs
  50677. function TouchCamera(name, position, scene) {
  50678. var _this = _super.call(this, name, position, scene) || this;
  50679. _this.inputs.addTouch();
  50680. _this._setupInputs();
  50681. return _this;
  50682. }
  50683. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  50684. //-- Begin properties for backward compatibility for inputs
  50685. get: function () {
  50686. var touch = this.inputs.attached["touch"];
  50687. if (touch)
  50688. return touch.touchAngularSensibility;
  50689. },
  50690. set: function (value) {
  50691. var touch = this.inputs.attached["touch"];
  50692. if (touch)
  50693. touch.touchAngularSensibility = value;
  50694. },
  50695. enumerable: true,
  50696. configurable: true
  50697. });
  50698. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  50699. get: function () {
  50700. var touch = this.inputs.attached["touch"];
  50701. if (touch)
  50702. return touch.touchMoveSensibility;
  50703. },
  50704. set: function (value) {
  50705. var touch = this.inputs.attached["touch"];
  50706. if (touch)
  50707. touch.touchMoveSensibility = value;
  50708. },
  50709. enumerable: true,
  50710. configurable: true
  50711. });
  50712. TouchCamera.prototype.getClassName = function () {
  50713. return "TouchCamera";
  50714. };
  50715. TouchCamera.prototype._setupInputs = function () {
  50716. var mouse = this.inputs.attached["mouse"];
  50717. if (mouse) {
  50718. mouse.touchEnabled = false;
  50719. }
  50720. };
  50721. return TouchCamera;
  50722. }(BABYLON.FreeCamera));
  50723. BABYLON.TouchCamera = TouchCamera;
  50724. })(BABYLON || (BABYLON = {}));
  50725. //# sourceMappingURL=babylon.touchCamera.js.map
  50726. var BABYLON;
  50727. (function (BABYLON) {
  50728. var ProceduralTexture = (function (_super) {
  50729. __extends(ProceduralTexture, _super);
  50730. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  50731. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50732. if (isCube === void 0) { isCube = false; }
  50733. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50734. _this.isCube = isCube;
  50735. _this.isEnabled = true;
  50736. _this._currentRefreshId = -1;
  50737. _this._refreshRate = 1;
  50738. _this._vertexBuffers = {};
  50739. _this._uniforms = new Array();
  50740. _this._samplers = new Array();
  50741. _this._textures = new Array();
  50742. _this._floats = new Array();
  50743. _this._floatsArrays = {};
  50744. _this._colors3 = new Array();
  50745. _this._colors4 = new Array();
  50746. _this._vectors2 = new Array();
  50747. _this._vectors3 = new Array();
  50748. _this._matrices = new Array();
  50749. _this._fallbackTextureUsed = false;
  50750. scene._proceduralTextures.push(_this);
  50751. _this.name = name;
  50752. _this.isRenderTarget = true;
  50753. _this._size = size;
  50754. _this._generateMipMaps = generateMipMaps;
  50755. _this.setFragment(fragment);
  50756. _this._fallbackTexture = fallbackTexture;
  50757. var engine = scene.getEngine();
  50758. if (isCube) {
  50759. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  50760. _this.setFloat("face", 0);
  50761. }
  50762. else {
  50763. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  50764. }
  50765. // VBO
  50766. var vertices = [];
  50767. vertices.push(1, 1);
  50768. vertices.push(-1, 1);
  50769. vertices.push(-1, -1);
  50770. vertices.push(1, -1);
  50771. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  50772. _this._createIndexBuffer();
  50773. return _this;
  50774. }
  50775. ProceduralTexture.prototype._createIndexBuffer = function () {
  50776. var engine = this.getScene().getEngine();
  50777. // Indices
  50778. var indices = [];
  50779. indices.push(0);
  50780. indices.push(1);
  50781. indices.push(2);
  50782. indices.push(0);
  50783. indices.push(2);
  50784. indices.push(3);
  50785. this._indexBuffer = engine.createIndexBuffer(indices);
  50786. };
  50787. ProceduralTexture.prototype._rebuild = function () {
  50788. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  50789. this._createIndexBuffer();
  50790. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50791. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50792. }
  50793. };
  50794. ProceduralTexture.prototype.reset = function () {
  50795. if (this._effect === undefined) {
  50796. return;
  50797. }
  50798. var engine = this.getScene().getEngine();
  50799. engine._releaseEffect(this._effect);
  50800. };
  50801. ProceduralTexture.prototype.isReady = function () {
  50802. var _this = this;
  50803. var engine = this.getScene().getEngine();
  50804. var shaders;
  50805. if (!this._fragment) {
  50806. return false;
  50807. }
  50808. if (this._fallbackTextureUsed) {
  50809. return true;
  50810. }
  50811. if (this._fragment.fragmentElement !== undefined) {
  50812. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  50813. }
  50814. else {
  50815. shaders = { vertex: "procedural", fragment: this._fragment };
  50816. }
  50817. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  50818. _this.releaseInternalTexture();
  50819. if (_this._fallbackTexture) {
  50820. _this._texture = _this._fallbackTexture._texture;
  50821. _this._texture.incrementReferences();
  50822. }
  50823. _this._fallbackTextureUsed = true;
  50824. });
  50825. return this._effect.isReady();
  50826. };
  50827. ProceduralTexture.prototype.resetRefreshCounter = function () {
  50828. this._currentRefreshId = -1;
  50829. };
  50830. ProceduralTexture.prototype.setFragment = function (fragment) {
  50831. this._fragment = fragment;
  50832. };
  50833. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  50834. get: function () {
  50835. return this._refreshRate;
  50836. },
  50837. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50838. set: function (value) {
  50839. this._refreshRate = value;
  50840. this.resetRefreshCounter();
  50841. },
  50842. enumerable: true,
  50843. configurable: true
  50844. });
  50845. ProceduralTexture.prototype._shouldRender = function () {
  50846. if (!this.isEnabled || !this.isReady() || !this._texture) {
  50847. return false;
  50848. }
  50849. if (this._fallbackTextureUsed) {
  50850. return false;
  50851. }
  50852. if (this._currentRefreshId === -1) {
  50853. this._currentRefreshId = 1;
  50854. return true;
  50855. }
  50856. if (this.refreshRate === this._currentRefreshId) {
  50857. this._currentRefreshId = 1;
  50858. return true;
  50859. }
  50860. this._currentRefreshId++;
  50861. return false;
  50862. };
  50863. ProceduralTexture.prototype.getRenderSize = function () {
  50864. return this._size;
  50865. };
  50866. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  50867. if (this._fallbackTextureUsed) {
  50868. return;
  50869. }
  50870. this.releaseInternalTexture();
  50871. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  50872. };
  50873. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  50874. if (this._uniforms.indexOf(uniformName) === -1) {
  50875. this._uniforms.push(uniformName);
  50876. }
  50877. };
  50878. ProceduralTexture.prototype.setTexture = function (name, texture) {
  50879. if (this._samplers.indexOf(name) === -1) {
  50880. this._samplers.push(name);
  50881. }
  50882. this._textures[name] = texture;
  50883. return this;
  50884. };
  50885. ProceduralTexture.prototype.setFloat = function (name, value) {
  50886. this._checkUniform(name);
  50887. this._floats[name] = value;
  50888. return this;
  50889. };
  50890. ProceduralTexture.prototype.setFloats = function (name, value) {
  50891. this._checkUniform(name);
  50892. this._floatsArrays[name] = value;
  50893. return this;
  50894. };
  50895. ProceduralTexture.prototype.setColor3 = function (name, value) {
  50896. this._checkUniform(name);
  50897. this._colors3[name] = value;
  50898. return this;
  50899. };
  50900. ProceduralTexture.prototype.setColor4 = function (name, value) {
  50901. this._checkUniform(name);
  50902. this._colors4[name] = value;
  50903. return this;
  50904. };
  50905. ProceduralTexture.prototype.setVector2 = function (name, value) {
  50906. this._checkUniform(name);
  50907. this._vectors2[name] = value;
  50908. return this;
  50909. };
  50910. ProceduralTexture.prototype.setVector3 = function (name, value) {
  50911. this._checkUniform(name);
  50912. this._vectors3[name] = value;
  50913. return this;
  50914. };
  50915. ProceduralTexture.prototype.setMatrix = function (name, value) {
  50916. this._checkUniform(name);
  50917. this._matrices[name] = value;
  50918. return this;
  50919. };
  50920. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  50921. var scene = this.getScene();
  50922. var engine = scene.getEngine();
  50923. // Render
  50924. engine.enableEffect(this._effect);
  50925. engine.setState(false);
  50926. // Texture
  50927. for (var name in this._textures) {
  50928. this._effect.setTexture(name, this._textures[name]);
  50929. }
  50930. // Float
  50931. for (name in this._floats) {
  50932. this._effect.setFloat(name, this._floats[name]);
  50933. }
  50934. // Floats
  50935. for (name in this._floatsArrays) {
  50936. this._effect.setArray(name, this._floatsArrays[name]);
  50937. }
  50938. // Color3
  50939. for (name in this._colors3) {
  50940. this._effect.setColor3(name, this._colors3[name]);
  50941. }
  50942. // Color4
  50943. for (name in this._colors4) {
  50944. var color = this._colors4[name];
  50945. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50946. }
  50947. // Vector2
  50948. for (name in this._vectors2) {
  50949. this._effect.setVector2(name, this._vectors2[name]);
  50950. }
  50951. // Vector3
  50952. for (name in this._vectors3) {
  50953. this._effect.setVector3(name, this._vectors3[name]);
  50954. }
  50955. // Matrix
  50956. for (name in this._matrices) {
  50957. this._effect.setMatrix(name, this._matrices[name]);
  50958. }
  50959. if (this.isCube) {
  50960. for (var face = 0; face < 6; face++) {
  50961. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  50962. // VBOs
  50963. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50964. this._effect.setFloat("face", face);
  50965. // Clear
  50966. engine.clear(scene.clearColor, true, true, true);
  50967. // Draw order
  50968. engine.draw(true, 0, 6);
  50969. // Mipmaps
  50970. if (face === 5) {
  50971. engine.generateMipMapsForCubemap(this._texture);
  50972. }
  50973. }
  50974. }
  50975. else {
  50976. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  50977. // VBOs
  50978. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50979. // Clear
  50980. engine.clear(scene.clearColor, true, true, true);
  50981. // Draw order
  50982. engine.draw(true, 0, 6);
  50983. }
  50984. // Unbind
  50985. engine.unBindFramebuffer(this._texture, this.isCube);
  50986. if (this.onGenerated) {
  50987. this.onGenerated();
  50988. }
  50989. };
  50990. ProceduralTexture.prototype.clone = function () {
  50991. var textureSize = this.getSize();
  50992. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  50993. // Base texture
  50994. newTexture.hasAlpha = this.hasAlpha;
  50995. newTexture.level = this.level;
  50996. // RenderTarget Texture
  50997. newTexture.coordinatesMode = this.coordinatesMode;
  50998. return newTexture;
  50999. };
  51000. ProceduralTexture.prototype.dispose = function () {
  51001. var index = this.getScene()._proceduralTextures.indexOf(this);
  51002. if (index >= 0) {
  51003. this.getScene()._proceduralTextures.splice(index, 1);
  51004. }
  51005. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  51006. if (vertexBuffer) {
  51007. vertexBuffer.dispose();
  51008. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  51009. }
  51010. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  51011. this._indexBuffer = null;
  51012. }
  51013. _super.prototype.dispose.call(this);
  51014. };
  51015. return ProceduralTexture;
  51016. }(BABYLON.Texture));
  51017. BABYLON.ProceduralTexture = ProceduralTexture;
  51018. })(BABYLON || (BABYLON = {}));
  51019. //# sourceMappingURL=babylon.proceduralTexture.js.map
  51020. /// <reference path="babylon.proceduralTexture.ts" />
  51021. var BABYLON;
  51022. (function (BABYLON) {
  51023. var CustomProceduralTexture = (function (_super) {
  51024. __extends(CustomProceduralTexture, _super);
  51025. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  51026. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  51027. _this._animate = true;
  51028. _this._time = 0;
  51029. _this._texturePath = texturePath;
  51030. //Try to load json
  51031. _this.loadJson(texturePath);
  51032. _this.refreshRate = 1;
  51033. return _this;
  51034. }
  51035. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  51036. var _this = this;
  51037. var that = this;
  51038. function noConfigFile() {
  51039. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  51040. try {
  51041. that.setFragment(that._texturePath);
  51042. }
  51043. catch (ex) {
  51044. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  51045. }
  51046. }
  51047. var configFileUrl = jsonUrl + "/config.json";
  51048. var xhr = new XMLHttpRequest();
  51049. xhr.open("GET", configFileUrl, true);
  51050. xhr.addEventListener("load", function () {
  51051. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  51052. try {
  51053. _this._config = JSON.parse(xhr.response);
  51054. _this.updateShaderUniforms();
  51055. _this.updateTextures();
  51056. _this.setFragment(_this._texturePath + "/custom");
  51057. _this._animate = _this._config.animate;
  51058. _this.refreshRate = _this._config.refreshrate;
  51059. }
  51060. catch (ex) {
  51061. noConfigFile();
  51062. }
  51063. }
  51064. else {
  51065. noConfigFile();
  51066. }
  51067. }, false);
  51068. xhr.addEventListener("error", function () {
  51069. noConfigFile();
  51070. }, false);
  51071. try {
  51072. xhr.send();
  51073. }
  51074. catch (ex) {
  51075. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  51076. }
  51077. };
  51078. CustomProceduralTexture.prototype.isReady = function () {
  51079. if (!_super.prototype.isReady.call(this)) {
  51080. return false;
  51081. }
  51082. for (var name in this._textures) {
  51083. var texture = this._textures[name];
  51084. if (!texture.isReady()) {
  51085. return false;
  51086. }
  51087. }
  51088. return true;
  51089. };
  51090. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  51091. if (this._animate) {
  51092. this._time += this.getScene().getAnimationRatio() * 0.03;
  51093. this.updateShaderUniforms();
  51094. }
  51095. _super.prototype.render.call(this, useCameraPostProcess);
  51096. };
  51097. CustomProceduralTexture.prototype.updateTextures = function () {
  51098. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  51099. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  51100. }
  51101. };
  51102. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  51103. if (this._config) {
  51104. for (var j = 0; j < this._config.uniforms.length; j++) {
  51105. var uniform = this._config.uniforms[j];
  51106. switch (uniform.type) {
  51107. case "float":
  51108. this.setFloat(uniform.name, uniform.value);
  51109. break;
  51110. case "color3":
  51111. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  51112. break;
  51113. case "color4":
  51114. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  51115. break;
  51116. case "vector2":
  51117. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  51118. break;
  51119. case "vector3":
  51120. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  51121. break;
  51122. }
  51123. }
  51124. }
  51125. this.setFloat("time", this._time);
  51126. };
  51127. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  51128. get: function () {
  51129. return this._animate;
  51130. },
  51131. set: function (value) {
  51132. this._animate = value;
  51133. },
  51134. enumerable: true,
  51135. configurable: true
  51136. });
  51137. return CustomProceduralTexture;
  51138. }(BABYLON.ProceduralTexture));
  51139. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  51140. })(BABYLON || (BABYLON = {}));
  51141. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  51142. var BABYLON;
  51143. (function (BABYLON) {
  51144. var FreeCameraGamepadInput = (function () {
  51145. function FreeCameraGamepadInput() {
  51146. this.gamepadAngularSensibility = 200;
  51147. this.gamepadMoveSensibility = 40;
  51148. // private members
  51149. this._cameraTransform = BABYLON.Matrix.Identity();
  51150. this._deltaTransform = BABYLON.Vector3.Zero();
  51151. this._vector3 = BABYLON.Vector3.Zero();
  51152. this._vector2 = BABYLON.Vector2.Zero();
  51153. }
  51154. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  51155. var _this = this;
  51156. var manager = this.camera.getScene().gamepadManager;
  51157. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  51158. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  51159. // prioritize XBOX gamepads.
  51160. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  51161. _this.gamepad = gamepad;
  51162. }
  51163. }
  51164. });
  51165. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  51166. if (_this.gamepad === gamepad) {
  51167. _this.gamepad = null;
  51168. }
  51169. });
  51170. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  51171. };
  51172. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  51173. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  51174. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  51175. this.gamepad = null;
  51176. };
  51177. FreeCameraGamepadInput.prototype.checkInputs = function () {
  51178. if (this.gamepad && this.gamepad.leftStick) {
  51179. var camera = this.camera;
  51180. var LSValues = this.gamepad.leftStick;
  51181. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  51182. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  51183. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  51184. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  51185. var RSValues = this.gamepad.rightStick;
  51186. if (RSValues) {
  51187. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  51188. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  51189. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  51190. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  51191. }
  51192. else {
  51193. RSValues = { x: 0, y: 0 };
  51194. }
  51195. if (!camera.rotationQuaternion) {
  51196. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  51197. }
  51198. else {
  51199. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  51200. }
  51201. var speed = camera._computeLocalCameraSpeed() * 50.0;
  51202. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  51203. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  51204. camera.cameraDirection.addInPlace(this._deltaTransform);
  51205. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  51206. camera.cameraRotation.addInPlace(this._vector2);
  51207. }
  51208. };
  51209. FreeCameraGamepadInput.prototype.getClassName = function () {
  51210. return "FreeCameraGamepadInput";
  51211. };
  51212. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  51213. return "gamepad";
  51214. };
  51215. __decorate([
  51216. BABYLON.serialize()
  51217. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  51218. __decorate([
  51219. BABYLON.serialize()
  51220. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  51221. return FreeCameraGamepadInput;
  51222. }());
  51223. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  51224. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  51225. })(BABYLON || (BABYLON = {}));
  51226. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  51227. var BABYLON;
  51228. (function (BABYLON) {
  51229. var ArcRotateCameraGamepadInput = (function () {
  51230. function ArcRotateCameraGamepadInput() {
  51231. this.gamepadRotationSensibility = 80;
  51232. this.gamepadMoveSensibility = 40;
  51233. }
  51234. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  51235. var _this = this;
  51236. var manager = this.camera.getScene().gamepadManager;
  51237. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  51238. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  51239. // prioritize XBOX gamepads.
  51240. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  51241. _this.gamepad = gamepad;
  51242. }
  51243. }
  51244. });
  51245. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  51246. if (_this.gamepad === gamepad) {
  51247. _this.gamepad = null;
  51248. }
  51249. });
  51250. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  51251. };
  51252. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  51253. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  51254. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  51255. this.gamepad = null;
  51256. };
  51257. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  51258. if (this.gamepad) {
  51259. var camera = this.camera;
  51260. var RSValues = this.gamepad.rightStick;
  51261. if (RSValues) {
  51262. if (RSValues.x != 0) {
  51263. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  51264. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  51265. camera.inertialAlphaOffset += normalizedRX;
  51266. }
  51267. }
  51268. if (RSValues.y != 0) {
  51269. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  51270. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  51271. camera.inertialBetaOffset += normalizedRY;
  51272. }
  51273. }
  51274. }
  51275. var LSValues = this.gamepad.leftStick;
  51276. if (LSValues && LSValues.y != 0) {
  51277. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  51278. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  51279. this.camera.inertialRadiusOffset -= normalizedLY;
  51280. }
  51281. }
  51282. }
  51283. };
  51284. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  51285. return "ArcRotateCameraGamepadInput";
  51286. };
  51287. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  51288. return "gamepad";
  51289. };
  51290. __decorate([
  51291. BABYLON.serialize()
  51292. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  51293. __decorate([
  51294. BABYLON.serialize()
  51295. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  51296. return ArcRotateCameraGamepadInput;
  51297. }());
  51298. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  51299. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  51300. })(BABYLON || (BABYLON = {}));
  51301. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  51302. var BABYLON;
  51303. (function (BABYLON) {
  51304. var GamepadManager = (function () {
  51305. function GamepadManager() {
  51306. var _this = this;
  51307. this._babylonGamepads = [];
  51308. this._oneGamepadConnected = false;
  51309. this._isMonitoring = false;
  51310. this._gamepadEventSupported = 'GamepadEvent' in window;
  51311. this._gamepadSupport = (navigator.getGamepads ||
  51312. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  51313. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  51314. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  51315. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  51316. for (var i in _this._babylonGamepads) {
  51317. var gamepad = _this._babylonGamepads[i];
  51318. if (gamepad && gamepad._isConnected) {
  51319. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  51320. }
  51321. }
  51322. });
  51323. this._onGamepadConnectedEvent = function (evt) {
  51324. var gamepad = evt.gamepad;
  51325. if (gamepad.index in _this._babylonGamepads) {
  51326. if (_this._babylonGamepads[gamepad.index].isConnected) {
  51327. return;
  51328. }
  51329. }
  51330. var newGamepad;
  51331. if (_this._babylonGamepads[gamepad.index]) {
  51332. newGamepad = _this._babylonGamepads[gamepad.index];
  51333. newGamepad.browserGamepad = gamepad;
  51334. newGamepad._isConnected = true;
  51335. }
  51336. else {
  51337. newGamepad = _this._addNewGamepad(gamepad);
  51338. }
  51339. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51340. _this._startMonitoringGamepads();
  51341. };
  51342. this._onGamepadDisconnectedEvent = function (evt) {
  51343. var gamepad = evt.gamepad;
  51344. // Remove the gamepad from the list of gamepads to monitor.
  51345. for (var i in _this._babylonGamepads) {
  51346. if (_this._babylonGamepads[i].index === gamepad.index) {
  51347. var disconnectedGamepad = _this._babylonGamepads[i];
  51348. disconnectedGamepad._isConnected = false;
  51349. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  51350. break;
  51351. }
  51352. }
  51353. };
  51354. if (this._gamepadSupport) {
  51355. //first add already-connected gamepads
  51356. this._updateGamepadObjects();
  51357. if (this._babylonGamepads.length) {
  51358. this._startMonitoringGamepads();
  51359. }
  51360. // Checking if the gamepad connected event is supported (like in Firefox)
  51361. if (this._gamepadEventSupported) {
  51362. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  51363. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  51364. }
  51365. else {
  51366. this._startMonitoringGamepads();
  51367. }
  51368. }
  51369. }
  51370. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  51371. get: function () {
  51372. return this._babylonGamepads;
  51373. },
  51374. enumerable: true,
  51375. configurable: true
  51376. });
  51377. GamepadManager.prototype.getGamepadByType = function (type) {
  51378. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  51379. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  51380. var gamepad = _a[_i];
  51381. if (gamepad && gamepad.type === type) {
  51382. return gamepad;
  51383. }
  51384. }
  51385. return null;
  51386. };
  51387. GamepadManager.prototype.dispose = function () {
  51388. if (this._gamepadEventSupported) {
  51389. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  51390. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  51391. this._onGamepadConnectedEvent = null;
  51392. this._onGamepadDisconnectedEvent = null;
  51393. }
  51394. this._babylonGamepads.forEach(function (gamepad) {
  51395. gamepad.dispose();
  51396. });
  51397. this.onGamepadConnectedObservable.clear();
  51398. this.onGamepadDisconnectedObservable.clear();
  51399. this._oneGamepadConnected = false;
  51400. this._stopMonitoringGamepads();
  51401. this._babylonGamepads = [];
  51402. };
  51403. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  51404. if (!this._oneGamepadConnected) {
  51405. this._oneGamepadConnected = true;
  51406. }
  51407. var newGamepad;
  51408. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  51409. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  51410. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  51411. }
  51412. else if (gamepad.pose) {
  51413. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  51414. }
  51415. else {
  51416. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  51417. }
  51418. this._babylonGamepads[newGamepad.index] = newGamepad;
  51419. return newGamepad;
  51420. };
  51421. GamepadManager.prototype._startMonitoringGamepads = function () {
  51422. if (!this._isMonitoring) {
  51423. this._isMonitoring = true;
  51424. this._checkGamepadsStatus();
  51425. }
  51426. };
  51427. GamepadManager.prototype._stopMonitoringGamepads = function () {
  51428. this._isMonitoring = false;
  51429. };
  51430. GamepadManager.prototype._checkGamepadsStatus = function () {
  51431. var _this = this;
  51432. // Hack to be compatible Chrome
  51433. this._updateGamepadObjects();
  51434. for (var i in this._babylonGamepads) {
  51435. var gamepad = this._babylonGamepads[i];
  51436. if (!gamepad || !gamepad.isConnected) {
  51437. continue;
  51438. }
  51439. gamepad.update();
  51440. }
  51441. if (this._isMonitoring) {
  51442. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  51443. }
  51444. };
  51445. // This function is called only on Chrome, which does not properly support
  51446. // connection/disconnection events and forces you to recopy again the gamepad object
  51447. GamepadManager.prototype._updateGamepadObjects = function () {
  51448. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  51449. for (var i = 0; i < gamepads.length; i++) {
  51450. if (gamepads[i]) {
  51451. if (!this._babylonGamepads[gamepads[i].index]) {
  51452. var newGamepad = this._addNewGamepad(gamepads[i]);
  51453. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51454. }
  51455. else {
  51456. // Forced to copy again this object for Chrome for unknown reason
  51457. this._babylonGamepads[i].browserGamepad = gamepads[i];
  51458. if (!this._babylonGamepads[i].isConnected) {
  51459. this._babylonGamepads[i]._isConnected = true;
  51460. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  51461. }
  51462. }
  51463. }
  51464. }
  51465. };
  51466. return GamepadManager;
  51467. }());
  51468. BABYLON.GamepadManager = GamepadManager;
  51469. })(BABYLON || (BABYLON = {}));
  51470. //# sourceMappingURL=babylon.gamepadManager.js.map
  51471. var BABYLON;
  51472. (function (BABYLON) {
  51473. var StickValues = (function () {
  51474. function StickValues(x, y) {
  51475. this.x = x;
  51476. this.y = y;
  51477. }
  51478. return StickValues;
  51479. }());
  51480. BABYLON.StickValues = StickValues;
  51481. var Gamepad = (function () {
  51482. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  51483. if (leftStickX === void 0) { leftStickX = 0; }
  51484. if (leftStickY === void 0) { leftStickY = 1; }
  51485. if (rightStickX === void 0) { rightStickX = 2; }
  51486. if (rightStickY === void 0) { rightStickY = 3; }
  51487. this.id = id;
  51488. this.index = index;
  51489. this.browserGamepad = browserGamepad;
  51490. this._isConnected = true;
  51491. this.type = Gamepad.GAMEPAD;
  51492. this._leftStickAxisX = leftStickX;
  51493. this._leftStickAxisY = leftStickY;
  51494. this._rightStickAxisX = rightStickX;
  51495. this._rightStickAxisY = rightStickY;
  51496. if (this.browserGamepad.axes.length >= 2) {
  51497. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51498. }
  51499. if (this.browserGamepad.axes.length >= 4) {
  51500. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51501. }
  51502. }
  51503. Object.defineProperty(Gamepad.prototype, "isConnected", {
  51504. get: function () {
  51505. return this._isConnected;
  51506. },
  51507. enumerable: true,
  51508. configurable: true
  51509. });
  51510. Gamepad.prototype.onleftstickchanged = function (callback) {
  51511. this._onleftstickchanged = callback;
  51512. };
  51513. Gamepad.prototype.onrightstickchanged = function (callback) {
  51514. this._onrightstickchanged = callback;
  51515. };
  51516. Object.defineProperty(Gamepad.prototype, "leftStick", {
  51517. get: function () {
  51518. return this._leftStick;
  51519. },
  51520. set: function (newValues) {
  51521. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  51522. this._onleftstickchanged(newValues);
  51523. }
  51524. this._leftStick = newValues;
  51525. },
  51526. enumerable: true,
  51527. configurable: true
  51528. });
  51529. Object.defineProperty(Gamepad.prototype, "rightStick", {
  51530. get: function () {
  51531. return this._rightStick;
  51532. },
  51533. set: function (newValues) {
  51534. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  51535. this._onrightstickchanged(newValues);
  51536. }
  51537. this._rightStick = newValues;
  51538. },
  51539. enumerable: true,
  51540. configurable: true
  51541. });
  51542. Gamepad.prototype.update = function () {
  51543. if (this._leftStick) {
  51544. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51545. }
  51546. if (this._rightStick) {
  51547. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51548. }
  51549. };
  51550. Gamepad.prototype.dispose = function () {
  51551. };
  51552. Gamepad.GAMEPAD = 0;
  51553. Gamepad.GENERIC = 1;
  51554. Gamepad.XBOX = 2;
  51555. Gamepad.POSE_ENABLED = 3;
  51556. return Gamepad;
  51557. }());
  51558. BABYLON.Gamepad = Gamepad;
  51559. var GenericPad = (function (_super) {
  51560. __extends(GenericPad, _super);
  51561. function GenericPad(id, index, browserGamepad) {
  51562. var _this = _super.call(this, id, index, browserGamepad) || this;
  51563. _this.onButtonDownObservable = new BABYLON.Observable();
  51564. _this.onButtonUpObservable = new BABYLON.Observable();
  51565. _this.type = Gamepad.GENERIC;
  51566. _this._buttons = new Array(browserGamepad.buttons.length);
  51567. return _this;
  51568. }
  51569. GenericPad.prototype.onbuttondown = function (callback) {
  51570. this._onbuttondown = callback;
  51571. };
  51572. GenericPad.prototype.onbuttonup = function (callback) {
  51573. this._onbuttonup = callback;
  51574. };
  51575. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51576. if (newValue !== currentValue) {
  51577. if (newValue === 1) {
  51578. if (this._onbuttondown) {
  51579. this._onbuttondown(buttonIndex);
  51580. }
  51581. this.onButtonDownObservable.notifyObservers(buttonIndex);
  51582. }
  51583. if (newValue === 0) {
  51584. if (this._onbuttonup) {
  51585. this._onbuttonup(buttonIndex);
  51586. }
  51587. this.onButtonUpObservable.notifyObservers(buttonIndex);
  51588. }
  51589. }
  51590. return newValue;
  51591. };
  51592. GenericPad.prototype.update = function () {
  51593. _super.prototype.update.call(this);
  51594. for (var index = 0; index < this._buttons.length; index++) {
  51595. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  51596. }
  51597. };
  51598. return GenericPad;
  51599. }(Gamepad));
  51600. BABYLON.GenericPad = GenericPad;
  51601. })(BABYLON || (BABYLON = {}));
  51602. //# sourceMappingURL=babylon.gamepad.js.map
  51603. var BABYLON;
  51604. (function (BABYLON) {
  51605. var Xbox360Button;
  51606. (function (Xbox360Button) {
  51607. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51608. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51609. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51610. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51611. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51612. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51613. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51614. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51615. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51616. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51617. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51618. var Xbox360Dpad;
  51619. (function (Xbox360Dpad) {
  51620. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51621. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51622. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51623. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51624. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51625. var Xbox360Pad = (function (_super) {
  51626. __extends(Xbox360Pad, _super);
  51627. function Xbox360Pad(id, index, gamepad, xboxOne) {
  51628. if (xboxOne === void 0) { xboxOne = false; }
  51629. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  51630. _this._leftTrigger = 0;
  51631. _this._rightTrigger = 0;
  51632. _this.onButtonDownObservable = new BABYLON.Observable();
  51633. _this.onButtonUpObservable = new BABYLON.Observable();
  51634. _this.onPadDownObservable = new BABYLON.Observable();
  51635. _this.onPadUpObservable = new BABYLON.Observable();
  51636. _this._buttonA = 0;
  51637. _this._buttonB = 0;
  51638. _this._buttonX = 0;
  51639. _this._buttonY = 0;
  51640. _this._buttonBack = 0;
  51641. _this._buttonStart = 0;
  51642. _this._buttonLB = 0;
  51643. _this._buttonRB = 0;
  51644. _this._buttonLeftStick = 0;
  51645. _this._buttonRightStick = 0;
  51646. _this._dPadUp = 0;
  51647. _this._dPadDown = 0;
  51648. _this._dPadLeft = 0;
  51649. _this._dPadRight = 0;
  51650. _this._isXboxOnePad = false;
  51651. _this.type = BABYLON.Gamepad.XBOX;
  51652. _this._isXboxOnePad = xboxOne;
  51653. return _this;
  51654. }
  51655. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51656. this._onlefttriggerchanged = callback;
  51657. };
  51658. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51659. this._onrighttriggerchanged = callback;
  51660. };
  51661. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51662. get: function () {
  51663. return this._leftTrigger;
  51664. },
  51665. set: function (newValue) {
  51666. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51667. this._onlefttriggerchanged(newValue);
  51668. }
  51669. this._leftTrigger = newValue;
  51670. },
  51671. enumerable: true,
  51672. configurable: true
  51673. });
  51674. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51675. get: function () {
  51676. return this._rightTrigger;
  51677. },
  51678. set: function (newValue) {
  51679. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51680. this._onrighttriggerchanged(newValue);
  51681. }
  51682. this._rightTrigger = newValue;
  51683. },
  51684. enumerable: true,
  51685. configurable: true
  51686. });
  51687. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51688. this._onbuttondown = callback;
  51689. };
  51690. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51691. this._onbuttonup = callback;
  51692. };
  51693. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51694. this._ondpaddown = callback;
  51695. };
  51696. Xbox360Pad.prototype.ondpadup = function (callback) {
  51697. this._ondpadup = callback;
  51698. };
  51699. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51700. if (newValue !== currentValue) {
  51701. if (newValue === 1) {
  51702. if (this._onbuttondown) {
  51703. this._onbuttondown(buttonType);
  51704. }
  51705. this.onButtonDownObservable.notifyObservers(buttonType);
  51706. }
  51707. if (newValue === 0) {
  51708. if (this._onbuttonup) {
  51709. this._onbuttonup(buttonType);
  51710. }
  51711. this.onButtonUpObservable.notifyObservers(buttonType);
  51712. }
  51713. }
  51714. return newValue;
  51715. };
  51716. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51717. if (newValue !== currentValue) {
  51718. if (newValue === 1) {
  51719. if (this._ondpaddown) {
  51720. this._ondpaddown(buttonType);
  51721. }
  51722. this.onPadDownObservable.notifyObservers(buttonType);
  51723. }
  51724. if (newValue === 0) {
  51725. if (this._ondpadup) {
  51726. this._ondpadup(buttonType);
  51727. }
  51728. this.onPadUpObservable.notifyObservers(buttonType);
  51729. }
  51730. }
  51731. return newValue;
  51732. };
  51733. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51734. get: function () {
  51735. return this._buttonA;
  51736. },
  51737. set: function (value) {
  51738. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51739. },
  51740. enumerable: true,
  51741. configurable: true
  51742. });
  51743. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51744. get: function () {
  51745. return this._buttonB;
  51746. },
  51747. set: function (value) {
  51748. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51749. },
  51750. enumerable: true,
  51751. configurable: true
  51752. });
  51753. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51754. get: function () {
  51755. return this._buttonX;
  51756. },
  51757. set: function (value) {
  51758. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51759. },
  51760. enumerable: true,
  51761. configurable: true
  51762. });
  51763. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51764. get: function () {
  51765. return this._buttonY;
  51766. },
  51767. set: function (value) {
  51768. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  51769. },
  51770. enumerable: true,
  51771. configurable: true
  51772. });
  51773. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  51774. get: function () {
  51775. return this._buttonStart;
  51776. },
  51777. set: function (value) {
  51778. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  51779. },
  51780. enumerable: true,
  51781. configurable: true
  51782. });
  51783. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  51784. get: function () {
  51785. return this._buttonBack;
  51786. },
  51787. set: function (value) {
  51788. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  51789. },
  51790. enumerable: true,
  51791. configurable: true
  51792. });
  51793. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  51794. get: function () {
  51795. return this._buttonLB;
  51796. },
  51797. set: function (value) {
  51798. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  51799. },
  51800. enumerable: true,
  51801. configurable: true
  51802. });
  51803. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  51804. get: function () {
  51805. return this._buttonRB;
  51806. },
  51807. set: function (value) {
  51808. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  51809. },
  51810. enumerable: true,
  51811. configurable: true
  51812. });
  51813. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  51814. get: function () {
  51815. return this._buttonLeftStick;
  51816. },
  51817. set: function (value) {
  51818. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  51819. },
  51820. enumerable: true,
  51821. configurable: true
  51822. });
  51823. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  51824. get: function () {
  51825. return this._buttonRightStick;
  51826. },
  51827. set: function (value) {
  51828. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  51829. },
  51830. enumerable: true,
  51831. configurable: true
  51832. });
  51833. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  51834. get: function () {
  51835. return this._dPadUp;
  51836. },
  51837. set: function (value) {
  51838. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  51839. },
  51840. enumerable: true,
  51841. configurable: true
  51842. });
  51843. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  51844. get: function () {
  51845. return this._dPadDown;
  51846. },
  51847. set: function (value) {
  51848. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  51849. },
  51850. enumerable: true,
  51851. configurable: true
  51852. });
  51853. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51854. get: function () {
  51855. return this._dPadLeft;
  51856. },
  51857. set: function (value) {
  51858. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51859. },
  51860. enumerable: true,
  51861. configurable: true
  51862. });
  51863. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51864. get: function () {
  51865. return this._dPadRight;
  51866. },
  51867. set: function (value) {
  51868. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51869. },
  51870. enumerable: true,
  51871. configurable: true
  51872. });
  51873. Xbox360Pad.prototype.update = function () {
  51874. _super.prototype.update.call(this);
  51875. if (this._isXboxOnePad) {
  51876. this.buttonA = this.browserGamepad.buttons[0].value;
  51877. this.buttonB = this.browserGamepad.buttons[1].value;
  51878. this.buttonX = this.browserGamepad.buttons[2].value;
  51879. this.buttonY = this.browserGamepad.buttons[3].value;
  51880. this.buttonLB = this.browserGamepad.buttons[4].value;
  51881. this.buttonRB = this.browserGamepad.buttons[5].value;
  51882. this.leftTrigger = this.browserGamepad.axes[2];
  51883. this.rightTrigger = this.browserGamepad.axes[5];
  51884. this.buttonBack = this.browserGamepad.buttons[9].value;
  51885. this.buttonStart = this.browserGamepad.buttons[8].value;
  51886. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  51887. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  51888. this.dPadUp = this.browserGamepad.buttons[11].value;
  51889. this.dPadDown = this.browserGamepad.buttons[12].value;
  51890. this.dPadLeft = this.browserGamepad.buttons[13].value;
  51891. this.dPadRight = this.browserGamepad.buttons[14].value;
  51892. }
  51893. else {
  51894. this.buttonA = this.browserGamepad.buttons[0].value;
  51895. this.buttonB = this.browserGamepad.buttons[1].value;
  51896. this.buttonX = this.browserGamepad.buttons[2].value;
  51897. this.buttonY = this.browserGamepad.buttons[3].value;
  51898. this.buttonLB = this.browserGamepad.buttons[4].value;
  51899. this.buttonRB = this.browserGamepad.buttons[5].value;
  51900. this.leftTrigger = this.browserGamepad.buttons[6].value;
  51901. this.rightTrigger = this.browserGamepad.buttons[7].value;
  51902. this.buttonBack = this.browserGamepad.buttons[8].value;
  51903. this.buttonStart = this.browserGamepad.buttons[9].value;
  51904. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  51905. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  51906. this.dPadUp = this.browserGamepad.buttons[12].value;
  51907. this.dPadDown = this.browserGamepad.buttons[13].value;
  51908. this.dPadLeft = this.browserGamepad.buttons[14].value;
  51909. this.dPadRight = this.browserGamepad.buttons[15].value;
  51910. }
  51911. };
  51912. return Xbox360Pad;
  51913. }(BABYLON.Gamepad));
  51914. BABYLON.Xbox360Pad = Xbox360Pad;
  51915. })(BABYLON || (BABYLON = {}));
  51916. //# sourceMappingURL=babylon.xboxGamepad.js.map
  51917. var BABYLON;
  51918. (function (BABYLON) {
  51919. var PoseEnabledControllerType;
  51920. (function (PoseEnabledControllerType) {
  51921. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  51922. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  51923. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  51924. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  51925. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  51926. var PoseEnabledControllerHelper = (function () {
  51927. function PoseEnabledControllerHelper() {
  51928. }
  51929. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  51930. // Oculus Touch
  51931. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  51932. return new BABYLON.OculusTouchController(vrGamepad);
  51933. }
  51934. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  51935. return new BABYLON.WindowsMotionController(vrGamepad);
  51936. }
  51937. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  51938. return new BABYLON.ViveController(vrGamepad);
  51939. }
  51940. else {
  51941. return new BABYLON.GenericController(vrGamepad);
  51942. }
  51943. };
  51944. return PoseEnabledControllerHelper;
  51945. }());
  51946. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  51947. var PoseEnabledController = (function (_super) {
  51948. __extends(PoseEnabledController, _super);
  51949. function PoseEnabledController(browserGamepad) {
  51950. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  51951. _this.deviceScaleFactor = 1;
  51952. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  51953. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  51954. _this.controllerType = PoseEnabledControllerType.GENERIC;
  51955. _this.position = BABYLON.Vector3.Zero();
  51956. _this.rotationQuaternion = new BABYLON.Quaternion();
  51957. _this.devicePosition = BABYLON.Vector3.Zero();
  51958. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  51959. _this._calculatedPosition = BABYLON.Vector3.Zero();
  51960. _this._calculatedRotation = new BABYLON.Quaternion();
  51961. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  51962. return _this;
  51963. }
  51964. PoseEnabledController.prototype.update = function () {
  51965. _super.prototype.update.call(this);
  51966. var pose = this.browserGamepad.pose;
  51967. this.updateFromDevice(pose);
  51968. if (this._mesh) {
  51969. this._mesh.position.copyFrom(this._calculatedPosition);
  51970. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  51971. }
  51972. };
  51973. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  51974. if (poseData) {
  51975. this.rawPose = poseData;
  51976. if (poseData.position) {
  51977. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  51978. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  51979. this.devicePosition.z *= -1;
  51980. }
  51981. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  51982. this._calculatedPosition.addInPlace(this.position);
  51983. }
  51984. if (poseData.orientation) {
  51985. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  51986. if (this._mesh) {
  51987. if (this._mesh.getScene().useRightHandedSystem) {
  51988. this.deviceRotationQuaternion.z *= -1;
  51989. this.deviceRotationQuaternion.w *= -1;
  51990. }
  51991. else {
  51992. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  51993. }
  51994. }
  51995. // if the camera is set, rotate to the camera's rotation
  51996. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  51997. }
  51998. }
  51999. };
  52000. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  52001. if (this._mesh) {
  52002. this._mesh.parent = undefined;
  52003. }
  52004. this._mesh = mesh;
  52005. if (this._poseControlledCamera) {
  52006. this._mesh.parent = this._poseControlledCamera;
  52007. }
  52008. if (!this._mesh.rotationQuaternion) {
  52009. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  52010. }
  52011. };
  52012. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  52013. this._poseControlledCamera = camera;
  52014. if (this._mesh) {
  52015. this._mesh.parent = this._poseControlledCamera;
  52016. }
  52017. };
  52018. PoseEnabledController.prototype.dispose = function () {
  52019. if (this._mesh) {
  52020. this._mesh.dispose();
  52021. }
  52022. this._mesh = undefined;
  52023. _super.prototype.dispose.call(this);
  52024. };
  52025. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  52026. get: function () {
  52027. return this._mesh;
  52028. },
  52029. enumerable: true,
  52030. configurable: true
  52031. });
  52032. PoseEnabledController.prototype.getForwardRay = function (length) {
  52033. if (length === void 0) { length = 100; }
  52034. if (!this.mesh) {
  52035. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  52036. }
  52037. var m = this.mesh.getWorldMatrix();
  52038. var origin = m.getTranslation();
  52039. var forward = new BABYLON.Vector3(0, 0, -1);
  52040. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  52041. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  52042. return new BABYLON.Ray(origin, direction, length);
  52043. };
  52044. return PoseEnabledController;
  52045. }(BABYLON.Gamepad));
  52046. BABYLON.PoseEnabledController = PoseEnabledController;
  52047. })(BABYLON || (BABYLON = {}));
  52048. //# sourceMappingURL=babylon.poseEnabledController.js.map
  52049. var BABYLON;
  52050. (function (BABYLON) {
  52051. var WebVRController = (function (_super) {
  52052. __extends(WebVRController, _super);
  52053. function WebVRController(vrGamepad) {
  52054. var _this = _super.call(this, vrGamepad) || this;
  52055. // Observables
  52056. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  52057. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  52058. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  52059. _this.onPadStateChangedObservable = new BABYLON.Observable();
  52060. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  52061. _this.pad = { x: 0, y: 0 };
  52062. // avoid GC, store state in a tmp object
  52063. _this._changes = {
  52064. pressChanged: false,
  52065. touchChanged: false,
  52066. valueChanged: false,
  52067. changed: false
  52068. };
  52069. _this._buttons = new Array(vrGamepad.buttons.length);
  52070. _this.hand = vrGamepad.hand;
  52071. return _this;
  52072. }
  52073. WebVRController.prototype.onButtonStateChange = function (callback) {
  52074. this._onButtonStateChange = callback;
  52075. };
  52076. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  52077. get: function () {
  52078. return this._defaultModel;
  52079. },
  52080. enumerable: true,
  52081. configurable: true
  52082. });
  52083. WebVRController.prototype.update = function () {
  52084. _super.prototype.update.call(this);
  52085. for (var index = 0; index < this._buttons.length; index++) {
  52086. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  52087. }
  52088. ;
  52089. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  52090. this.pad.x = this.leftStick.x;
  52091. this.pad.y = this.leftStick.y;
  52092. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  52093. }
  52094. };
  52095. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  52096. if (!newState) {
  52097. newState = {
  52098. pressed: false,
  52099. touched: false,
  52100. value: 0
  52101. };
  52102. }
  52103. if (!currentState) {
  52104. this._buttons[buttonIndex] = {
  52105. pressed: newState.pressed,
  52106. touched: newState.touched,
  52107. value: newState.value
  52108. };
  52109. return;
  52110. }
  52111. this._checkChanges(newState, currentState);
  52112. if (this._changes.changed) {
  52113. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  52114. this.handleButtonChange(buttonIndex, newState, this._changes);
  52115. }
  52116. this._buttons[buttonIndex].pressed = newState.pressed;
  52117. this._buttons[buttonIndex].touched = newState.touched;
  52118. // oculus triggers are never 0, thou not touched.
  52119. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  52120. };
  52121. WebVRController.prototype._checkChanges = function (newState, currentState) {
  52122. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  52123. this._changes.touchChanged = newState.touched !== currentState.touched;
  52124. this._changes.valueChanged = newState.value !== currentState.value;
  52125. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  52126. return this._changes;
  52127. };
  52128. WebVRController.prototype.dispose = function () {
  52129. _super.prototype.dispose.call(this);
  52130. this.onTriggerStateChangedObservable.clear();
  52131. this.onMainButtonStateChangedObservable.clear();
  52132. this.onSecondaryButtonStateChangedObservable.clear();
  52133. this.onPadStateChangedObservable.clear();
  52134. this.onPadValuesChangedObservable.clear();
  52135. };
  52136. return WebVRController;
  52137. }(BABYLON.PoseEnabledController));
  52138. BABYLON.WebVRController = WebVRController;
  52139. })(BABYLON || (BABYLON = {}));
  52140. //# sourceMappingURL=babylon.webVRController.js.map
  52141. var BABYLON;
  52142. (function (BABYLON) {
  52143. var OculusTouchController = (function (_super) {
  52144. __extends(OculusTouchController, _super);
  52145. function OculusTouchController(vrGamepad) {
  52146. var _this = _super.call(this, vrGamepad) || this;
  52147. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  52148. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  52149. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  52150. return _this;
  52151. }
  52152. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52153. var _this = this;
  52154. var meshName;
  52155. // Hand
  52156. if (this.hand === 'left') {
  52157. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  52158. }
  52159. else {
  52160. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  52161. }
  52162. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  52163. /*
  52164. Parent Mesh name: oculus_touch_left
  52165. - body
  52166. - trigger
  52167. - thumbstick
  52168. - grip
  52169. - button_y
  52170. - button_x
  52171. - button_enter
  52172. */
  52173. _this._defaultModel = newMeshes[1];
  52174. if (meshLoaded) {
  52175. meshLoaded(_this._defaultModel);
  52176. }
  52177. _this.attachToMesh(_this._defaultModel);
  52178. });
  52179. };
  52180. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  52181. // helper getters for left and right hand.
  52182. get: function () {
  52183. if (this.hand === 'right') {
  52184. return this.onMainButtonStateChangedObservable;
  52185. }
  52186. else {
  52187. throw new Error('No A button on left hand');
  52188. }
  52189. },
  52190. enumerable: true,
  52191. configurable: true
  52192. });
  52193. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  52194. get: function () {
  52195. if (this.hand === 'right') {
  52196. return this.onSecondaryButtonStateChangedObservable;
  52197. }
  52198. else {
  52199. throw new Error('No B button on left hand');
  52200. }
  52201. },
  52202. enumerable: true,
  52203. configurable: true
  52204. });
  52205. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  52206. get: function () {
  52207. if (this.hand === 'left') {
  52208. return this.onMainButtonStateChangedObservable;
  52209. }
  52210. else {
  52211. throw new Error('No X button on right hand');
  52212. }
  52213. },
  52214. enumerable: true,
  52215. configurable: true
  52216. });
  52217. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  52218. get: function () {
  52219. if (this.hand === 'left') {
  52220. return this.onSecondaryButtonStateChangedObservable;
  52221. }
  52222. else {
  52223. throw new Error('No Y button on right hand');
  52224. }
  52225. },
  52226. enumerable: true,
  52227. configurable: true
  52228. });
  52229. /*
  52230. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  52231. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  52232. 2) secondary trigger (same)
  52233. 3) A (right) X (left), touch, pressed = value
  52234. 4) B / Y
  52235. 5) thumb rest
  52236. */
  52237. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52238. var notifyObject = state; //{ state: state, changes: changes };
  52239. var triggerDirection = this.hand === 'right' ? -1 : 1;
  52240. switch (buttonIdx) {
  52241. case 0:
  52242. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  52243. return;
  52244. case 1:// index trigger
  52245. if (this._defaultModel) {
  52246. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  52247. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  52248. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  52249. }
  52250. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  52251. return;
  52252. case 2:// secondary trigger
  52253. if (this._defaultModel) {
  52254. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  52255. }
  52256. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  52257. return;
  52258. case 3:
  52259. if (this._defaultModel) {
  52260. if (notifyObject.pressed) {
  52261. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  52262. }
  52263. else {
  52264. (this._defaultModel.getChildren()[1]).position.y = 0;
  52265. }
  52266. }
  52267. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  52268. return;
  52269. case 4:
  52270. if (this._defaultModel) {
  52271. if (notifyObject.pressed) {
  52272. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  52273. }
  52274. else {
  52275. (this._defaultModel.getChildren()[2]).position.y = 0;
  52276. }
  52277. }
  52278. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  52279. return;
  52280. case 5:
  52281. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  52282. return;
  52283. }
  52284. };
  52285. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  52286. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  52287. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  52288. return OculusTouchController;
  52289. }(BABYLON.WebVRController));
  52290. BABYLON.OculusTouchController = OculusTouchController;
  52291. })(BABYLON || (BABYLON = {}));
  52292. //# sourceMappingURL=babylon.oculusTouchController.js.map
  52293. var BABYLON;
  52294. (function (BABYLON) {
  52295. var ViveController = (function (_super) {
  52296. __extends(ViveController, _super);
  52297. function ViveController(vrGamepad) {
  52298. var _this = _super.call(this, vrGamepad) || this;
  52299. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  52300. return _this;
  52301. }
  52302. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52303. var _this = this;
  52304. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  52305. /*
  52306. Parent Mesh name: ViveWand
  52307. - body
  52308. - r_gripper
  52309. - l_gripper
  52310. - menu_button
  52311. - system_button
  52312. - trackpad
  52313. - trigger
  52314. - LED
  52315. */
  52316. _this._defaultModel = newMeshes[1];
  52317. if (meshLoaded) {
  52318. meshLoaded(_this._defaultModel);
  52319. }
  52320. _this.attachToMesh(_this._defaultModel);
  52321. });
  52322. };
  52323. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  52324. get: function () {
  52325. return this.onMainButtonStateChangedObservable;
  52326. },
  52327. enumerable: true,
  52328. configurable: true
  52329. });
  52330. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  52331. get: function () {
  52332. return this.onMainButtonStateChangedObservable;
  52333. },
  52334. enumerable: true,
  52335. configurable: true
  52336. });
  52337. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  52338. get: function () {
  52339. return this.onSecondaryButtonStateChangedObservable;
  52340. },
  52341. enumerable: true,
  52342. configurable: true
  52343. });
  52344. /**
  52345. * Vive mapping:
  52346. * 0: touchpad
  52347. * 1: trigger
  52348. * 2: left AND right buttons
  52349. * 3: menu button
  52350. */
  52351. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52352. var notifyObject = state; //{ state: state, changes: changes };
  52353. switch (buttonIdx) {
  52354. case 0:
  52355. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  52356. return;
  52357. case 1:// index trigger
  52358. if (this._defaultModel) {
  52359. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  52360. }
  52361. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  52362. return;
  52363. case 2:// left AND right button
  52364. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  52365. return;
  52366. case 3:
  52367. if (this._defaultModel) {
  52368. if (notifyObject.pressed) {
  52369. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  52370. }
  52371. else {
  52372. (this._defaultModel.getChildren()[2]).position.y = 0;
  52373. }
  52374. }
  52375. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  52376. return;
  52377. }
  52378. };
  52379. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  52380. ViveController.MODEL_FILENAME = 'wand.babylon';
  52381. return ViveController;
  52382. }(BABYLON.WebVRController));
  52383. BABYLON.ViveController = ViveController;
  52384. })(BABYLON || (BABYLON = {}));
  52385. //# sourceMappingURL=babylon.viveController.js.map
  52386. var BABYLON;
  52387. (function (BABYLON) {
  52388. var GenericController = (function (_super) {
  52389. __extends(GenericController, _super);
  52390. function GenericController(vrGamepad) {
  52391. return _super.call(this, vrGamepad) || this;
  52392. }
  52393. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52394. var _this = this;
  52395. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  52396. _this._defaultModel = newMeshes[1];
  52397. if (meshLoaded) {
  52398. meshLoaded(_this._defaultModel);
  52399. }
  52400. _this.attachToMesh(_this._defaultModel);
  52401. });
  52402. };
  52403. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52404. console.log("Button id: " + buttonIdx + "state: ");
  52405. console.dir(state);
  52406. };
  52407. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  52408. GenericController.MODEL_FILENAME = 'generic.babylon';
  52409. return GenericController;
  52410. }(BABYLON.WebVRController));
  52411. BABYLON.GenericController = GenericController;
  52412. })(BABYLON || (BABYLON = {}));
  52413. //# sourceMappingURL=babylon.genericController.js.map
  52414. var BABYLON;
  52415. (function (BABYLON) {
  52416. var LoadedMeshInfo = (function () {
  52417. function LoadedMeshInfo() {
  52418. this.buttonMeshes = {};
  52419. this.axisMeshes = {};
  52420. }
  52421. return LoadedMeshInfo;
  52422. }());
  52423. var WindowsMotionController = (function (_super) {
  52424. __extends(WindowsMotionController, _super);
  52425. function WindowsMotionController(vrGamepad) {
  52426. var _this = _super.call(this, vrGamepad) || this;
  52427. _this._mapping = {
  52428. // Semantic button names
  52429. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  52430. // A mapping of the button name to glTF model node name
  52431. // that should be transformed by button value.
  52432. buttonMeshNames: {
  52433. 'trigger': 'SELECT',
  52434. 'menu': 'MENU',
  52435. 'grip': 'GRASP',
  52436. 'thumbstick': 'THUMBSTICK_PRESS',
  52437. 'trackpad': 'TOUCHPAD_PRESS'
  52438. },
  52439. // This mapping is used to translate from the Motion Controller to Babylon semantics
  52440. buttonObservableNames: {
  52441. 'trigger': 'onTriggerStateChangedObservable',
  52442. 'menu': 'onSecondaryButtonStateChangedObservable',
  52443. 'grip': 'onMainButtonStateChangedObservable',
  52444. 'thumbstick': 'onPadStateChangedObservable',
  52445. 'trackpad': 'onTrackpadChangedObservable'
  52446. },
  52447. // A mapping of the axis name to glTF model node name
  52448. // that should be transformed by axis value.
  52449. // This array mirrors the browserGamepad.axes array, such that
  52450. // the mesh corresponding to axis 0 is in this array index 0.
  52451. axisMeshNames: [
  52452. 'THUMBSTICK_X',
  52453. 'THUMBSTICK_Y',
  52454. 'TOUCHPAD_TOUCH_X',
  52455. 'TOUCHPAD_TOUCH_Y'
  52456. ],
  52457. pointingPoseMeshName: 'POINTING_POSE'
  52458. };
  52459. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  52460. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  52461. _this._loadedMeshInfo = null;
  52462. return _this;
  52463. }
  52464. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  52465. get: function () {
  52466. return this.onTriggerStateChangedObservable;
  52467. },
  52468. enumerable: true,
  52469. configurable: true
  52470. });
  52471. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  52472. get: function () {
  52473. return this.onSecondaryButtonStateChangedObservable;
  52474. },
  52475. enumerable: true,
  52476. configurable: true
  52477. });
  52478. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  52479. get: function () {
  52480. return this.onMainButtonStateChangedObservable;
  52481. },
  52482. enumerable: true,
  52483. configurable: true
  52484. });
  52485. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  52486. get: function () {
  52487. return this.onPadStateChangedObservable;
  52488. },
  52489. enumerable: true,
  52490. configurable: true
  52491. });
  52492. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  52493. get: function () {
  52494. return this.onTrackpadChangedObservable;
  52495. },
  52496. enumerable: true,
  52497. configurable: true
  52498. });
  52499. /**
  52500. * Called once per frame by the engine.
  52501. */
  52502. WindowsMotionController.prototype.update = function () {
  52503. _super.prototype.update.call(this);
  52504. // Only need to animate axes if there is a loaded mesh
  52505. if (this._loadedMeshInfo) {
  52506. if (this.browserGamepad.axes) {
  52507. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  52508. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  52509. }
  52510. }
  52511. }
  52512. };
  52513. /**
  52514. * Called once for each button that changed state since the last frame
  52515. * @param buttonIdx Which button index changed
  52516. * @param state New state of the button
  52517. * @param changes Which properties on the state changed since last frame
  52518. */
  52519. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52520. var buttonName = this._mapping.buttons[buttonIdx];
  52521. if (!buttonName) {
  52522. return;
  52523. }
  52524. // Only emit events for buttons that we know how to map from index to name
  52525. var observable = this[this._mapping.buttonObservableNames[buttonName]];
  52526. if (observable) {
  52527. observable.notifyObservers(state);
  52528. }
  52529. this.lerpButtonTransform(buttonName, state.value);
  52530. };
  52531. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  52532. // If there is no loaded mesh, there is nothing to transform.
  52533. if (!this._loadedMeshInfo) {
  52534. return;
  52535. }
  52536. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  52537. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  52538. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  52539. };
  52540. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  52541. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  52542. if (!meshInfo) {
  52543. return;
  52544. }
  52545. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  52546. var lerpValue = axisValue * 0.5 + 0.5;
  52547. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  52548. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  52549. };
  52550. /**
  52551. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  52552. * @param scene scene in which to add meshes
  52553. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  52554. */
  52555. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  52556. var _this = this;
  52557. if (forceDefault === void 0) { forceDefault = false; }
  52558. var path;
  52559. var filename;
  52560. // Checking if GLB loader is present
  52561. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  52562. // Determine the device specific folder based on the ID suffix
  52563. var device = 'default';
  52564. if (this.id && !forceDefault) {
  52565. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  52566. device = ((match && match[0]) || device);
  52567. }
  52568. // Hand
  52569. if (this.hand === 'left') {
  52570. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  52571. }
  52572. else {
  52573. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  52574. }
  52575. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  52576. }
  52577. else {
  52578. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  52579. path = BABYLON.GenericController.MODEL_BASE_URL;
  52580. filename = BABYLON.GenericController.MODEL_FILENAME;
  52581. }
  52582. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  52583. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  52584. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  52585. if (!_this._loadedMeshInfo) {
  52586. return;
  52587. }
  52588. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  52589. _this.attachToMesh(_this._defaultModel);
  52590. if (meshLoaded) {
  52591. meshLoaded(_this._defaultModel);
  52592. }
  52593. }, null, function (scene, message) {
  52594. BABYLON.Tools.Log(message);
  52595. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  52596. if (!forceDefault) {
  52597. _this.initControllerMesh(scene, meshLoaded, true);
  52598. }
  52599. });
  52600. };
  52601. /**
  52602. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  52603. * can be transformed by button presses and axes values, based on this._mapping.
  52604. *
  52605. * @param scene scene in which the meshes exist
  52606. * @param meshes list of meshes that make up the controller model to process
  52607. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  52608. */
  52609. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  52610. var loadedMeshInfo = null;
  52611. // Create a new mesh to contain the glTF hierarchy
  52612. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  52613. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  52614. var childMesh = null;
  52615. for (var i = 0; i < meshes.length; i++) {
  52616. var mesh = meshes[i];
  52617. if (!mesh.parent) {
  52618. // Exclude controller meshes from picking results
  52619. mesh.isPickable = false;
  52620. // Handle root node, attach to the new parentMesh
  52621. childMesh = mesh;
  52622. break;
  52623. }
  52624. }
  52625. if (childMesh) {
  52626. childMesh.setParent(parentMesh);
  52627. // Create our mesh info. Note that this method will always return non-null.
  52628. loadedMeshInfo = this.createMeshInfo(parentMesh);
  52629. }
  52630. else {
  52631. BABYLON.Tools.Warn('Could not find root node in model file.');
  52632. }
  52633. return loadedMeshInfo;
  52634. };
  52635. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  52636. var loadedMeshInfo = new LoadedMeshInfo();
  52637. var i;
  52638. loadedMeshInfo.rootNode = rootNode;
  52639. // Reset the caches
  52640. loadedMeshInfo.buttonMeshes = {};
  52641. loadedMeshInfo.axisMeshes = {};
  52642. // Button Meshes
  52643. for (i = 0; i < this._mapping.buttons.length; i++) {
  52644. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  52645. if (!buttonMeshName) {
  52646. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  52647. continue;
  52648. }
  52649. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  52650. if (!buttonMesh) {
  52651. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  52652. continue;
  52653. }
  52654. var buttonMeshInfo = {
  52655. index: i,
  52656. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  52657. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  52658. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  52659. };
  52660. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  52661. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  52662. }
  52663. else {
  52664. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  52665. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  52666. '(VALUE: ' + !!buttonMeshInfo.value +
  52667. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  52668. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  52669. ')');
  52670. }
  52671. }
  52672. // Axis Meshes
  52673. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  52674. var axisMeshName = this._mapping.axisMeshNames[i];
  52675. if (!axisMeshName) {
  52676. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  52677. continue;
  52678. }
  52679. var axisMesh = getChildByName(rootNode, axisMeshName);
  52680. if (!axisMesh) {
  52681. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  52682. continue;
  52683. }
  52684. var axisMeshInfo = {
  52685. index: i,
  52686. value: getImmediateChildByName(axisMesh, 'VALUE'),
  52687. min: getImmediateChildByName(axisMesh, 'MIN'),
  52688. max: getImmediateChildByName(axisMesh, 'MAX')
  52689. };
  52690. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  52691. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  52692. }
  52693. else {
  52694. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  52695. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  52696. '(VALUE: ' + !!axisMeshInfo.value +
  52697. ', MIN: ' + !!axisMeshInfo.min +
  52698. ', MAX:' + !!axisMeshInfo.max +
  52699. ')');
  52700. }
  52701. }
  52702. // Pointing Ray
  52703. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  52704. if (!loadedMeshInfo.pointingPoseNode) {
  52705. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  52706. }
  52707. return loadedMeshInfo;
  52708. // Look through all children recursively. This will return null if no mesh exists with the given name.
  52709. function getChildByName(node, name) {
  52710. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  52711. }
  52712. // Look through only immediate children. This will return null if no mesh exists with the given name.
  52713. function getImmediateChildByName(node, name) {
  52714. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  52715. }
  52716. };
  52717. WindowsMotionController.prototype.getForwardRay = function (length) {
  52718. if (length === void 0) { length = 100; }
  52719. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  52720. return _super.prototype.getForwardRay.call(this, length);
  52721. }
  52722. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  52723. var origin = m.getTranslation();
  52724. var forward = new BABYLON.Vector3(0, 0, -1);
  52725. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  52726. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  52727. return new BABYLON.Ray(origin, direction, length);
  52728. };
  52729. WindowsMotionController.prototype.dispose = function () {
  52730. _super.prototype.dispose.call(this);
  52731. this.onTrackpadChangedObservable.clear();
  52732. };
  52733. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  52734. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  52735. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  52736. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  52737. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  52738. return WindowsMotionController;
  52739. }(BABYLON.WebVRController));
  52740. BABYLON.WindowsMotionController = WindowsMotionController;
  52741. })(BABYLON || (BABYLON = {}));
  52742. //# sourceMappingURL=babylon.windowsMotionController.js.map
  52743. /// <reference path="babylon.targetCamera.ts" />
  52744. var BABYLON;
  52745. (function (BABYLON) {
  52746. var FollowCamera = (function (_super) {
  52747. __extends(FollowCamera, _super);
  52748. function FollowCamera(name, position, scene, lockedTarget) {
  52749. var _this = _super.call(this, name, position, scene) || this;
  52750. _this.radius = 12;
  52751. _this.rotationOffset = 0;
  52752. _this.heightOffset = 4;
  52753. _this.cameraAcceleration = 0.05;
  52754. _this.maxCameraSpeed = 20;
  52755. _this.lockedTarget = lockedTarget;
  52756. return _this;
  52757. }
  52758. FollowCamera.prototype.getRadians = function (degrees) {
  52759. return degrees * Math.PI / 180;
  52760. };
  52761. FollowCamera.prototype.follow = function (cameraTarget) {
  52762. if (!cameraTarget)
  52763. return;
  52764. var yRotation;
  52765. if (cameraTarget.rotationQuaternion) {
  52766. var rotMatrix = new BABYLON.Matrix();
  52767. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  52768. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  52769. }
  52770. else {
  52771. yRotation = cameraTarget.rotation.y;
  52772. }
  52773. var radians = this.getRadians(this.rotationOffset) + yRotation;
  52774. var targetPosition = cameraTarget.getAbsolutePosition();
  52775. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  52776. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  52777. var dx = targetX - this.position.x;
  52778. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  52779. var dz = (targetZ) - this.position.z;
  52780. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  52781. var vy = dy * this.cameraAcceleration;
  52782. var vz = dz * this.cameraAcceleration * 2;
  52783. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  52784. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  52785. }
  52786. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  52787. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  52788. }
  52789. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  52790. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  52791. }
  52792. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  52793. this.setTarget(targetPosition);
  52794. };
  52795. FollowCamera.prototype._checkInputs = function () {
  52796. _super.prototype._checkInputs.call(this);
  52797. this.follow(this.lockedTarget);
  52798. };
  52799. FollowCamera.prototype.getClassName = function () {
  52800. return "FollowCamera";
  52801. };
  52802. __decorate([
  52803. BABYLON.serialize()
  52804. ], FollowCamera.prototype, "radius", void 0);
  52805. __decorate([
  52806. BABYLON.serialize()
  52807. ], FollowCamera.prototype, "rotationOffset", void 0);
  52808. __decorate([
  52809. BABYLON.serialize()
  52810. ], FollowCamera.prototype, "heightOffset", void 0);
  52811. __decorate([
  52812. BABYLON.serialize()
  52813. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  52814. __decorate([
  52815. BABYLON.serialize()
  52816. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  52817. __decorate([
  52818. BABYLON.serializeAsMeshReference("lockedTargetId")
  52819. ], FollowCamera.prototype, "lockedTarget", void 0);
  52820. return FollowCamera;
  52821. }(BABYLON.TargetCamera));
  52822. BABYLON.FollowCamera = FollowCamera;
  52823. var ArcFollowCamera = (function (_super) {
  52824. __extends(ArcFollowCamera, _super);
  52825. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  52826. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  52827. _this.alpha = alpha;
  52828. _this.beta = beta;
  52829. _this.radius = radius;
  52830. _this.target = target;
  52831. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  52832. _this.follow();
  52833. return _this;
  52834. }
  52835. ArcFollowCamera.prototype.follow = function () {
  52836. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  52837. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  52838. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  52839. var targetPosition = this.target.getAbsolutePosition();
  52840. this.position = targetPosition.add(this._cartesianCoordinates);
  52841. this.setTarget(targetPosition);
  52842. };
  52843. ArcFollowCamera.prototype._checkInputs = function () {
  52844. _super.prototype._checkInputs.call(this);
  52845. this.follow();
  52846. };
  52847. ArcFollowCamera.prototype.getClassName = function () {
  52848. return "ArcFollowCamera";
  52849. };
  52850. return ArcFollowCamera;
  52851. }(BABYLON.TargetCamera));
  52852. BABYLON.ArcFollowCamera = ArcFollowCamera;
  52853. })(BABYLON || (BABYLON = {}));
  52854. //# sourceMappingURL=babylon.followCamera.js.map
  52855. /// <reference path="babylon.touchCamera.ts" />
  52856. var BABYLON;
  52857. (function (BABYLON) {
  52858. // We're mainly based on the logic defined into the FreeCamera code
  52859. var UniversalCamera = (function (_super) {
  52860. __extends(UniversalCamera, _super);
  52861. //-- end properties for backward compatibility for inputs
  52862. function UniversalCamera(name, position, scene) {
  52863. var _this = _super.call(this, name, position, scene) || this;
  52864. _this.inputs.addGamepad();
  52865. return _this;
  52866. }
  52867. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  52868. //-- Begin properties for backward compatibility for inputs
  52869. get: function () {
  52870. var gamepad = this.inputs.attached["gamepad"];
  52871. if (gamepad)
  52872. return gamepad.gamepadAngularSensibility;
  52873. },
  52874. set: function (value) {
  52875. var gamepad = this.inputs.attached["gamepad"];
  52876. if (gamepad)
  52877. gamepad.gamepadAngularSensibility = value;
  52878. },
  52879. enumerable: true,
  52880. configurable: true
  52881. });
  52882. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  52883. get: function () {
  52884. var gamepad = this.inputs.attached["gamepad"];
  52885. if (gamepad)
  52886. return gamepad.gamepadMoveSensibility;
  52887. },
  52888. set: function (value) {
  52889. var gamepad = this.inputs.attached["gamepad"];
  52890. if (gamepad)
  52891. gamepad.gamepadMoveSensibility = value;
  52892. },
  52893. enumerable: true,
  52894. configurable: true
  52895. });
  52896. UniversalCamera.prototype.getClassName = function () {
  52897. return "UniversalCamera";
  52898. };
  52899. return UniversalCamera;
  52900. }(BABYLON.TouchCamera));
  52901. BABYLON.UniversalCamera = UniversalCamera;
  52902. })(BABYLON || (BABYLON = {}));
  52903. //# sourceMappingURL=babylon.universalCamera.js.map
  52904. /// <reference path="babylon.universalCamera.ts" />
  52905. var BABYLON;
  52906. (function (BABYLON) {
  52907. // We're mainly based on the logic defined into the FreeCamera code
  52908. var GamepadCamera = (function (_super) {
  52909. __extends(GamepadCamera, _super);
  52910. //-- end properties for backward compatibility for inputs
  52911. function GamepadCamera(name, position, scene) {
  52912. return _super.call(this, name, position, scene) || this;
  52913. }
  52914. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  52915. //-- Begin properties for backward compatibility for inputs
  52916. get: function () {
  52917. var gamepad = this.inputs.attached["gamepad"];
  52918. if (gamepad)
  52919. return gamepad.gamepadAngularSensibility;
  52920. },
  52921. set: function (value) {
  52922. var gamepad = this.inputs.attached["gamepad"];
  52923. if (gamepad)
  52924. gamepad.gamepadAngularSensibility = value;
  52925. },
  52926. enumerable: true,
  52927. configurable: true
  52928. });
  52929. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  52930. get: function () {
  52931. var gamepad = this.inputs.attached["gamepad"];
  52932. if (gamepad)
  52933. return gamepad.gamepadMoveSensibility;
  52934. },
  52935. set: function (value) {
  52936. var gamepad = this.inputs.attached["gamepad"];
  52937. if (gamepad)
  52938. gamepad.gamepadMoveSensibility = value;
  52939. },
  52940. enumerable: true,
  52941. configurable: true
  52942. });
  52943. GamepadCamera.prototype.getClassName = function () {
  52944. return "GamepadCamera";
  52945. };
  52946. return GamepadCamera;
  52947. }(BABYLON.UniversalCamera));
  52948. BABYLON.GamepadCamera = GamepadCamera;
  52949. })(BABYLON || (BABYLON = {}));
  52950. //# sourceMappingURL=babylon.gamepadCamera.js.map
  52951. var BABYLON;
  52952. (function (BABYLON) {
  52953. var PostProcessRenderPipelineManager = (function () {
  52954. function PostProcessRenderPipelineManager() {
  52955. this._renderPipelines = {};
  52956. }
  52957. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  52958. this._renderPipelines[renderPipeline._name] = renderPipeline;
  52959. };
  52960. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  52961. var renderPipeline = this._renderPipelines[renderPipelineName];
  52962. if (!renderPipeline) {
  52963. return;
  52964. }
  52965. renderPipeline._attachCameras(cameras, unique);
  52966. };
  52967. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  52968. var renderPipeline = this._renderPipelines[renderPipelineName];
  52969. if (!renderPipeline) {
  52970. return;
  52971. }
  52972. renderPipeline._detachCameras(cameras);
  52973. };
  52974. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  52975. var renderPipeline = this._renderPipelines[renderPipelineName];
  52976. if (!renderPipeline) {
  52977. return;
  52978. }
  52979. renderPipeline._enableEffect(renderEffectName, cameras);
  52980. };
  52981. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  52982. var renderPipeline = this._renderPipelines[renderPipelineName];
  52983. if (!renderPipeline) {
  52984. return;
  52985. }
  52986. renderPipeline._disableEffect(renderEffectName, cameras);
  52987. };
  52988. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  52989. var renderPipeline = this._renderPipelines[renderPipelineName];
  52990. if (!renderPipeline) {
  52991. return;
  52992. }
  52993. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  52994. };
  52995. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  52996. var renderPipeline = this._renderPipelines[renderPipelineName];
  52997. if (!renderPipeline) {
  52998. return;
  52999. }
  53000. renderPipeline._disableDisplayOnlyPass(cameras);
  53001. };
  53002. PostProcessRenderPipelineManager.prototype.update = function () {
  53003. for (var renderPipelineName in this._renderPipelines) {
  53004. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  53005. var pipeline = this._renderPipelines[renderPipelineName];
  53006. if (!pipeline.isSupported) {
  53007. pipeline.dispose();
  53008. delete this._renderPipelines[renderPipelineName];
  53009. }
  53010. else {
  53011. pipeline._update();
  53012. }
  53013. }
  53014. }
  53015. };
  53016. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  53017. for (var renderPipelineName in this._renderPipelines) {
  53018. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  53019. var pipeline = this._renderPipelines[renderPipelineName];
  53020. pipeline._rebuild();
  53021. }
  53022. }
  53023. };
  53024. PostProcessRenderPipelineManager.prototype.dispose = function () {
  53025. for (var renderPipelineName in this._renderPipelines) {
  53026. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  53027. var pipeline = this._renderPipelines[renderPipelineName];
  53028. pipeline.dispose();
  53029. }
  53030. }
  53031. };
  53032. return PostProcessRenderPipelineManager;
  53033. }());
  53034. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  53035. })(BABYLON || (BABYLON = {}));
  53036. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  53037. var BABYLON;
  53038. (function (BABYLON) {
  53039. var PostProcessRenderPass = (function () {
  53040. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  53041. this._enabled = true;
  53042. this._refCount = 0;
  53043. this._name = name;
  53044. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  53045. this.setRenderList(renderList);
  53046. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  53047. this._renderTexture.onAfterRenderObservable.add(afterRender);
  53048. this._scene = scene;
  53049. this._renderList = renderList;
  53050. }
  53051. // private
  53052. PostProcessRenderPass.prototype._incRefCount = function () {
  53053. if (this._refCount === 0) {
  53054. this._scene.customRenderTargets.push(this._renderTexture);
  53055. }
  53056. return ++this._refCount;
  53057. };
  53058. PostProcessRenderPass.prototype._decRefCount = function () {
  53059. this._refCount--;
  53060. if (this._refCount <= 0) {
  53061. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  53062. }
  53063. return this._refCount;
  53064. };
  53065. PostProcessRenderPass.prototype._update = function () {
  53066. this.setRenderList(this._renderList);
  53067. };
  53068. // public
  53069. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  53070. this._renderTexture.renderList = renderList;
  53071. };
  53072. PostProcessRenderPass.prototype.getRenderTexture = function () {
  53073. return this._renderTexture;
  53074. };
  53075. return PostProcessRenderPass;
  53076. }());
  53077. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  53078. })(BABYLON || (BABYLON = {}));
  53079. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  53080. var BABYLON;
  53081. (function (BABYLON) {
  53082. var PostProcessRenderEffect = (function () {
  53083. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  53084. this._engine = engine;
  53085. this._name = name;
  53086. this._singleInstance = singleInstance || true;
  53087. this._getPostProcess = getPostProcess;
  53088. this._cameras = [];
  53089. this._indicesForCamera = [];
  53090. this._postProcesses = {};
  53091. this._renderPasses = {};
  53092. this._renderEffectAsPasses = {};
  53093. }
  53094. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  53095. get: function () {
  53096. for (var index in this._postProcesses) {
  53097. if (!this._postProcesses[index].isSupported) {
  53098. return false;
  53099. }
  53100. }
  53101. return true;
  53102. },
  53103. enumerable: true,
  53104. configurable: true
  53105. });
  53106. PostProcessRenderEffect.prototype._update = function () {
  53107. for (var renderPassName in this._renderPasses) {
  53108. this._renderPasses[renderPassName]._update();
  53109. }
  53110. };
  53111. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  53112. this._renderPasses[renderPass._name] = renderPass;
  53113. this._linkParameters();
  53114. };
  53115. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  53116. delete this._renderPasses[renderPass._name];
  53117. this._linkParameters();
  53118. };
  53119. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  53120. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  53121. this._linkParameters();
  53122. };
  53123. PostProcessRenderEffect.prototype.getPass = function (passName) {
  53124. for (var renderPassName in this._renderPasses) {
  53125. if (renderPassName === passName) {
  53126. return this._renderPasses[passName];
  53127. }
  53128. }
  53129. };
  53130. PostProcessRenderEffect.prototype.emptyPasses = function () {
  53131. this._renderPasses = {};
  53132. this._linkParameters();
  53133. };
  53134. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  53135. var cameraKey;
  53136. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53137. for (var i = 0; i < _cam.length; i++) {
  53138. var camera = _cam[i];
  53139. var cameraName = camera.name;
  53140. if (this._singleInstance) {
  53141. cameraKey = 0;
  53142. }
  53143. else {
  53144. cameraKey = cameraName;
  53145. }
  53146. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  53147. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  53148. if (!this._indicesForCamera[cameraName]) {
  53149. this._indicesForCamera[cameraName] = [];
  53150. }
  53151. this._indicesForCamera[cameraName].push(index);
  53152. if (this._cameras.indexOf(camera) === -1) {
  53153. this._cameras[cameraName] = camera;
  53154. }
  53155. for (var passName in this._renderPasses) {
  53156. this._renderPasses[passName]._incRefCount();
  53157. }
  53158. }
  53159. this._linkParameters();
  53160. };
  53161. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  53162. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53163. for (var i = 0; i < _cam.length; i++) {
  53164. var camera = _cam[i];
  53165. var cameraName = camera.name;
  53166. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  53167. var index = this._cameras.indexOf(cameraName);
  53168. this._indicesForCamera.splice(index, 1);
  53169. this._cameras.splice(index, 1);
  53170. for (var passName in this._renderPasses) {
  53171. this._renderPasses[passName]._decRefCount();
  53172. }
  53173. }
  53174. };
  53175. PostProcessRenderEffect.prototype._enable = function (cameras) {
  53176. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53177. for (var i = 0; i < _cam.length; i++) {
  53178. var camera = _cam[i];
  53179. var cameraName = camera.name;
  53180. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  53181. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  53182. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  53183. }
  53184. }
  53185. for (var passName in this._renderPasses) {
  53186. this._renderPasses[passName]._incRefCount();
  53187. }
  53188. }
  53189. };
  53190. PostProcessRenderEffect.prototype._disable = function (cameras) {
  53191. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53192. for (var i = 0; i < _cam.length; i++) {
  53193. var camera = _cam[i];
  53194. var cameraName = camera.Name;
  53195. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  53196. for (var passName in this._renderPasses) {
  53197. this._renderPasses[passName]._decRefCount();
  53198. }
  53199. }
  53200. };
  53201. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  53202. if (this._singleInstance) {
  53203. return this._postProcesses[0];
  53204. }
  53205. else {
  53206. return this._postProcesses[camera.name];
  53207. }
  53208. };
  53209. PostProcessRenderEffect.prototype._linkParameters = function () {
  53210. var _this = this;
  53211. for (var index in this._postProcesses) {
  53212. if (this.applyParameters) {
  53213. this.applyParameters(this._postProcesses[index]);
  53214. }
  53215. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  53216. _this._linkTextures(effect);
  53217. });
  53218. }
  53219. };
  53220. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  53221. for (var renderPassName in this._renderPasses) {
  53222. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  53223. }
  53224. for (var renderEffectName in this._renderEffectAsPasses) {
  53225. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  53226. }
  53227. };
  53228. return PostProcessRenderEffect;
  53229. }());
  53230. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  53231. })(BABYLON || (BABYLON = {}));
  53232. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  53233. var BABYLON;
  53234. (function (BABYLON) {
  53235. var PostProcessRenderPipeline = (function () {
  53236. function PostProcessRenderPipeline(engine, name) {
  53237. this._engine = engine;
  53238. this._name = name;
  53239. this._renderEffects = new Array();
  53240. this._renderEffectsForIsolatedPass = new Array();
  53241. this._cameras = [];
  53242. }
  53243. PostProcessRenderPipeline.prototype.getClassName = function () {
  53244. return "PostProcessRenderPipeline";
  53245. };
  53246. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  53247. get: function () {
  53248. for (var renderEffectName in this._renderEffects) {
  53249. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53250. if (!this._renderEffects[renderEffectName].isSupported) {
  53251. return false;
  53252. }
  53253. }
  53254. }
  53255. return true;
  53256. },
  53257. enumerable: true,
  53258. configurable: true
  53259. });
  53260. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  53261. this._renderEffects[renderEffect._name] = renderEffect;
  53262. };
  53263. // private
  53264. PostProcessRenderPipeline.prototype._rebuild = function () {
  53265. };
  53266. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  53267. var renderEffects = this._renderEffects[renderEffectName];
  53268. if (!renderEffects) {
  53269. return;
  53270. }
  53271. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  53272. };
  53273. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  53274. var renderEffects = this._renderEffects[renderEffectName];
  53275. if (!renderEffects) {
  53276. return;
  53277. }
  53278. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  53279. };
  53280. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  53281. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53282. var indicesToDelete = [];
  53283. var i;
  53284. for (i = 0; i < _cam.length; i++) {
  53285. var camera = _cam[i];
  53286. var cameraName = camera.name;
  53287. if (this._cameras.indexOf(camera) === -1) {
  53288. this._cameras[cameraName] = camera;
  53289. }
  53290. else if (unique) {
  53291. indicesToDelete.push(i);
  53292. }
  53293. }
  53294. for (i = 0; i < indicesToDelete.length; i++) {
  53295. cameras.splice(indicesToDelete[i], 1);
  53296. }
  53297. for (var renderEffectName in this._renderEffects) {
  53298. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53299. this._renderEffects[renderEffectName]._attachCameras(_cam);
  53300. }
  53301. }
  53302. };
  53303. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  53304. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53305. for (var renderEffectName in this._renderEffects) {
  53306. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53307. this._renderEffects[renderEffectName]._detachCameras(_cam);
  53308. }
  53309. }
  53310. for (var i = 0; i < _cam.length; i++) {
  53311. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  53312. }
  53313. };
  53314. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  53315. var _this = this;
  53316. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53317. var pass = null;
  53318. var renderEffectName;
  53319. for (renderEffectName in this._renderEffects) {
  53320. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53321. pass = this._renderEffects[renderEffectName].getPass(passName);
  53322. if (pass != null) {
  53323. break;
  53324. }
  53325. }
  53326. }
  53327. if (pass === null) {
  53328. return;
  53329. }
  53330. for (renderEffectName in this._renderEffects) {
  53331. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53332. this._renderEffects[renderEffectName]._disable(_cam);
  53333. }
  53334. }
  53335. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  53336. for (var i = 0; i < _cam.length; i++) {
  53337. var camera = _cam[i];
  53338. var cameraName = camera.name;
  53339. 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); });
  53340. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  53341. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  53342. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  53343. }
  53344. };
  53345. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  53346. var _this = this;
  53347. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53348. for (var i = 0; i < _cam.length; i++) {
  53349. var camera = _cam[i];
  53350. var cameraName = camera.name;
  53351. 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); });
  53352. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  53353. }
  53354. for (var renderEffectName in this._renderEffects) {
  53355. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53356. this._renderEffects[renderEffectName]._enable(_cam);
  53357. }
  53358. }
  53359. };
  53360. PostProcessRenderPipeline.prototype._update = function () {
  53361. for (var renderEffectName in this._renderEffects) {
  53362. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53363. this._renderEffects[renderEffectName]._update();
  53364. }
  53365. }
  53366. for (var i = 0; i < this._cameras.length; i++) {
  53367. var cameraName = this._cameras[i].name;
  53368. if (this._renderEffectsForIsolatedPass[cameraName]) {
  53369. this._renderEffectsForIsolatedPass[cameraName]._update();
  53370. }
  53371. }
  53372. };
  53373. PostProcessRenderPipeline.prototype._reset = function () {
  53374. this._renderEffects = new Array();
  53375. this._renderEffectsForIsolatedPass = new Array();
  53376. };
  53377. PostProcessRenderPipeline.prototype.dispose = function () {
  53378. // Must be implemented by children
  53379. };
  53380. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  53381. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  53382. __decorate([
  53383. BABYLON.serialize()
  53384. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  53385. return PostProcessRenderPipeline;
  53386. }());
  53387. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  53388. })(BABYLON || (BABYLON = {}));
  53389. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  53390. var BABYLON;
  53391. (function (BABYLON) {
  53392. var DepthRenderer = (function () {
  53393. function DepthRenderer(scene, type) {
  53394. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53395. var _this = this;
  53396. this._viewMatrix = BABYLON.Matrix.Zero();
  53397. this._projectionMatrix = BABYLON.Matrix.Zero();
  53398. this._transformMatrix = BABYLON.Matrix.Zero();
  53399. this._worldViewProjection = BABYLON.Matrix.Zero();
  53400. this._scene = scene;
  53401. var engine = scene.getEngine();
  53402. // Render target
  53403. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53404. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53405. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53406. this._depthMap.refreshRate = 1;
  53407. this._depthMap.renderParticles = false;
  53408. this._depthMap.renderList = null;
  53409. // set default depth value to 1.0 (far away)
  53410. this._depthMap.onClearObservable.add(function (engine) {
  53411. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53412. });
  53413. // Custom render function
  53414. var renderSubMesh = function (subMesh) {
  53415. var mesh = subMesh.getRenderingMesh();
  53416. var scene = _this._scene;
  53417. var engine = scene.getEngine();
  53418. // Culling
  53419. engine.setState(subMesh.getMaterial().backFaceCulling);
  53420. // Managing instances
  53421. var batch = mesh._getInstancesRenderList(subMesh._id);
  53422. if (batch.mustReturn) {
  53423. return;
  53424. }
  53425. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  53426. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53427. engine.enableEffect(_this._effect);
  53428. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53429. var material = subMesh.getMaterial();
  53430. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53431. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  53432. // Alpha test
  53433. if (material && material.needAlphaTesting()) {
  53434. var alphaTexture = material.getAlphaTestTexture();
  53435. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53436. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53437. }
  53438. // Bones
  53439. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53440. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53441. }
  53442. // Draw
  53443. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53444. }
  53445. };
  53446. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53447. var index;
  53448. if (depthOnlySubMeshes.length) {
  53449. engine.setColorWrite(false);
  53450. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53451. renderSubMesh(depthOnlySubMeshes.data[index]);
  53452. }
  53453. engine.setColorWrite(true);
  53454. }
  53455. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53456. renderSubMesh(opaqueSubMeshes.data[index]);
  53457. }
  53458. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53459. renderSubMesh(alphaTestSubMeshes.data[index]);
  53460. }
  53461. };
  53462. }
  53463. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  53464. var material = subMesh.getMaterial();
  53465. if (material.disableDepthWrite) {
  53466. return false;
  53467. }
  53468. var defines = [];
  53469. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53470. var mesh = subMesh.getMesh();
  53471. var scene = mesh.getScene();
  53472. // Alpha test
  53473. if (material && material.needAlphaTesting()) {
  53474. defines.push("#define ALPHATEST");
  53475. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53476. attribs.push(BABYLON.VertexBuffer.UVKind);
  53477. defines.push("#define UV1");
  53478. }
  53479. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53480. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53481. defines.push("#define UV2");
  53482. }
  53483. }
  53484. // Bones
  53485. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53486. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53487. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53488. if (mesh.numBoneInfluencers > 4) {
  53489. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53490. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53491. }
  53492. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53493. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53494. }
  53495. else {
  53496. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53497. }
  53498. // Instances
  53499. if (useInstances) {
  53500. defines.push("#define INSTANCES");
  53501. attribs.push("world0");
  53502. attribs.push("world1");
  53503. attribs.push("world2");
  53504. attribs.push("world3");
  53505. }
  53506. // Get correct effect
  53507. var join = defines.join("\n");
  53508. if (this._cachedDefines !== join) {
  53509. this._cachedDefines = join;
  53510. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  53511. }
  53512. return this._effect.isReady();
  53513. };
  53514. DepthRenderer.prototype.getDepthMap = function () {
  53515. return this._depthMap;
  53516. };
  53517. // Methods
  53518. DepthRenderer.prototype.dispose = function () {
  53519. this._depthMap.dispose();
  53520. };
  53521. return DepthRenderer;
  53522. }());
  53523. BABYLON.DepthRenderer = DepthRenderer;
  53524. })(BABYLON || (BABYLON = {}));
  53525. //# sourceMappingURL=babylon.depthRenderer.js.map
  53526. var BABYLON;
  53527. (function (BABYLON) {
  53528. var SSAORenderingPipeline = (function (_super) {
  53529. __extends(SSAORenderingPipeline, _super);
  53530. /**
  53531. * @constructor
  53532. * @param {string} name - The rendering pipeline name
  53533. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53534. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  53535. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53536. */
  53537. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  53538. var _this = _super.call(this, scene.getEngine(), name) || this;
  53539. // Members
  53540. /**
  53541. * The PassPostProcess id in the pipeline that contains the original scene color
  53542. * @type {string}
  53543. */
  53544. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53545. /**
  53546. * The SSAO PostProcess id in the pipeline
  53547. * @type {string}
  53548. */
  53549. _this.SSAORenderEffect = "SSAORenderEffect";
  53550. /**
  53551. * The horizontal blur PostProcess id in the pipeline
  53552. * @type {string}
  53553. */
  53554. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53555. /**
  53556. * The vertical blur PostProcess id in the pipeline
  53557. * @type {string}
  53558. */
  53559. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53560. /**
  53561. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53562. * @type {string}
  53563. */
  53564. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53565. /**
  53566. * The output strength of the SSAO post-process. Default value is 1.0.
  53567. * @type {number}
  53568. */
  53569. _this.totalStrength = 1.0;
  53570. /**
  53571. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  53572. * @type {number}
  53573. */
  53574. _this.radius = 0.0001;
  53575. /**
  53576. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  53577. * Must not be equal to fallOff and superior to fallOff.
  53578. * Default value is 0.975
  53579. * @type {number}
  53580. */
  53581. _this.area = 0.0075;
  53582. /**
  53583. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  53584. * Must not be equal to area and inferior to area.
  53585. * Default value is 0.0
  53586. * @type {number}
  53587. */
  53588. _this.fallOff = 0.000001;
  53589. /**
  53590. * The base color of the SSAO post-process
  53591. * The final result is "base + ssao" between [0, 1]
  53592. * @type {number}
  53593. */
  53594. _this.base = 0.5;
  53595. _this._firstUpdate = true;
  53596. _this._scene = scene;
  53597. // Set up assets
  53598. _this._createRandomTexture();
  53599. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53600. var ssaoRatio = ratio.ssaoRatio || ratio;
  53601. var combineRatio = ratio.combineRatio || ratio;
  53602. _this._ratio = {
  53603. ssaoRatio: ssaoRatio,
  53604. combineRatio: combineRatio
  53605. };
  53606. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53607. _this._createSSAOPostProcess(ssaoRatio);
  53608. _this._createBlurPostProcess(ssaoRatio);
  53609. _this._createSSAOCombinePostProcess(combineRatio);
  53610. // Set up pipeline
  53611. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53612. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53613. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53614. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53615. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53616. // Finish
  53617. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53618. if (cameras)
  53619. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53620. return _this;
  53621. }
  53622. // Public Methods
  53623. /**
  53624. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53625. */
  53626. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53627. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53628. for (var i = 0; i < this._scene.cameras.length; i++) {
  53629. var camera = this._scene.cameras[i];
  53630. this._originalColorPostProcess.dispose(camera);
  53631. this._ssaoPostProcess.dispose(camera);
  53632. this._blurHPostProcess.dispose(camera);
  53633. this._blurVPostProcess.dispose(camera);
  53634. this._ssaoCombinePostProcess.dispose(camera);
  53635. }
  53636. this._randomTexture.dispose();
  53637. if (disableDepthRender)
  53638. this._scene.disableDepthRenderer();
  53639. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53640. _super.prototype.dispose.call(this);
  53641. };
  53642. // Private Methods
  53643. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53644. var _this = this;
  53645. /*
  53646. var samplerOffsets = [
  53647. -8.0, -6.0, -4.0, -2.0,
  53648. 0.0,
  53649. 2.0, 4.0, 6.0, 8.0
  53650. ];
  53651. */
  53652. var samples = 16;
  53653. var samplerOffsets = [];
  53654. for (var i = -8; i < 8; i++) {
  53655. samplerOffsets.push(i * 2);
  53656. }
  53657. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  53658. this._blurHPostProcess.onApply = function (effect) {
  53659. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53660. effect.setTexture("depthSampler", _this._depthTexture);
  53661. if (_this._firstUpdate) {
  53662. effect.setArray("samplerOffsets", samplerOffsets);
  53663. }
  53664. };
  53665. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  53666. this._blurVPostProcess.onApply = function (effect) {
  53667. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53668. effect.setTexture("depthSampler", _this._depthTexture);
  53669. if (_this._firstUpdate) {
  53670. effect.setArray("samplerOffsets", samplerOffsets);
  53671. _this._firstUpdate = false;
  53672. }
  53673. };
  53674. };
  53675. SSAORenderingPipeline.prototype._rebuild = function () {
  53676. this._firstUpdate = true;
  53677. _super.prototype._rebuild.call(this);
  53678. };
  53679. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53680. var _this = this;
  53681. var numSamples = 16;
  53682. var sampleSphere = [
  53683. 0.5381, 0.1856, -0.4319,
  53684. 0.1379, 0.2486, 0.4430,
  53685. 0.3371, 0.5679, -0.0057,
  53686. -0.6999, -0.0451, -0.0019,
  53687. 0.0689, -0.1598, -0.8547,
  53688. 0.0560, 0.0069, -0.1843,
  53689. -0.0146, 0.1402, 0.0762,
  53690. 0.0100, -0.1924, -0.0344,
  53691. -0.3577, -0.5301, -0.4358,
  53692. -0.3169, 0.1063, 0.0158,
  53693. 0.0103, -0.5869, 0.0046,
  53694. -0.0897, -0.4940, 0.3287,
  53695. 0.7119, -0.0154, -0.0918,
  53696. -0.0533, 0.0596, -0.5411,
  53697. 0.0352, -0.0631, 0.5460,
  53698. -0.4776, 0.2847, -0.0271
  53699. ];
  53700. var samplesFactor = 1.0 / numSamples;
  53701. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  53702. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53703. "area", "fallOff", "base", "range", "viewport"
  53704. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53705. var viewport = new BABYLON.Vector2(0, 0);
  53706. this._ssaoPostProcess.onApply = function (effect) {
  53707. if (_this._firstUpdate) {
  53708. effect.setArray3("sampleSphere", sampleSphere);
  53709. effect.setFloat("samplesFactor", samplesFactor);
  53710. effect.setFloat("randTextureTiles", 4.0);
  53711. }
  53712. effect.setFloat("totalStrength", _this.totalStrength);
  53713. effect.setFloat("radius", _this.radius);
  53714. effect.setFloat("area", _this.area);
  53715. effect.setFloat("fallOff", _this.fallOff);
  53716. effect.setFloat("base", _this.base);
  53717. effect.setTexture("textureSampler", _this._depthTexture);
  53718. effect.setTexture("randomSampler", _this._randomTexture);
  53719. };
  53720. };
  53721. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53722. var _this = this;
  53723. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53724. this._ssaoCombinePostProcess.onApply = function (effect) {
  53725. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53726. };
  53727. };
  53728. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  53729. var size = 512;
  53730. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53731. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53732. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53733. var context = this._randomTexture.getContext();
  53734. var rand = function (min, max) {
  53735. return Math.random() * (max - min) + min;
  53736. };
  53737. var randVector = BABYLON.Vector3.Zero();
  53738. for (var x = 0; x < size; x++) {
  53739. for (var y = 0; y < size; y++) {
  53740. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  53741. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  53742. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  53743. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53744. context.fillRect(x, y, 1, 1);
  53745. }
  53746. }
  53747. this._randomTexture.update(false);
  53748. };
  53749. __decorate([
  53750. BABYLON.serialize()
  53751. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  53752. __decorate([
  53753. BABYLON.serialize()
  53754. ], SSAORenderingPipeline.prototype, "radius", void 0);
  53755. __decorate([
  53756. BABYLON.serialize()
  53757. ], SSAORenderingPipeline.prototype, "area", void 0);
  53758. __decorate([
  53759. BABYLON.serialize()
  53760. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  53761. __decorate([
  53762. BABYLON.serialize()
  53763. ], SSAORenderingPipeline.prototype, "base", void 0);
  53764. __decorate([
  53765. BABYLON.serialize()
  53766. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  53767. return SSAORenderingPipeline;
  53768. }(BABYLON.PostProcessRenderPipeline));
  53769. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  53770. })(BABYLON || (BABYLON = {}));
  53771. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  53772. var BABYLON;
  53773. (function (BABYLON) {
  53774. var SSAO2RenderingPipeline = (function (_super) {
  53775. __extends(SSAO2RenderingPipeline, _super);
  53776. /**
  53777. * @constructor
  53778. * @param {string} name - The rendering pipeline name
  53779. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53780. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  53781. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53782. */
  53783. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  53784. var _this = _super.call(this, scene.getEngine(), name) || this;
  53785. // Members
  53786. /**
  53787. * The PassPostProcess id in the pipeline that contains the original scene color
  53788. * @type {string}
  53789. */
  53790. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53791. /**
  53792. * The SSAO PostProcess id in the pipeline
  53793. * @type {string}
  53794. */
  53795. _this.SSAORenderEffect = "SSAORenderEffect";
  53796. /**
  53797. * The horizontal blur PostProcess id in the pipeline
  53798. * @type {string}
  53799. */
  53800. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53801. /**
  53802. * The vertical blur PostProcess id in the pipeline
  53803. * @type {string}
  53804. */
  53805. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53806. /**
  53807. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53808. * @type {string}
  53809. */
  53810. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53811. /**
  53812. * The output strength of the SSAO post-process. Default value is 1.0.
  53813. * @type {number}
  53814. */
  53815. _this.totalStrength = 1.0;
  53816. /**
  53817. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  53818. * @type {number}
  53819. */
  53820. _this.maxZ = 100.0;
  53821. /**
  53822. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  53823. * @type {number}
  53824. */
  53825. _this.minZAspect = 0.2;
  53826. /**
  53827. * Number of samples used for the SSAO calculations. Default value is 8
  53828. * @type {number}
  53829. */
  53830. _this._samples = 8;
  53831. /**
  53832. * Are we using bilateral blur ?
  53833. * @type {boolean}
  53834. */
  53835. _this._expensiveBlur = true;
  53836. /**
  53837. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  53838. * @type {number}
  53839. */
  53840. _this.radius = 2.0;
  53841. /**
  53842. * The base color of the SSAO post-process
  53843. * The final result is "base + ssao" between [0, 1]
  53844. * @type {number}
  53845. */
  53846. _this.base = 0.1;
  53847. _this._firstUpdate = true;
  53848. _this._scene = scene;
  53849. if (!_this.isSupported) {
  53850. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  53851. return _this;
  53852. }
  53853. var ssaoRatio = ratio.ssaoRatio || ratio;
  53854. var blurRatio = ratio.blurRatio || ratio;
  53855. _this._ratio = {
  53856. ssaoRatio: ssaoRatio,
  53857. blurRatio: blurRatio
  53858. };
  53859. // Set up assets
  53860. _this._createRandomTexture();
  53861. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  53862. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  53863. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53864. _this._createSSAOPostProcess(1.0);
  53865. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  53866. _this._createSSAOCombinePostProcess(blurRatio);
  53867. // Set up pipeline
  53868. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53869. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53870. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53871. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53872. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53873. // Finish
  53874. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53875. if (cameras)
  53876. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53877. return _this;
  53878. }
  53879. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  53880. get: function () {
  53881. return this._samples;
  53882. },
  53883. set: function (n) {
  53884. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  53885. this._samples = n;
  53886. this._sampleSphere = this._generateHemisphere();
  53887. this._firstUpdate = true;
  53888. },
  53889. enumerable: true,
  53890. configurable: true
  53891. });
  53892. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  53893. get: function () {
  53894. return this._expensiveBlur;
  53895. },
  53896. set: function (b) {
  53897. this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  53898. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  53899. this._expensiveBlur = b;
  53900. this._firstUpdate = true;
  53901. },
  53902. enumerable: true,
  53903. configurable: true
  53904. });
  53905. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  53906. /**
  53907. * Support test.
  53908. * @type {boolean}
  53909. */
  53910. get: function () {
  53911. var engine = BABYLON.Engine.LastCreatedEngine;
  53912. return engine.getCaps().drawBuffersExtension;
  53913. },
  53914. enumerable: true,
  53915. configurable: true
  53916. });
  53917. // Public Methods
  53918. /**
  53919. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53920. */
  53921. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  53922. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  53923. for (var i = 0; i < this._scene.cameras.length; i++) {
  53924. var camera = this._scene.cameras[i];
  53925. this._originalColorPostProcess.dispose(camera);
  53926. this._ssaoPostProcess.dispose(camera);
  53927. this._blurHPostProcess.dispose(camera);
  53928. this._blurVPostProcess.dispose(camera);
  53929. this._ssaoCombinePostProcess.dispose(camera);
  53930. }
  53931. this._randomTexture.dispose();
  53932. if (disableGeometryBufferRenderer)
  53933. this._scene.disableGeometryBufferRenderer();
  53934. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53935. _super.prototype.dispose.call(this);
  53936. };
  53937. // Private Methods
  53938. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  53939. var _this = this;
  53940. var samples = 16;
  53941. this._samplerOffsets = [];
  53942. var expensive = this.expensiveBlur;
  53943. for (var i = -8; i < 8; i++) {
  53944. this._samplerOffsets.push(i * 2 + 0.5);
  53945. }
  53946. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  53947. this._blurHPostProcess.onApply = function (effect) {
  53948. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53949. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53950. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53951. effect.setFloat("radius", _this.radius);
  53952. effect.setTexture("depthSampler", _this._depthTexture);
  53953. if (_this._firstUpdate) {
  53954. effect.setArray("samplerOffsets", _this._samplerOffsets);
  53955. }
  53956. };
  53957. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  53958. this._blurVPostProcess.onApply = function (effect) {
  53959. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53960. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53961. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53962. effect.setFloat("radius", _this.radius);
  53963. effect.setTexture("depthSampler", _this._depthTexture);
  53964. if (_this._firstUpdate) {
  53965. effect.setArray("samplerOffsets", _this._samplerOffsets);
  53966. _this._firstUpdate = false;
  53967. }
  53968. };
  53969. };
  53970. SSAO2RenderingPipeline.prototype._rebuild = function () {
  53971. this._firstUpdate = true;
  53972. _super.prototype._rebuild.call(this);
  53973. };
  53974. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  53975. var numSamples = this.samples;
  53976. var result = [];
  53977. var vector, scale;
  53978. var rand = function (min, max) {
  53979. return Math.random() * (max - min) + min;
  53980. };
  53981. var lerp = function (start, end, percent) {
  53982. return (start + percent * (end - start));
  53983. };
  53984. var i = 0;
  53985. var normal = new BABYLON.Vector3(0, 0, 1);
  53986. while (i < numSamples) {
  53987. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  53988. vector.normalize();
  53989. scale = i / numSamples;
  53990. scale = lerp(0.1, 1.0, scale * scale);
  53991. vector.scaleInPlace(scale);
  53992. result.push(vector.x, vector.y, vector.z);
  53993. i++;
  53994. }
  53995. return result;
  53996. };
  53997. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53998. var _this = this;
  53999. var numSamples = this.samples;
  54000. this._sampleSphere = this._generateHemisphere();
  54001. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  54002. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  54003. "base", "range", "projection", "near", "far", "texelSize",
  54004. "xViewport", "yViewport", "maxZ", "minZAspect"
  54005. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  54006. this._ssaoPostProcess.onApply = function (effect) {
  54007. if (_this._firstUpdate) {
  54008. effect.setArray3("sampleSphere", _this._sampleSphere);
  54009. effect.setFloat("randTextureTiles", 4.0);
  54010. }
  54011. effect.setFloat("samplesFactor", 1 / _this.samples);
  54012. effect.setFloat("totalStrength", _this.totalStrength);
  54013. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  54014. effect.setFloat("radius", _this.radius);
  54015. effect.setFloat("maxZ", _this.maxZ);
  54016. effect.setFloat("minZAspect", _this.minZAspect);
  54017. effect.setFloat("base", _this.base);
  54018. effect.setFloat("near", _this._scene.activeCamera.minZ);
  54019. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  54020. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  54021. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  54022. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  54023. effect.setTexture("textureSampler", _this._depthTexture);
  54024. effect.setTexture("normalSampler", _this._normalTexture);
  54025. effect.setTexture("randomSampler", _this._randomTexture);
  54026. };
  54027. };
  54028. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  54029. var _this = this;
  54030. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54031. this._ssaoCombinePostProcess.onApply = function (effect) {
  54032. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  54033. };
  54034. };
  54035. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  54036. var size = 512;
  54037. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54038. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54039. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54040. var context = this._randomTexture.getContext();
  54041. var rand = function (min, max) {
  54042. return Math.random() * (max - min) + min;
  54043. };
  54044. var randVector = BABYLON.Vector3.Zero();
  54045. for (var x = 0; x < size; x++) {
  54046. for (var y = 0; y < size; y++) {
  54047. randVector.x = rand(0.0, 1.0);
  54048. randVector.y = rand(0.0, 1.0);
  54049. randVector.z = 0.0;
  54050. randVector.normalize();
  54051. randVector.scaleInPlace(255);
  54052. randVector.x = Math.floor(randVector.x);
  54053. randVector.y = Math.floor(randVector.y);
  54054. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  54055. context.fillRect(x, y, 1, 1);
  54056. }
  54057. }
  54058. this._randomTexture.update(false);
  54059. };
  54060. __decorate([
  54061. BABYLON.serialize()
  54062. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  54063. __decorate([
  54064. BABYLON.serialize()
  54065. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  54066. __decorate([
  54067. BABYLON.serialize()
  54068. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  54069. __decorate([
  54070. BABYLON.serialize("samples")
  54071. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  54072. __decorate([
  54073. BABYLON.serialize("expensiveBlur")
  54074. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  54075. __decorate([
  54076. BABYLON.serialize()
  54077. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  54078. __decorate([
  54079. BABYLON.serialize()
  54080. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  54081. __decorate([
  54082. BABYLON.serialize()
  54083. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  54084. return SSAO2RenderingPipeline;
  54085. }(BABYLON.PostProcessRenderPipeline));
  54086. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  54087. })(BABYLON || (BABYLON = {}));
  54088. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  54089. // BABYLON.JS Chromatic Aberration GLSL Shader
  54090. // Author: Olivier Guyot
  54091. // Separates very slightly R, G and B colors on the edges of the screen
  54092. // Inspired by Francois Tarlier & Martins Upitis
  54093. var BABYLON;
  54094. (function (BABYLON) {
  54095. var LensRenderingPipeline = (function (_super) {
  54096. __extends(LensRenderingPipeline, _super);
  54097. /**
  54098. * @constructor
  54099. *
  54100. * Effect parameters are as follow:
  54101. * {
  54102. * chromatic_aberration: number; // from 0 to x (1 for realism)
  54103. * edge_blur: number; // from 0 to x (1 for realism)
  54104. * distortion: number; // from 0 to x (1 for realism)
  54105. * grain_amount: number; // from 0 to 1
  54106. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  54107. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  54108. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  54109. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  54110. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  54111. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  54112. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  54113. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  54114. * }
  54115. * Note: if an effect parameter is unset, effect is disabled
  54116. *
  54117. * @param {string} name - The rendering pipeline name
  54118. * @param {object} parameters - An object containing all parameters (see above)
  54119. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54120. * @param {number} 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)
  54121. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54122. */
  54123. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  54124. if (ratio === void 0) { ratio = 1.0; }
  54125. var _this = _super.call(this, scene.getEngine(), name) || this;
  54126. // Lens effects can be of the following:
  54127. // - chromatic aberration (slight shift of RGB colors)
  54128. // - blur on the edge of the lens
  54129. // - lens distortion
  54130. // - depth-of-field blur & highlights enhancing
  54131. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  54132. // - grain effect (noise or custom texture)
  54133. // Two additional texture samplers are needed:
  54134. // - depth map (for depth-of-field)
  54135. // - grain texture
  54136. /**
  54137. * The chromatic aberration PostProcess id in the pipeline
  54138. * @type {string}
  54139. */
  54140. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  54141. /**
  54142. * The highlights enhancing PostProcess id in the pipeline
  54143. * @type {string}
  54144. */
  54145. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  54146. /**
  54147. * The depth-of-field PostProcess id in the pipeline
  54148. * @type {string}
  54149. */
  54150. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  54151. _this._scene = scene;
  54152. // Fetch texture samplers
  54153. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54154. if (parameters.grain_texture) {
  54155. _this._grainTexture = parameters.grain_texture;
  54156. }
  54157. else {
  54158. _this._createGrainTexture();
  54159. }
  54160. // save parameters
  54161. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  54162. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  54163. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  54164. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  54165. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  54166. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  54167. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  54168. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  54169. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  54170. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  54171. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  54172. // Create effects
  54173. _this._createChromaticAberrationPostProcess(ratio);
  54174. _this._createHighlightsPostProcess(ratio);
  54175. _this._createDepthOfFieldPostProcess(ratio / 4);
  54176. // Set up pipeline
  54177. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  54178. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  54179. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  54180. if (_this._highlightsGain === -1) {
  54181. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  54182. }
  54183. // Finish
  54184. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54185. if (cameras) {
  54186. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54187. }
  54188. return _this;
  54189. }
  54190. // public methods (self explanatory)
  54191. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  54192. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  54193. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  54194. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  54195. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  54196. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  54197. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  54198. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  54199. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  54200. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  54201. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  54202. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  54203. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  54204. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  54205. };
  54206. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  54207. this._highlightsPostProcess.updateEffect();
  54208. };
  54209. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  54210. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  54211. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  54212. this._highlightsGain = amount;
  54213. };
  54214. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  54215. if (this._highlightsGain === -1) {
  54216. this._highlightsGain = 1.0;
  54217. }
  54218. this._highlightsThreshold = amount;
  54219. };
  54220. LensRenderingPipeline.prototype.disableHighlights = function () {
  54221. this._highlightsGain = -1;
  54222. };
  54223. /**
  54224. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  54225. */
  54226. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54227. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54228. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54229. this._chromaticAberrationPostProcess = undefined;
  54230. this._highlightsPostProcess = undefined;
  54231. this._depthOfFieldPostProcess = undefined;
  54232. this._grainTexture.dispose();
  54233. if (disableDepthRender)
  54234. this._scene.disableDepthRenderer();
  54235. };
  54236. // colors shifting and distortion
  54237. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  54238. var _this = this;
  54239. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  54240. [], // samplers
  54241. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54242. this._chromaticAberrationPostProcess.onApply = function (effect) {
  54243. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  54244. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54245. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54246. };
  54247. };
  54248. // highlights enhancing
  54249. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  54250. var _this = this;
  54251. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  54252. [], // samplers
  54253. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  54254. this._highlightsPostProcess.onApply = function (effect) {
  54255. effect.setFloat('gain', _this._highlightsGain);
  54256. effect.setFloat('threshold', _this._highlightsThreshold);
  54257. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  54258. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54259. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54260. };
  54261. };
  54262. // colors shifting and distortion
  54263. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  54264. var _this = this;
  54265. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  54266. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  54267. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  54268. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54269. this._depthOfFieldPostProcess.onApply = function (effect) {
  54270. effect.setTexture("depthSampler", _this._depthTexture);
  54271. effect.setTexture("grainSampler", _this._grainTexture);
  54272. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  54273. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  54274. effect.setFloat('grain_amount', _this._grainAmount);
  54275. effect.setBool('blur_noise', _this._blurNoise);
  54276. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54277. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54278. effect.setFloat('distortion', _this._distortion);
  54279. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  54280. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  54281. effect.setFloat('aperture', _this._dofAperture);
  54282. effect.setFloat('darken', _this._dofDarken);
  54283. effect.setFloat('edge_blur', _this._edgeBlur);
  54284. effect.setBool('highlights', (_this._highlightsGain !== -1));
  54285. effect.setFloat('near', _this._scene.activeCamera.minZ);
  54286. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  54287. };
  54288. };
  54289. // creates a black and white random noise texture, 512x512
  54290. LensRenderingPipeline.prototype._createGrainTexture = function () {
  54291. var size = 512;
  54292. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54293. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54294. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54295. var context = this._grainTexture.getContext();
  54296. var rand = function (min, max) {
  54297. return Math.random() * (max - min) + min;
  54298. };
  54299. var value;
  54300. for (var x = 0; x < size; x++) {
  54301. for (var y = 0; y < size; y++) {
  54302. value = Math.floor(rand(0.42, 0.58) * 255);
  54303. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  54304. context.fillRect(x, y, 1, 1);
  54305. }
  54306. }
  54307. this._grainTexture.update(false);
  54308. };
  54309. return LensRenderingPipeline;
  54310. }(BABYLON.PostProcessRenderPipeline));
  54311. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  54312. })(BABYLON || (BABYLON = {}));
  54313. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  54314. var BABYLON;
  54315. (function (BABYLON) {
  54316. var StandardRenderingPipeline = (function (_super) {
  54317. __extends(StandardRenderingPipeline, _super);
  54318. /**
  54319. * @constructor
  54320. * @param {string} name - The rendering pipeline name
  54321. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54322. * @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)
  54323. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54324. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54325. */
  54326. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54327. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54328. var _this = _super.call(this, scene.getEngine(), name) || this;
  54329. _this.downSampleX4PostProcess = null;
  54330. _this.brightPassPostProcess = null;
  54331. _this.blurHPostProcesses = [];
  54332. _this.blurVPostProcesses = [];
  54333. _this.textureAdderPostProcess = null;
  54334. _this.volumetricLightPostProcess = null;
  54335. _this.volumetricLightSmoothXPostProcess = null;
  54336. _this.volumetricLightSmoothYPostProcess = null;
  54337. _this.volumetricLightMergePostProces = null;
  54338. _this.volumetricLightFinalPostProcess = null;
  54339. _this.luminancePostProcess = null;
  54340. _this.luminanceDownSamplePostProcesses = [];
  54341. _this.hdrPostProcess = null;
  54342. _this.textureAdderFinalPostProcess = null;
  54343. _this.lensFlareFinalPostProcess = null;
  54344. _this.hdrFinalPostProcess = null;
  54345. _this.lensFlarePostProcess = null;
  54346. _this.lensFlareComposePostProcess = null;
  54347. _this.motionBlurPostProcess = null;
  54348. _this.depthOfFieldPostProcess = null;
  54349. // Values
  54350. _this.brightThreshold = 1.0;
  54351. _this.blurWidth = 512.0;
  54352. _this.horizontalBlur = false;
  54353. _this.exposure = 1.0;
  54354. _this.lensTexture = null;
  54355. _this.volumetricLightCoefficient = 0.2;
  54356. _this.volumetricLightPower = 4.0;
  54357. _this.volumetricLightBlurScale = 64.0;
  54358. _this.sourceLight = null;
  54359. _this.hdrMinimumLuminance = 1.0;
  54360. _this.hdrDecreaseRate = 0.5;
  54361. _this.hdrIncreaseRate = 0.5;
  54362. _this.lensColorTexture = null;
  54363. _this.lensFlareStrength = 20.0;
  54364. _this.lensFlareGhostDispersal = 1.4;
  54365. _this.lensFlareHaloWidth = 0.7;
  54366. _this.lensFlareDistortionStrength = 16.0;
  54367. _this.lensStarTexture = null;
  54368. _this.lensFlareDirtTexture = null;
  54369. _this.depthOfFieldDistance = 10.0;
  54370. _this.depthOfFieldBlurWidth = 64.0;
  54371. _this.motionStrength = 1.0;
  54372. // IAnimatable
  54373. _this.animations = [];
  54374. _this._currentDepthOfFieldSource = null;
  54375. _this._hdrCurrentLuminance = 1.0;
  54376. // Getters and setters
  54377. _this._bloomEnabled = true;
  54378. _this._depthOfFieldEnabled = false;
  54379. _this._vlsEnabled = false;
  54380. _this._lensFlareEnabled = false;
  54381. _this._hdrEnabled = false;
  54382. _this._motionBlurEnabled = false;
  54383. _this._motionBlurSamples = 64.0;
  54384. _this._volumetricLightStepsCount = 50.0;
  54385. _this._cameras = cameras || [];
  54386. // Initialize
  54387. _this._scene = scene;
  54388. _this._basePostProcess = originalPostProcess;
  54389. _this._ratio = ratio;
  54390. // Misc
  54391. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54392. // Finish
  54393. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54394. _this._buildPipeline();
  54395. return _this;
  54396. }
  54397. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  54398. get: function () {
  54399. return this._bloomEnabled;
  54400. },
  54401. set: function (enabled) {
  54402. if (this._bloomEnabled === enabled) {
  54403. return;
  54404. }
  54405. this._bloomEnabled = enabled;
  54406. this._buildPipeline();
  54407. },
  54408. enumerable: true,
  54409. configurable: true
  54410. });
  54411. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54412. get: function () {
  54413. return this._depthOfFieldEnabled;
  54414. },
  54415. set: function (enabled) {
  54416. if (this._depthOfFieldEnabled === enabled) {
  54417. return;
  54418. }
  54419. this._depthOfFieldEnabled = enabled;
  54420. this._buildPipeline();
  54421. },
  54422. enumerable: true,
  54423. configurable: true
  54424. });
  54425. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54426. get: function () {
  54427. return this._lensFlareEnabled;
  54428. },
  54429. set: function (enabled) {
  54430. if (this._lensFlareEnabled === enabled) {
  54431. return;
  54432. }
  54433. this._lensFlareEnabled = enabled;
  54434. this._buildPipeline();
  54435. },
  54436. enumerable: true,
  54437. configurable: true
  54438. });
  54439. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  54440. get: function () {
  54441. return this._hdrEnabled;
  54442. },
  54443. set: function (enabled) {
  54444. if (this._hdrEnabled === enabled) {
  54445. return;
  54446. }
  54447. this._hdrEnabled = enabled;
  54448. this._buildPipeline();
  54449. },
  54450. enumerable: true,
  54451. configurable: true
  54452. });
  54453. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  54454. get: function () {
  54455. return this._vlsEnabled;
  54456. },
  54457. set: function (enabled) {
  54458. if (this._vlsEnabled === enabled) {
  54459. return;
  54460. }
  54461. if (enabled) {
  54462. var geometry = this._scene.enableGeometryBufferRenderer();
  54463. if (!geometry) {
  54464. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  54465. return;
  54466. }
  54467. }
  54468. this._vlsEnabled = enabled;
  54469. this._buildPipeline();
  54470. },
  54471. enumerable: true,
  54472. configurable: true
  54473. });
  54474. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  54475. get: function () {
  54476. return this._motionBlurEnabled;
  54477. },
  54478. set: function (enabled) {
  54479. if (this._motionBlurEnabled === enabled) {
  54480. return;
  54481. }
  54482. this._motionBlurEnabled = enabled;
  54483. this._buildPipeline();
  54484. },
  54485. enumerable: true,
  54486. configurable: true
  54487. });
  54488. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  54489. get: function () {
  54490. return this._volumetricLightStepsCount;
  54491. },
  54492. set: function (count) {
  54493. if (this.volumetricLightPostProcess) {
  54494. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  54495. }
  54496. this._volumetricLightStepsCount = count;
  54497. },
  54498. enumerable: true,
  54499. configurable: true
  54500. });
  54501. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  54502. get: function () {
  54503. return this._motionBlurSamples;
  54504. },
  54505. set: function (samples) {
  54506. if (this.motionBlurPostProcess) {
  54507. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  54508. }
  54509. this._motionBlurSamples = samples;
  54510. },
  54511. enumerable: true,
  54512. configurable: true
  54513. });
  54514. StandardRenderingPipeline.prototype._buildPipeline = function () {
  54515. var _this = this;
  54516. var ratio = this._ratio;
  54517. var scene = this._scene;
  54518. this._disposePostProcesses();
  54519. this._reset();
  54520. // Create pass post-process
  54521. if (!this._basePostProcess) {
  54522. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  54523. this.originalPostProcess.onApply = function (effect) {
  54524. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  54525. };
  54526. }
  54527. else {
  54528. this.originalPostProcess = this._basePostProcess;
  54529. }
  54530. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54531. this._currentDepthOfFieldSource = this.originalPostProcess;
  54532. if (this._vlsEnabled) {
  54533. // Create volumetric light
  54534. this._createVolumetricLightPostProcess(scene, ratio);
  54535. // Create volumetric light final post-process
  54536. this.volumetricLightFinalPostProcess = new BABYLON.PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54537. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  54538. }
  54539. if (this._bloomEnabled) {
  54540. // Create down sample X4 post-process
  54541. this._createDownSampleX4PostProcess(scene, ratio / 2);
  54542. // Create bright pass post-process
  54543. this._createBrightPassPostProcess(scene, ratio / 2);
  54544. // Create gaussian blur post-processes (down sampling blurs)
  54545. this._createBlurPostProcesses(scene, ratio / 4, 1);
  54546. // Create texture adder post-process
  54547. this._createTextureAdderPostProcess(scene, ratio);
  54548. // Create depth-of-field source post-process
  54549. this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54550. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54551. }
  54552. if (this._lensFlareEnabled) {
  54553. // Create lens flare post-process
  54554. this._createLensFlarePostProcess(scene, ratio);
  54555. // Create depth-of-field source post-process post lens-flare and disable it now
  54556. this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54557. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  54558. }
  54559. if (this._hdrEnabled) {
  54560. // Create luminance
  54561. this._createLuminancePostProcesses(scene, this._floatTextureType);
  54562. // Create HDR
  54563. this._createHdrPostProcess(scene, ratio);
  54564. // Create depth-of-field source post-process post hdr and disable it now
  54565. this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54566. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  54567. }
  54568. if (this._depthOfFieldEnabled) {
  54569. // Create gaussian blur used by depth-of-field
  54570. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  54571. // Create depth-of-field post-process
  54572. this._createDepthOfFieldPostProcess(scene, ratio);
  54573. }
  54574. if (this._motionBlurEnabled) {
  54575. // Create motion blur post-process
  54576. this._createMotionBlurPostProcess(scene, ratio);
  54577. }
  54578. if (this._cameras !== null) {
  54579. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  54580. }
  54581. };
  54582. // Down Sample X4 Post-Processs
  54583. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54584. var _this = this;
  54585. var downSampleX4Offsets = new Array(32);
  54586. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54587. this.downSampleX4PostProcess.onApply = function (effect) {
  54588. var id = 0;
  54589. for (var i = -2; i < 2; i++) {
  54590. for (var j = -2; j < 2; j++) {
  54591. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54592. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54593. id += 2;
  54594. }
  54595. }
  54596. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54597. };
  54598. // Add to pipeline
  54599. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54600. };
  54601. // Brightpass Post-Process
  54602. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54603. var _this = this;
  54604. var brightOffsets = new Array(8);
  54605. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54606. this.brightPassPostProcess.onApply = function (effect) {
  54607. var sU = (1.0 / _this.brightPassPostProcess.width);
  54608. var sV = (1.0 / _this.brightPassPostProcess.height);
  54609. brightOffsets[0] = -0.5 * sU;
  54610. brightOffsets[1] = 0.5 * sV;
  54611. brightOffsets[2] = 0.5 * sU;
  54612. brightOffsets[3] = 0.5 * sV;
  54613. brightOffsets[4] = -0.5 * sU;
  54614. brightOffsets[5] = -0.5 * sV;
  54615. brightOffsets[6] = 0.5 * sU;
  54616. brightOffsets[7] = -0.5 * sV;
  54617. effect.setArray2("dsOffsets", brightOffsets);
  54618. effect.setFloat("brightThreshold", _this.brightThreshold);
  54619. };
  54620. // Add to pipeline
  54621. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54622. };
  54623. // Create blur H&V post-processes
  54624. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  54625. var _this = this;
  54626. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  54627. var engine = scene.getEngine();
  54628. var blurX = new BABYLON.BlurPostProcess("HDRBlurH" + "_" + indice, new BABYLON.Vector2(1, 0), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54629. var blurY = new BABYLON.BlurPostProcess("HDRBlurV" + "_" + indice, new BABYLON.Vector2(0, 1), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54630. blurX.onActivateObservable.add(function () {
  54631. var dw = blurX.width / engine.getRenderingCanvas().width;
  54632. blurX.kernel = _this[blurWidthKey] * dw;
  54633. });
  54634. blurY.onActivateObservable.add(function () {
  54635. var dw = blurY.height / engine.getRenderingCanvas().height;
  54636. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  54637. });
  54638. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  54639. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  54640. this.blurHPostProcesses.push(blurX);
  54641. this.blurVPostProcesses.push(blurY);
  54642. };
  54643. // Create texture adder post-process
  54644. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54645. var _this = this;
  54646. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54647. this.textureAdderPostProcess.onApply = function (effect) {
  54648. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  54649. effect.setTexture("lensSampler", _this.lensTexture);
  54650. effect.setFloat("exposure", _this.exposure);
  54651. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  54652. };
  54653. // Add to pipeline
  54654. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54655. };
  54656. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  54657. var _this = this;
  54658. var geometryRenderer = scene.enableGeometryBufferRenderer();
  54659. geometryRenderer.enablePosition = true;
  54660. var geometry = geometryRenderer.getGBuffer();
  54661. // Base post-process
  54662. this.volumetricLightPostProcess = new BABYLON.PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1));
  54663. var depthValues = BABYLON.Vector2.Zero();
  54664. this.volumetricLightPostProcess.onApply = function (effect) {
  54665. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  54666. var generator = _this.sourceLight.getShadowGenerator();
  54667. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  54668. effect.setTexture("positionSampler", geometry.textures[2]);
  54669. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  54670. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  54671. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  54672. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  54673. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  54674. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  54675. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  54676. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  54677. effect.setVector2("depthValues", depthValues);
  54678. }
  54679. };
  54680. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  54681. // Smooth
  54682. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  54683. // Merge
  54684. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  54685. this.volumetricLightMergePostProces.onApply = function (effect) {
  54686. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  54687. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  54688. };
  54689. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  54690. };
  54691. // Create luminance
  54692. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  54693. var _this = this;
  54694. // Create luminance
  54695. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  54696. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  54697. var offsets = [];
  54698. this.luminancePostProcess.onApply = function (effect) {
  54699. var sU = (1.0 / _this.luminancePostProcess.width);
  54700. var sV = (1.0 / _this.luminancePostProcess.height);
  54701. offsets[0] = -0.5 * sU;
  54702. offsets[1] = 0.5 * sV;
  54703. offsets[2] = 0.5 * sU;
  54704. offsets[3] = 0.5 * sV;
  54705. offsets[4] = -0.5 * sU;
  54706. offsets[5] = -0.5 * sV;
  54707. offsets[6] = 0.5 * sU;
  54708. offsets[7] = -0.5 * sV;
  54709. effect.setArray2("lumOffsets", offsets);
  54710. };
  54711. // Add to pipeline
  54712. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  54713. // Create down sample luminance
  54714. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  54715. var size = Math.pow(3, i);
  54716. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  54717. if (i === 0) {
  54718. defines += "#define FINAL_DOWN_SAMPLER";
  54719. }
  54720. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  54721. this.luminanceDownSamplePostProcesses.push(postProcess);
  54722. }
  54723. // Create callbacks and add effects
  54724. var lastLuminance = this.luminancePostProcess;
  54725. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  54726. var downSampleOffsets = new Array(18);
  54727. pp.onApply = function (effect) {
  54728. var id = 0;
  54729. for (var x = -1; x < 2; x++) {
  54730. for (var y = -1; y < 2; y++) {
  54731. downSampleOffsets[id] = x / lastLuminance.width;
  54732. downSampleOffsets[id + 1] = y / lastLuminance.height;
  54733. id += 2;
  54734. }
  54735. }
  54736. effect.setArray2("dsOffsets", downSampleOffsets);
  54737. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  54738. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  54739. lastLuminance = _this.luminancePostProcess;
  54740. }
  54741. else {
  54742. lastLuminance = pp;
  54743. }
  54744. };
  54745. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  54746. pp.onAfterRender = function (effect) {
  54747. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  54748. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  54749. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  54750. };
  54751. }
  54752. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  54753. });
  54754. };
  54755. // Create HDR post-process
  54756. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  54757. var _this = this;
  54758. this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54759. var outputLiminance = 1;
  54760. var time = 0;
  54761. var lastTime = 0;
  54762. this.hdrPostProcess.onApply = function (effect) {
  54763. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  54764. time += scene.getEngine().getDeltaTime();
  54765. if (outputLiminance < 0) {
  54766. outputLiminance = _this._hdrCurrentLuminance;
  54767. }
  54768. else {
  54769. var dt = (lastTime - time) / 1000.0;
  54770. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  54771. outputLiminance += _this.hdrDecreaseRate * dt;
  54772. }
  54773. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  54774. outputLiminance -= _this.hdrIncreaseRate * dt;
  54775. }
  54776. else {
  54777. outputLiminance = _this._hdrCurrentLuminance;
  54778. }
  54779. }
  54780. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  54781. effect.setFloat("averageLuminance", outputLiminance);
  54782. lastTime = time;
  54783. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  54784. };
  54785. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  54786. };
  54787. // Create lens flare post-process
  54788. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54789. var _this = this;
  54790. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54791. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  54792. this._createBlurPostProcesses(scene, ratio / 4, 2);
  54793. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54794. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  54795. var resolution = new BABYLON.Vector2(0, 0);
  54796. // Lens flare
  54797. this.lensFlarePostProcess.onApply = function (effect) {
  54798. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  54799. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54800. effect.setFloat("strength", _this.lensFlareStrength);
  54801. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54802. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54803. // Shift
  54804. resolution.x = _this.lensFlarePostProcess.width;
  54805. resolution.y = _this.lensFlarePostProcess.height;
  54806. effect.setVector2("resolution", resolution);
  54807. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54808. };
  54809. // Compose
  54810. var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  54811. var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  54812. this.lensFlareComposePostProcess.onApply = function (effect) {
  54813. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  54814. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54815. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54816. // Lens start rotation matrix
  54817. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54818. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54819. var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
  54820. camRot *= 4.0;
  54821. var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  54822. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54823. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54824. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  54825. };
  54826. };
  54827. // Create depth-of-field post-process
  54828. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54829. var _this = this;
  54830. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54831. this.depthOfFieldPostProcess.onApply = function (effect) {
  54832. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  54833. effect.setTexture("depthSampler", _this._getDepthTexture());
  54834. effect.setFloat("distance", _this.depthOfFieldDistance);
  54835. };
  54836. // Add to pipeline
  54837. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54838. };
  54839. // Create motion blur post-process
  54840. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  54841. var _this = this;
  54842. this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54843. var motionScale = 0;
  54844. var prevViewProjection = BABYLON.Matrix.Identity();
  54845. var invViewProjection = BABYLON.Matrix.Identity();
  54846. var viewProjection = BABYLON.Matrix.Identity();
  54847. var screenSize = BABYLON.Vector2.Zero();
  54848. this.motionBlurPostProcess.onApply = function (effect) {
  54849. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  54850. viewProjection.invertToRef(invViewProjection);
  54851. effect.setMatrix("inverseViewProjection", invViewProjection);
  54852. effect.setMatrix("prevViewProjection", prevViewProjection);
  54853. prevViewProjection = viewProjection;
  54854. screenSize.x = _this.motionBlurPostProcess.width;
  54855. screenSize.y = _this.motionBlurPostProcess.height;
  54856. effect.setVector2("screenSize", screenSize);
  54857. motionScale = scene.getEngine().getFps() / 60.0;
  54858. effect.setFloat("motionScale", motionScale);
  54859. effect.setFloat("motionStrength", _this.motionStrength);
  54860. effect.setTexture("depthSampler", _this._getDepthTexture());
  54861. };
  54862. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  54863. };
  54864. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  54865. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  54866. return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  54867. }
  54868. return this._scene.enableDepthRenderer().getDepthMap();
  54869. };
  54870. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  54871. for (var i = 0; i < this._cameras.length; i++) {
  54872. var camera = this._cameras[i];
  54873. if (this.originalPostProcess) {
  54874. this.originalPostProcess.dispose(camera);
  54875. }
  54876. if (this.downSampleX4PostProcess) {
  54877. this.downSampleX4PostProcess.dispose(camera);
  54878. }
  54879. if (this.brightPassPostProcess) {
  54880. this.brightPassPostProcess.dispose(camera);
  54881. }
  54882. if (this.textureAdderPostProcess) {
  54883. this.textureAdderPostProcess.dispose(camera);
  54884. }
  54885. if (this.textureAdderFinalPostProcess) {
  54886. this.textureAdderFinalPostProcess.dispose(camera);
  54887. }
  54888. if (this.volumetricLightPostProcess) {
  54889. this.volumetricLightPostProcess.dispose(camera);
  54890. }
  54891. if (this.volumetricLightSmoothXPostProcess) {
  54892. this.volumetricLightSmoothXPostProcess.dispose(camera);
  54893. }
  54894. if (this.volumetricLightSmoothYPostProcess) {
  54895. this.volumetricLightSmoothYPostProcess.dispose(camera);
  54896. }
  54897. if (this.volumetricLightMergePostProces) {
  54898. this.volumetricLightMergePostProces.dispose(camera);
  54899. }
  54900. if (this.volumetricLightFinalPostProcess) {
  54901. this.volumetricLightFinalPostProcess.dispose(camera);
  54902. }
  54903. if (this.lensFlarePostProcess) {
  54904. this.lensFlarePostProcess.dispose(camera);
  54905. }
  54906. if (this.lensFlareComposePostProcess) {
  54907. this.lensFlareComposePostProcess.dispose(camera);
  54908. }
  54909. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  54910. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  54911. }
  54912. if (this.luminancePostProcess) {
  54913. this.luminancePostProcess.dispose(camera);
  54914. }
  54915. if (this.hdrPostProcess) {
  54916. this.hdrPostProcess.dispose(camera);
  54917. }
  54918. if (this.hdrFinalPostProcess) {
  54919. this.hdrFinalPostProcess.dispose(camera);
  54920. }
  54921. if (this.depthOfFieldPostProcess) {
  54922. this.depthOfFieldPostProcess.dispose(camera);
  54923. }
  54924. if (this.motionBlurPostProcess) {
  54925. this.motionBlurPostProcess.dispose(camera);
  54926. }
  54927. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  54928. this.blurHPostProcesses[j].dispose(camera);
  54929. }
  54930. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  54931. this.blurVPostProcesses[j].dispose(camera);
  54932. }
  54933. }
  54934. this.originalPostProcess = null;
  54935. this.downSampleX4PostProcess = null;
  54936. this.brightPassPostProcess = null;
  54937. this.textureAdderPostProcess = null;
  54938. this.textureAdderFinalPostProcess = null;
  54939. this.volumetricLightPostProcess = null;
  54940. this.volumetricLightSmoothXPostProcess = null;
  54941. this.volumetricLightSmoothYPostProcess = null;
  54942. this.volumetricLightMergePostProces = null;
  54943. this.volumetricLightFinalPostProcess = null;
  54944. this.lensFlarePostProcess = null;
  54945. this.lensFlareComposePostProcess = null;
  54946. this.luminancePostProcess = null;
  54947. this.hdrPostProcess = null;
  54948. this.hdrFinalPostProcess = null;
  54949. this.depthOfFieldPostProcess = null;
  54950. this.motionBlurPostProcess = null;
  54951. this.luminanceDownSamplePostProcesses = [];
  54952. this.blurHPostProcesses = [];
  54953. this.blurVPostProcesses = [];
  54954. };
  54955. // Dispose
  54956. StandardRenderingPipeline.prototype.dispose = function () {
  54957. this._disposePostProcesses();
  54958. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  54959. _super.prototype.dispose.call(this);
  54960. };
  54961. // Serialize rendering pipeline
  54962. StandardRenderingPipeline.prototype.serialize = function () {
  54963. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54964. serializationObject.customType = "StandardRenderingPipeline";
  54965. return serializationObject;
  54966. };
  54967. /**
  54968. * Static members
  54969. */
  54970. // Parse serialized pipeline
  54971. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  54972. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  54973. };
  54974. // Luminance steps
  54975. StandardRenderingPipeline.LuminanceSteps = 6;
  54976. __decorate([
  54977. BABYLON.serialize()
  54978. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  54979. __decorate([
  54980. BABYLON.serialize()
  54981. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  54982. __decorate([
  54983. BABYLON.serialize()
  54984. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  54985. __decorate([
  54986. BABYLON.serialize()
  54987. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  54988. __decorate([
  54989. BABYLON.serializeAsTexture("lensTexture")
  54990. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  54991. __decorate([
  54992. BABYLON.serialize()
  54993. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  54994. __decorate([
  54995. BABYLON.serialize()
  54996. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  54997. __decorate([
  54998. BABYLON.serialize()
  54999. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  55000. __decorate([
  55001. BABYLON.serialize()
  55002. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  55003. __decorate([
  55004. BABYLON.serialize()
  55005. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  55006. __decorate([
  55007. BABYLON.serialize()
  55008. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  55009. __decorate([
  55010. BABYLON.serializeAsTexture("lensColorTexture")
  55011. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  55012. __decorate([
  55013. BABYLON.serialize()
  55014. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  55015. __decorate([
  55016. BABYLON.serialize()
  55017. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  55018. __decorate([
  55019. BABYLON.serialize()
  55020. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  55021. __decorate([
  55022. BABYLON.serialize()
  55023. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  55024. __decorate([
  55025. BABYLON.serializeAsTexture("lensStarTexture")
  55026. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  55027. __decorate([
  55028. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  55029. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  55030. __decorate([
  55031. BABYLON.serialize()
  55032. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  55033. __decorate([
  55034. BABYLON.serialize()
  55035. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  55036. __decorate([
  55037. BABYLON.serialize()
  55038. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  55039. __decorate([
  55040. BABYLON.serialize()
  55041. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  55042. __decorate([
  55043. BABYLON.serialize()
  55044. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  55045. __decorate([
  55046. BABYLON.serialize()
  55047. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  55048. __decorate([
  55049. BABYLON.serialize()
  55050. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  55051. __decorate([
  55052. BABYLON.serialize()
  55053. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  55054. __decorate([
  55055. BABYLON.serialize()
  55056. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  55057. __decorate([
  55058. BABYLON.serialize()
  55059. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  55060. __decorate([
  55061. BABYLON.serialize()
  55062. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  55063. return StandardRenderingPipeline;
  55064. }(BABYLON.PostProcessRenderPipeline));
  55065. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  55066. })(BABYLON || (BABYLON = {}));
  55067. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  55068. var BABYLON;
  55069. (function (BABYLON) {
  55070. var FxaaPostProcess = (function (_super) {
  55071. __extends(FxaaPostProcess, _super);
  55072. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55073. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55074. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  55075. _this.onApplyObservable.add(function (effect) {
  55076. var texelSize = _this.texelSize;
  55077. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  55078. });
  55079. return _this;
  55080. }
  55081. return FxaaPostProcess;
  55082. }(BABYLON.PostProcess));
  55083. BABYLON.FxaaPostProcess = FxaaPostProcess;
  55084. })(BABYLON || (BABYLON = {}));
  55085. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  55086. var BABYLON;
  55087. (function (BABYLON) {
  55088. var DefaultRenderingPipeline = (function (_super) {
  55089. __extends(DefaultRenderingPipeline, _super);
  55090. /**
  55091. * @constructor
  55092. * @param {string} name - The rendering pipeline name
  55093. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55094. * @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)
  55095. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55096. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  55097. */
  55098. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  55099. if (automaticBuild === void 0) { automaticBuild = true; }
  55100. var _this = _super.call(this, scene.getEngine(), name) || this;
  55101. _this.PassPostProcessId = "PassPostProcessEffect";
  55102. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  55103. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  55104. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  55105. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  55106. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  55107. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  55108. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  55109. // IAnimatable
  55110. _this.animations = [];
  55111. // Values
  55112. _this._bloomEnabled = false;
  55113. _this._fxaaEnabled = false;
  55114. _this._imageProcessingEnabled = true;
  55115. _this._bloomScale = 0.6;
  55116. _this._buildAllowed = true;
  55117. /**
  55118. * Specifies the size of the bloom blur kernel, relative to the final output size
  55119. */
  55120. _this.bloomKernel = 64;
  55121. /**
  55122. * Specifies the weight of the bloom in the final rendering
  55123. */
  55124. _this._bloomWeight = 0.15;
  55125. _this._cameras = cameras || [];
  55126. _this._buildAllowed = automaticBuild;
  55127. // Initialize
  55128. _this._scene = scene;
  55129. var caps = _this._scene.getEngine().getCaps();
  55130. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  55131. // Misc
  55132. if (_this._hdr) {
  55133. if (caps.textureHalfFloatRender) {
  55134. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55135. }
  55136. else if (caps.textureFloatRender) {
  55137. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55138. }
  55139. }
  55140. else {
  55141. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55142. }
  55143. // Attach
  55144. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55145. _this._buildPipeline();
  55146. return _this;
  55147. }
  55148. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  55149. get: function () {
  55150. return this._bloomWeight;
  55151. },
  55152. set: function (value) {
  55153. if (this._bloomWeight === value) {
  55154. return;
  55155. }
  55156. this._bloomWeight = value;
  55157. if (this._hdr && this.copyBack) {
  55158. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  55159. }
  55160. },
  55161. enumerable: true,
  55162. configurable: true
  55163. });
  55164. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  55165. get: function () {
  55166. return this._bloomScale;
  55167. },
  55168. set: function (value) {
  55169. if (this._bloomScale === value) {
  55170. return;
  55171. }
  55172. this._bloomScale = value;
  55173. this._buildPipeline();
  55174. },
  55175. enumerable: true,
  55176. configurable: true
  55177. });
  55178. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  55179. get: function () {
  55180. return this._bloomEnabled;
  55181. },
  55182. set: function (enabled) {
  55183. if (this._bloomEnabled === enabled) {
  55184. return;
  55185. }
  55186. this._bloomEnabled = enabled;
  55187. this._buildPipeline();
  55188. },
  55189. enumerable: true,
  55190. configurable: true
  55191. });
  55192. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  55193. get: function () {
  55194. return this._fxaaEnabled;
  55195. },
  55196. set: function (enabled) {
  55197. if (this._fxaaEnabled === enabled) {
  55198. return;
  55199. }
  55200. this._fxaaEnabled = enabled;
  55201. this._buildPipeline();
  55202. },
  55203. enumerable: true,
  55204. configurable: true
  55205. });
  55206. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  55207. get: function () {
  55208. return this._imageProcessingEnabled;
  55209. },
  55210. set: function (enabled) {
  55211. if (this._imageProcessingEnabled === enabled) {
  55212. return;
  55213. }
  55214. this._imageProcessingEnabled = enabled;
  55215. this._buildPipeline();
  55216. },
  55217. enumerable: true,
  55218. configurable: true
  55219. });
  55220. /**
  55221. * Force the compilation of the entire pipeline.
  55222. */
  55223. DefaultRenderingPipeline.prototype.prepare = function () {
  55224. var previousState = this._buildAllowed;
  55225. this._buildAllowed = true;
  55226. this._buildPipeline();
  55227. this._buildAllowed = previousState;
  55228. };
  55229. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  55230. var _this = this;
  55231. if (!this._buildAllowed) {
  55232. return;
  55233. }
  55234. var engine = this._scene.getEngine();
  55235. this._disposePostProcesses();
  55236. this._reset();
  55237. if (this.bloomEnabled) {
  55238. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55239. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  55240. if (!this._hdr) {
  55241. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55242. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  55243. this.highlights.autoClear = false;
  55244. this.highlights.alwaysForcePOT = true;
  55245. }
  55246. 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);
  55247. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  55248. this.blurX.alwaysForcePOT = true;
  55249. this.blurX.autoClear = false;
  55250. this.blurX.onActivateObservable.add(function () {
  55251. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  55252. _this.blurX.kernel = _this.bloomKernel * dw;
  55253. });
  55254. 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);
  55255. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  55256. this.blurY.alwaysForcePOT = true;
  55257. this.blurY.autoClear = false;
  55258. this.blurY.onActivateObservable.add(function () {
  55259. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  55260. _this.blurY.kernel = _this.bloomKernel * dh;
  55261. });
  55262. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55263. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  55264. this.copyBack.alwaysForcePOT = true;
  55265. if (this._hdr) {
  55266. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  55267. var w = this.bloomWeight;
  55268. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  55269. }
  55270. else {
  55271. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  55272. }
  55273. this.copyBack.autoClear = false;
  55274. }
  55275. if (this._imageProcessingEnabled) {
  55276. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55277. if (this._hdr) {
  55278. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  55279. }
  55280. else {
  55281. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  55282. }
  55283. }
  55284. if (this.fxaaEnabled) {
  55285. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55286. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  55287. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  55288. }
  55289. else {
  55290. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55291. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  55292. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  55293. }
  55294. if (this.bloomEnabled) {
  55295. if (this._hdr) {
  55296. this.copyBack.shareOutputWith(this.blurX);
  55297. if (this.imageProcessing) {
  55298. this.imageProcessing.shareOutputWith(this.pass);
  55299. this.imageProcessing.autoClear = false;
  55300. }
  55301. else if (this.fxaa) {
  55302. this.fxaa.shareOutputWith(this.pass);
  55303. }
  55304. else {
  55305. this.finalMerge.shareOutputWith(this.pass);
  55306. }
  55307. }
  55308. else {
  55309. if (this.fxaa) {
  55310. this.fxaa.shareOutputWith(this.pass);
  55311. }
  55312. else {
  55313. this.finalMerge.shareOutputWith(this.pass);
  55314. }
  55315. }
  55316. }
  55317. if (this._cameras !== null) {
  55318. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  55319. }
  55320. };
  55321. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  55322. for (var i = 0; i < this._cameras.length; i++) {
  55323. var camera = this._cameras[i];
  55324. if (this.pass) {
  55325. this.pass.dispose(camera);
  55326. }
  55327. if (this.highlights) {
  55328. this.highlights.dispose(camera);
  55329. }
  55330. if (this.blurX) {
  55331. this.blurX.dispose(camera);
  55332. }
  55333. if (this.blurY) {
  55334. this.blurY.dispose(camera);
  55335. }
  55336. if (this.copyBack) {
  55337. this.copyBack.dispose(camera);
  55338. }
  55339. if (this.imageProcessing) {
  55340. this.imageProcessing.dispose(camera);
  55341. }
  55342. if (this.fxaa) {
  55343. this.fxaa.dispose(camera);
  55344. }
  55345. if (this.finalMerge) {
  55346. this.finalMerge.dispose(camera);
  55347. }
  55348. }
  55349. this.pass = null;
  55350. this.highlights = null;
  55351. this.blurX = null;
  55352. this.blurY = null;
  55353. this.copyBack = null;
  55354. this.imageProcessing = null;
  55355. this.fxaa = null;
  55356. this.finalMerge = null;
  55357. };
  55358. // Dispose
  55359. DefaultRenderingPipeline.prototype.dispose = function () {
  55360. this._disposePostProcesses();
  55361. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  55362. _super.prototype.dispose.call(this);
  55363. };
  55364. // Serialize rendering pipeline
  55365. DefaultRenderingPipeline.prototype.serialize = function () {
  55366. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55367. serializationObject.customType = "DefaultRenderingPipeline";
  55368. return serializationObject;
  55369. };
  55370. // Parse serialized pipeline
  55371. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  55372. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  55373. };
  55374. __decorate([
  55375. BABYLON.serialize()
  55376. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  55377. __decorate([
  55378. BABYLON.serialize()
  55379. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  55380. __decorate([
  55381. BABYLON.serialize()
  55382. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  55383. __decorate([
  55384. BABYLON.serialize()
  55385. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  55386. __decorate([
  55387. BABYLON.serialize()
  55388. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  55389. __decorate([
  55390. BABYLON.serialize()
  55391. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  55392. __decorate([
  55393. BABYLON.serialize()
  55394. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  55395. __decorate([
  55396. BABYLON.serialize()
  55397. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  55398. return DefaultRenderingPipeline;
  55399. }(BABYLON.PostProcessRenderPipeline));
  55400. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  55401. })(BABYLON || (BABYLON = {}));
  55402. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  55403. var BABYLON;
  55404. (function (BABYLON) {
  55405. var GeometryBufferRenderer = (function () {
  55406. function GeometryBufferRenderer(scene, ratio) {
  55407. if (ratio === void 0) { ratio = 1; }
  55408. this._viewMatrix = BABYLON.Matrix.Zero();
  55409. this._projectionMatrix = BABYLON.Matrix.Zero();
  55410. this._transformMatrix = BABYLON.Matrix.Zero();
  55411. this._worldViewProjection = BABYLON.Matrix.Zero();
  55412. this._enablePosition = false;
  55413. this._scene = scene;
  55414. this._ratio = ratio;
  55415. // Render target
  55416. this._createRenderTargets();
  55417. }
  55418. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  55419. set: function (meshes) {
  55420. this._multiRenderTarget.renderList = meshes;
  55421. },
  55422. enumerable: true,
  55423. configurable: true
  55424. });
  55425. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  55426. get: function () {
  55427. return this._multiRenderTarget.isSupported;
  55428. },
  55429. enumerable: true,
  55430. configurable: true
  55431. });
  55432. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  55433. get: function () {
  55434. return this._enablePosition;
  55435. },
  55436. set: function (enable) {
  55437. this._enablePosition = enable;
  55438. this.dispose();
  55439. this._createRenderTargets();
  55440. },
  55441. enumerable: true,
  55442. configurable: true
  55443. });
  55444. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  55445. var material = subMesh.getMaterial();
  55446. if (material && material.disableDepthWrite) {
  55447. return false;
  55448. }
  55449. var defines = [];
  55450. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  55451. var mesh = subMesh.getMesh();
  55452. var scene = mesh.getScene();
  55453. // Alpha test
  55454. if (material && material.needAlphaTesting()) {
  55455. defines.push("#define ALPHATEST");
  55456. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55457. attribs.push(BABYLON.VertexBuffer.UVKind);
  55458. defines.push("#define UV1");
  55459. }
  55460. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55461. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55462. defines.push("#define UV2");
  55463. }
  55464. }
  55465. // Buffers
  55466. if (this._enablePosition) {
  55467. defines.push("#define POSITION");
  55468. }
  55469. // Bones
  55470. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55471. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55472. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55473. if (mesh.numBoneInfluencers > 4) {
  55474. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55475. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55476. }
  55477. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55478. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55479. }
  55480. else {
  55481. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55482. }
  55483. // Instances
  55484. if (useInstances) {
  55485. defines.push("#define INSTANCES");
  55486. attribs.push("world0");
  55487. attribs.push("world1");
  55488. attribs.push("world2");
  55489. attribs.push("world3");
  55490. }
  55491. // Get correct effect
  55492. var join = defines.join("\n");
  55493. if (this._cachedDefines !== join) {
  55494. this._cachedDefines = join;
  55495. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, null, null, null, { buffersCount: this._enablePosition ? 3 : 2 });
  55496. }
  55497. return this._effect.isReady();
  55498. };
  55499. GeometryBufferRenderer.prototype.getGBuffer = function () {
  55500. return this._multiRenderTarget;
  55501. };
  55502. // Methods
  55503. GeometryBufferRenderer.prototype.dispose = function () {
  55504. this.getGBuffer().dispose();
  55505. };
  55506. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  55507. var _this = this;
  55508. var engine = this._scene.getEngine();
  55509. var count = this._enablePosition ? 3 : 2;
  55510. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  55511. if (!this.isSupported) {
  55512. return null;
  55513. }
  55514. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55515. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55516. this._multiRenderTarget.refreshRate = 1;
  55517. this._multiRenderTarget.renderParticles = false;
  55518. this._multiRenderTarget.renderList = null;
  55519. // set default depth value to 1.0 (far away)
  55520. this._multiRenderTarget.onClearObservable.add(function (engine) {
  55521. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  55522. });
  55523. // Custom render function
  55524. var renderSubMesh = function (subMesh) {
  55525. var mesh = subMesh.getRenderingMesh();
  55526. var scene = _this._scene;
  55527. var engine = scene.getEngine();
  55528. // Culling
  55529. engine.setState(subMesh.getMaterial().backFaceCulling);
  55530. // Managing instances
  55531. var batch = mesh._getInstancesRenderList(subMesh._id);
  55532. if (batch.mustReturn) {
  55533. return;
  55534. }
  55535. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55536. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55537. engine.enableEffect(_this._effect);
  55538. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55539. var material = subMesh.getMaterial();
  55540. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55541. _this._effect.setMatrix("view", scene.getViewMatrix());
  55542. // Alpha test
  55543. if (material && material.needAlphaTesting()) {
  55544. var alphaTexture = material.getAlphaTestTexture();
  55545. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55546. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55547. }
  55548. // Bones
  55549. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55550. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55551. }
  55552. // Draw
  55553. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55554. }
  55555. };
  55556. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55557. var index;
  55558. if (depthOnlySubMeshes.length) {
  55559. engine.setColorWrite(false);
  55560. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55561. renderSubMesh(depthOnlySubMeshes.data[index]);
  55562. }
  55563. engine.setColorWrite(true);
  55564. }
  55565. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55566. renderSubMesh(opaqueSubMeshes.data[index]);
  55567. }
  55568. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55569. renderSubMesh(alphaTestSubMeshes.data[index]);
  55570. }
  55571. };
  55572. };
  55573. return GeometryBufferRenderer;
  55574. }());
  55575. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  55576. })(BABYLON || (BABYLON = {}));
  55577. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  55578. var BABYLON;
  55579. (function (BABYLON) {
  55580. var RefractionPostProcess = (function (_super) {
  55581. __extends(RefractionPostProcess, _super);
  55582. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  55583. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  55584. _this.color = color;
  55585. _this.depth = depth;
  55586. _this.colorLevel = colorLevel;
  55587. _this.onActivateObservable.add(function (cam) {
  55588. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  55589. });
  55590. _this.onApplyObservable.add(function (effect) {
  55591. effect.setColor3("baseColor", _this.color);
  55592. effect.setFloat("depth", _this.depth);
  55593. effect.setFloat("colorLevel", _this.colorLevel);
  55594. effect.setTexture("refractionSampler", _this._refRexture);
  55595. });
  55596. return _this;
  55597. }
  55598. // Methods
  55599. RefractionPostProcess.prototype.dispose = function (camera) {
  55600. if (this._refRexture) {
  55601. this._refRexture.dispose();
  55602. }
  55603. _super.prototype.dispose.call(this, camera);
  55604. };
  55605. return RefractionPostProcess;
  55606. }(BABYLON.PostProcess));
  55607. BABYLON.RefractionPostProcess = RefractionPostProcess;
  55608. })(BABYLON || (BABYLON = {}));
  55609. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  55610. var BABYLON;
  55611. (function (BABYLON) {
  55612. var BlackAndWhitePostProcess = (function (_super) {
  55613. __extends(BlackAndWhitePostProcess, _super);
  55614. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  55615. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  55616. _this.degree = 1;
  55617. _this.onApplyObservable.add(function (effect) {
  55618. effect.setFloat("degree", _this.degree);
  55619. });
  55620. return _this;
  55621. }
  55622. return BlackAndWhitePostProcess;
  55623. }(BABYLON.PostProcess));
  55624. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  55625. })(BABYLON || (BABYLON = {}));
  55626. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  55627. var BABYLON;
  55628. (function (BABYLON) {
  55629. var ConvolutionPostProcess = (function (_super) {
  55630. __extends(ConvolutionPostProcess, _super);
  55631. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  55632. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  55633. _this.kernel = kernel;
  55634. _this.onApply = function (effect) {
  55635. effect.setFloat2("screenSize", _this.width, _this.height);
  55636. effect.setArray("kernel", _this.kernel);
  55637. };
  55638. return _this;
  55639. }
  55640. // Statics
  55641. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  55642. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  55643. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  55644. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  55645. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  55646. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  55647. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  55648. return ConvolutionPostProcess;
  55649. }(BABYLON.PostProcess));
  55650. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  55651. })(BABYLON || (BABYLON = {}));
  55652. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  55653. var BABYLON;
  55654. (function (BABYLON) {
  55655. var FilterPostProcess = (function (_super) {
  55656. __extends(FilterPostProcess, _super);
  55657. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  55658. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  55659. _this.kernelMatrix = kernelMatrix;
  55660. _this.onApply = function (effect) {
  55661. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  55662. };
  55663. return _this;
  55664. }
  55665. return FilterPostProcess;
  55666. }(BABYLON.PostProcess));
  55667. BABYLON.FilterPostProcess = FilterPostProcess;
  55668. })(BABYLON || (BABYLON = {}));
  55669. //# sourceMappingURL=babylon.filterPostProcess.js.map
  55670. var BABYLON;
  55671. (function (BABYLON) {
  55672. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  55673. var VolumetricLightScatteringPostProcess = (function (_super) {
  55674. __extends(VolumetricLightScatteringPostProcess, _super);
  55675. /**
  55676. * @constructor
  55677. * @param {string} name - The post-process name
  55678. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  55679. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  55680. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  55681. * @param {number} samples - The post-process quality, default 100
  55682. * @param {number} samplingMode - The post-process filtering mode
  55683. * @param {BABYLON.Engine} engine - The babylon engine
  55684. * @param {boolean} reusable - If the post-process is reusable
  55685. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  55686. */
  55687. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  55688. if (samples === void 0) { samples = 100; }
  55689. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55690. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  55691. _this._screenCoordinates = BABYLON.Vector2.Zero();
  55692. /**
  55693. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  55694. * @type {Vector3}
  55695. */
  55696. _this.customMeshPosition = BABYLON.Vector3.Zero();
  55697. /**
  55698. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  55699. * @type {boolean}
  55700. */
  55701. _this.useCustomMeshPosition = false;
  55702. /**
  55703. * If the post-process should inverse the light scattering direction
  55704. * @type {boolean}
  55705. */
  55706. _this.invert = true;
  55707. /**
  55708. * Array containing the excluded meshes not rendered in the internal pass
  55709. */
  55710. _this.excludedMeshes = new Array();
  55711. /**
  55712. * Controls the overall intensity of the post-process
  55713. * @type {number}
  55714. */
  55715. _this.exposure = 0.3;
  55716. /**
  55717. * Dissipates each sample's contribution in range [0, 1]
  55718. * @type {number}
  55719. */
  55720. _this.decay = 0.96815;
  55721. /**
  55722. * Controls the overall intensity of each sample
  55723. * @type {number}
  55724. */
  55725. _this.weight = 0.58767;
  55726. /**
  55727. * Controls the density of each sample
  55728. * @type {number}
  55729. */
  55730. _this.density = 0.926;
  55731. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  55732. var engine = scene.getEngine();
  55733. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  55734. // Configure mesh
  55735. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  55736. // Configure
  55737. _this._createPass(scene, ratio.passRatio || ratio);
  55738. _this.onActivate = function (camera) {
  55739. if (!_this.isSupported) {
  55740. _this.dispose(camera);
  55741. }
  55742. _this.onActivate = null;
  55743. };
  55744. _this.onApplyObservable.add(function (effect) {
  55745. _this._updateMeshScreenCoordinates(scene);
  55746. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  55747. effect.setFloat("exposure", _this.exposure);
  55748. effect.setFloat("decay", _this.decay);
  55749. effect.setFloat("weight", _this.weight);
  55750. effect.setFloat("density", _this.density);
  55751. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  55752. });
  55753. return _this;
  55754. }
  55755. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  55756. get: function () {
  55757. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55758. return false;
  55759. },
  55760. set: function (useDiffuseColor) {
  55761. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55762. },
  55763. enumerable: true,
  55764. configurable: true
  55765. });
  55766. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  55767. return "VolumetricLightScatteringPostProcess";
  55768. };
  55769. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  55770. var mesh = subMesh.getMesh();
  55771. // Render this.mesh as default
  55772. if (mesh === this.mesh) {
  55773. return mesh.material.isReady(mesh);
  55774. }
  55775. var defines = [];
  55776. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55777. var material = subMesh.getMaterial();
  55778. var needUV = false;
  55779. // Alpha test
  55780. if (material) {
  55781. if (material.needAlphaTesting()) {
  55782. defines.push("#define ALPHATEST");
  55783. }
  55784. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55785. attribs.push(BABYLON.VertexBuffer.UVKind);
  55786. defines.push("#define UV1");
  55787. }
  55788. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55789. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55790. defines.push("#define UV2");
  55791. }
  55792. }
  55793. // Bones
  55794. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55795. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55796. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55797. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55798. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55799. }
  55800. else {
  55801. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55802. }
  55803. // Instances
  55804. if (useInstances) {
  55805. defines.push("#define INSTANCES");
  55806. attribs.push("world0");
  55807. attribs.push("world1");
  55808. attribs.push("world2");
  55809. attribs.push("world3");
  55810. }
  55811. // Get correct effect
  55812. var join = defines.join("\n");
  55813. if (this._cachedDefines !== join) {
  55814. this._cachedDefines = join;
  55815. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  55816. }
  55817. return this._volumetricLightScatteringPass.isReady();
  55818. };
  55819. /**
  55820. * Sets the new light position for light scattering effect
  55821. * @param {BABYLON.Vector3} The new custom light position
  55822. */
  55823. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  55824. this.customMeshPosition = position;
  55825. };
  55826. /**
  55827. * Returns the light position for light scattering effect
  55828. * @return {BABYLON.Vector3} The custom light position
  55829. */
  55830. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  55831. return this.customMeshPosition;
  55832. };
  55833. /**
  55834. * Disposes the internal assets and detaches the post-process from the camera
  55835. */
  55836. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  55837. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  55838. if (rttIndex !== -1) {
  55839. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  55840. }
  55841. this._volumetricLightScatteringRTT.dispose();
  55842. _super.prototype.dispose.call(this, camera);
  55843. };
  55844. /**
  55845. * Returns the render target texture used by the post-process
  55846. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  55847. */
  55848. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  55849. return this._volumetricLightScatteringRTT;
  55850. };
  55851. // Private methods
  55852. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  55853. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  55854. return true;
  55855. }
  55856. return false;
  55857. };
  55858. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  55859. var _this = this;
  55860. var engine = scene.getEngine();
  55861. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55862. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55863. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55864. this._volumetricLightScatteringRTT.renderList = null;
  55865. this._volumetricLightScatteringRTT.renderParticles = false;
  55866. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  55867. // Custom render function for submeshes
  55868. var renderSubMesh = function (subMesh) {
  55869. var mesh = subMesh.getRenderingMesh();
  55870. if (_this._meshExcluded(mesh)) {
  55871. return;
  55872. }
  55873. var scene = mesh.getScene();
  55874. var engine = scene.getEngine();
  55875. // Culling
  55876. engine.setState(subMesh.getMaterial().backFaceCulling);
  55877. // Managing instances
  55878. var batch = mesh._getInstancesRenderList(subMesh._id);
  55879. if (batch.mustReturn) {
  55880. return;
  55881. }
  55882. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55883. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55884. var effect = _this._volumetricLightScatteringPass;
  55885. if (mesh === _this.mesh) {
  55886. if (subMesh.effect) {
  55887. effect = subMesh.effect;
  55888. }
  55889. else {
  55890. effect = subMesh.getMaterial().getEffect();
  55891. }
  55892. }
  55893. engine.enableEffect(effect);
  55894. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  55895. if (mesh === _this.mesh) {
  55896. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  55897. }
  55898. else {
  55899. var material = subMesh.getMaterial();
  55900. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  55901. // Alpha test
  55902. if (material && material.needAlphaTesting()) {
  55903. var alphaTexture = material.getAlphaTestTexture();
  55904. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  55905. if (alphaTexture) {
  55906. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55907. }
  55908. }
  55909. // Bones
  55910. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55911. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55912. }
  55913. }
  55914. // Draw
  55915. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  55916. }
  55917. };
  55918. // Render target texture callbacks
  55919. var savedSceneClearColor;
  55920. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  55921. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  55922. savedSceneClearColor = scene.clearColor;
  55923. scene.clearColor = sceneClearColor;
  55924. });
  55925. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  55926. scene.clearColor = savedSceneClearColor;
  55927. });
  55928. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55929. var engine = scene.getEngine();
  55930. var index;
  55931. if (depthOnlySubMeshes.length) {
  55932. engine.setColorWrite(false);
  55933. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55934. renderSubMesh(depthOnlySubMeshes.data[index]);
  55935. }
  55936. engine.setColorWrite(true);
  55937. }
  55938. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55939. renderSubMesh(opaqueSubMeshes.data[index]);
  55940. }
  55941. engine.setAlphaTesting(true);
  55942. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55943. renderSubMesh(alphaTestSubMeshes.data[index]);
  55944. }
  55945. engine.setAlphaTesting(false);
  55946. if (transparentSubMeshes.length) {
  55947. // Sort sub meshes
  55948. for (index = 0; index < transparentSubMeshes.length; index++) {
  55949. var submesh = transparentSubMeshes.data[index];
  55950. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  55951. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  55952. }
  55953. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  55954. sortedArray.sort(function (a, b) {
  55955. // Alpha index first
  55956. if (a._alphaIndex > b._alphaIndex) {
  55957. return 1;
  55958. }
  55959. if (a._alphaIndex < b._alphaIndex) {
  55960. return -1;
  55961. }
  55962. // Then distance to camera
  55963. if (a._distanceToCamera < b._distanceToCamera) {
  55964. return 1;
  55965. }
  55966. if (a._distanceToCamera > b._distanceToCamera) {
  55967. return -1;
  55968. }
  55969. return 0;
  55970. });
  55971. // Render sub meshes
  55972. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55973. for (index = 0; index < sortedArray.length; index++) {
  55974. renderSubMesh(sortedArray[index]);
  55975. }
  55976. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55977. }
  55978. };
  55979. };
  55980. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  55981. var transform = scene.getTransformMatrix();
  55982. var meshPosition;
  55983. if (this.useCustomMeshPosition) {
  55984. meshPosition = this.customMeshPosition;
  55985. }
  55986. else if (this.attachedNode) {
  55987. meshPosition = this.attachedNode.position;
  55988. }
  55989. else {
  55990. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  55991. }
  55992. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  55993. this._screenCoordinates.x = pos.x / this._viewPort.width;
  55994. this._screenCoordinates.y = pos.y / this._viewPort.height;
  55995. if (this.invert)
  55996. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  55997. };
  55998. // Static methods
  55999. /**
  56000. * Creates a default mesh for the Volumeric Light Scattering post-process
  56001. * @param {string} The mesh name
  56002. * @param {BABYLON.Scene} The scene where to create the mesh
  56003. * @return {BABYLON.Mesh} the default mesh
  56004. */
  56005. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  56006. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  56007. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  56008. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  56009. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  56010. mesh.material = material;
  56011. return mesh;
  56012. };
  56013. __decorate([
  56014. BABYLON.serializeAsVector3()
  56015. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  56016. __decorate([
  56017. BABYLON.serialize()
  56018. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  56019. __decorate([
  56020. BABYLON.serialize()
  56021. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  56022. __decorate([
  56023. BABYLON.serializeAsMeshReference()
  56024. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  56025. __decorate([
  56026. BABYLON.serialize()
  56027. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  56028. __decorate([
  56029. BABYLON.serialize()
  56030. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  56031. __decorate([
  56032. BABYLON.serialize()
  56033. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  56034. __decorate([
  56035. BABYLON.serialize()
  56036. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  56037. __decorate([
  56038. BABYLON.serialize()
  56039. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  56040. return VolumetricLightScatteringPostProcess;
  56041. }(BABYLON.PostProcess));
  56042. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  56043. })(BABYLON || (BABYLON = {}));
  56044. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  56045. //
  56046. // This post-process allows the modification of rendered colors by using
  56047. // a 'look-up table' (LUT). This effect is also called Color Grading.
  56048. //
  56049. // The object needs to be provided an url to a texture containing the color
  56050. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  56051. // Use an image editing software to tweak the LUT to match your needs.
  56052. //
  56053. // For an example of a color LUT, see here:
  56054. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  56055. // For explanations on color grading, see here:
  56056. // http://udn.epicgames.com/Three/ColorGrading.html
  56057. //
  56058. var BABYLON;
  56059. (function (BABYLON) {
  56060. var ColorCorrectionPostProcess = (function (_super) {
  56061. __extends(ColorCorrectionPostProcess, _super);
  56062. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  56063. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  56064. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56065. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  56066. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56067. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56068. _this.onApply = function (effect) {
  56069. effect.setTexture("colorTable", _this._colorTableTexture);
  56070. };
  56071. return _this;
  56072. }
  56073. return ColorCorrectionPostProcess;
  56074. }(BABYLON.PostProcess));
  56075. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  56076. })(BABYLON || (BABYLON = {}));
  56077. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  56078. var BABYLON;
  56079. (function (BABYLON) {
  56080. var TonemappingOperator;
  56081. (function (TonemappingOperator) {
  56082. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  56083. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  56084. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  56085. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  56086. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  56087. ;
  56088. var TonemapPostProcess = (function (_super) {
  56089. __extends(TonemapPostProcess, _super);
  56090. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  56091. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56092. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56093. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  56094. _this._operator = _operator;
  56095. _this.exposureAdjustment = exposureAdjustment;
  56096. var defines = "#define ";
  56097. if (_this._operator === TonemappingOperator.Hable)
  56098. defines += "HABLE_TONEMAPPING";
  56099. else if (_this._operator === TonemappingOperator.Reinhard)
  56100. defines += "REINHARD_TONEMAPPING";
  56101. else if (_this._operator === TonemappingOperator.HejiDawson)
  56102. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  56103. else if (_this._operator === TonemappingOperator.Photographic)
  56104. defines += "PHOTOGRAPHIC_TONEMAPPING";
  56105. //sadly a second call to create the effect.
  56106. _this.updateEffect(defines);
  56107. _this.onApply = function (effect) {
  56108. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  56109. };
  56110. return _this;
  56111. }
  56112. return TonemapPostProcess;
  56113. }(BABYLON.PostProcess));
  56114. BABYLON.TonemapPostProcess = TonemapPostProcess;
  56115. })(BABYLON || (BABYLON = {}));
  56116. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  56117. var BABYLON;
  56118. (function (BABYLON) {
  56119. var DisplayPassPostProcess = (function (_super) {
  56120. __extends(DisplayPassPostProcess, _super);
  56121. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  56122. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  56123. }
  56124. return DisplayPassPostProcess;
  56125. }(BABYLON.PostProcess));
  56126. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  56127. })(BABYLON || (BABYLON = {}));
  56128. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  56129. var BABYLON;
  56130. (function (BABYLON) {
  56131. var HighlightsPostProcess = (function (_super) {
  56132. __extends(HighlightsPostProcess, _super);
  56133. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56134. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56135. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  56136. }
  56137. return HighlightsPostProcess;
  56138. }(BABYLON.PostProcess));
  56139. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  56140. })(BABYLON || (BABYLON = {}));
  56141. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  56142. var BABYLON;
  56143. (function (BABYLON) {
  56144. var ImageProcessingPostProcess = (function (_super) {
  56145. __extends(ImageProcessingPostProcess, _super);
  56146. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56147. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56148. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  56149. _this._fromLinearSpace = true;
  56150. /**
  56151. * Defines cache preventing GC.
  56152. */
  56153. _this._defines = {
  56154. IMAGEPROCESSING: false,
  56155. VIGNETTE: false,
  56156. VIGNETTEBLENDMODEMULTIPLY: false,
  56157. VIGNETTEBLENDMODEOPAQUE: false,
  56158. TONEMAPPING: false,
  56159. CONTRAST: false,
  56160. COLORCURVES: false,
  56161. COLORGRADING: false,
  56162. FROMLINEARSPACE: false,
  56163. SAMPLER3DGREENDEPTH: false,
  56164. SAMPLER3DBGRMAP: false,
  56165. IMAGEPROCESSINGPOSTPROCESS: false,
  56166. EXPOSURE: false,
  56167. };
  56168. // Setup the default processing configuration to the scene.
  56169. _this._attachImageProcessingConfiguration(null, true);
  56170. _this.imageProcessingConfiguration.applyByPostProcess = true;
  56171. _this.onApply = function (effect) {
  56172. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  56173. };
  56174. return _this;
  56175. }
  56176. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  56177. /**
  56178. * Gets the image processing configuration used either in this material.
  56179. */
  56180. get: function () {
  56181. return this._imageProcessingConfiguration;
  56182. },
  56183. /**
  56184. * Sets the Default image processing configuration used either in the this material.
  56185. *
  56186. * If sets to null, the scene one is in use.
  56187. */
  56188. set: function (value) {
  56189. this._attachImageProcessingConfiguration(value);
  56190. },
  56191. enumerable: true,
  56192. configurable: true
  56193. });
  56194. /**
  56195. * Attaches a new image processing configuration to the PBR Material.
  56196. * @param configuration
  56197. */
  56198. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  56199. var _this = this;
  56200. if (doNotBuild === void 0) { doNotBuild = false; }
  56201. if (configuration === this._imageProcessingConfiguration) {
  56202. return;
  56203. }
  56204. // Detaches observer.
  56205. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  56206. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  56207. }
  56208. // Pick the scene configuration if needed.
  56209. if (!configuration) {
  56210. var camera = this.getCamera();
  56211. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  56212. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  56213. }
  56214. else {
  56215. this._imageProcessingConfiguration = configuration;
  56216. }
  56217. // Attaches observer.
  56218. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  56219. _this._updateParameters();
  56220. });
  56221. // Ensure the effect will be rebuilt.
  56222. if (!doNotBuild) {
  56223. this._updateParameters();
  56224. }
  56225. };
  56226. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  56227. /**
  56228. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  56229. */
  56230. get: function () {
  56231. return this.imageProcessingConfiguration.colorCurves;
  56232. },
  56233. /**
  56234. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  56235. */
  56236. set: function (value) {
  56237. this.imageProcessingConfiguration.colorCurves = value;
  56238. },
  56239. enumerable: true,
  56240. configurable: true
  56241. });
  56242. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  56243. /**
  56244. * Gets wether the color curves effect is enabled.
  56245. */
  56246. get: function () {
  56247. return this.imageProcessingConfiguration.colorCurvesEnabled;
  56248. },
  56249. /**
  56250. * Sets wether the color curves effect is enabled.
  56251. */
  56252. set: function (value) {
  56253. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  56254. },
  56255. enumerable: true,
  56256. configurable: true
  56257. });
  56258. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  56259. /**
  56260. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  56261. */
  56262. get: function () {
  56263. return this.imageProcessingConfiguration.colorGradingTexture;
  56264. },
  56265. /**
  56266. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  56267. */
  56268. set: function (value) {
  56269. this.imageProcessingConfiguration.colorGradingTexture = value;
  56270. },
  56271. enumerable: true,
  56272. configurable: true
  56273. });
  56274. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  56275. /**
  56276. * Gets wether the color grading effect is enabled.
  56277. */
  56278. get: function () {
  56279. return this.imageProcessingConfiguration.colorGradingEnabled;
  56280. },
  56281. /**
  56282. * Gets wether the color grading effect is enabled.
  56283. */
  56284. set: function (value) {
  56285. this.imageProcessingConfiguration.colorGradingEnabled = value;
  56286. },
  56287. enumerable: true,
  56288. configurable: true
  56289. });
  56290. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  56291. /**
  56292. * Gets exposure used in the effect.
  56293. */
  56294. get: function () {
  56295. return this.imageProcessingConfiguration.exposure;
  56296. },
  56297. /**
  56298. * Sets exposure used in the effect.
  56299. */
  56300. set: function (value) {
  56301. this.imageProcessingConfiguration.exposure = value;
  56302. },
  56303. enumerable: true,
  56304. configurable: true
  56305. });
  56306. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  56307. /**
  56308. * Gets wether tonemapping is enabled or not.
  56309. */
  56310. get: function () {
  56311. return this._imageProcessingConfiguration.toneMappingEnabled;
  56312. },
  56313. /**
  56314. * Sets wether tonemapping is enabled or not
  56315. */
  56316. set: function (value) {
  56317. this._imageProcessingConfiguration.toneMappingEnabled = value;
  56318. },
  56319. enumerable: true,
  56320. configurable: true
  56321. });
  56322. ;
  56323. ;
  56324. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  56325. /**
  56326. * Gets contrast used in the effect.
  56327. */
  56328. get: function () {
  56329. return this.imageProcessingConfiguration.contrast;
  56330. },
  56331. /**
  56332. * Sets contrast used in the effect.
  56333. */
  56334. set: function (value) {
  56335. this.imageProcessingConfiguration.contrast = value;
  56336. },
  56337. enumerable: true,
  56338. configurable: true
  56339. });
  56340. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  56341. /**
  56342. * Gets Vignette stretch size.
  56343. */
  56344. get: function () {
  56345. return this.imageProcessingConfiguration.vignetteStretch;
  56346. },
  56347. /**
  56348. * Sets Vignette stretch size.
  56349. */
  56350. set: function (value) {
  56351. this.imageProcessingConfiguration.vignetteStretch = value;
  56352. },
  56353. enumerable: true,
  56354. configurable: true
  56355. });
  56356. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  56357. /**
  56358. * Gets Vignette centre X Offset.
  56359. */
  56360. get: function () {
  56361. return this.imageProcessingConfiguration.vignetteCentreX;
  56362. },
  56363. /**
  56364. * Sets Vignette centre X Offset.
  56365. */
  56366. set: function (value) {
  56367. this.imageProcessingConfiguration.vignetteCentreX = value;
  56368. },
  56369. enumerable: true,
  56370. configurable: true
  56371. });
  56372. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  56373. /**
  56374. * Gets Vignette centre Y Offset.
  56375. */
  56376. get: function () {
  56377. return this.imageProcessingConfiguration.vignetteCentreY;
  56378. },
  56379. /**
  56380. * Sets Vignette centre Y Offset.
  56381. */
  56382. set: function (value) {
  56383. this.imageProcessingConfiguration.vignetteCentreY = value;
  56384. },
  56385. enumerable: true,
  56386. configurable: true
  56387. });
  56388. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  56389. /**
  56390. * Gets Vignette weight or intensity of the vignette effect.
  56391. */
  56392. get: function () {
  56393. return this.imageProcessingConfiguration.vignetteWeight;
  56394. },
  56395. /**
  56396. * Sets Vignette weight or intensity of the vignette effect.
  56397. */
  56398. set: function (value) {
  56399. this.imageProcessingConfiguration.vignetteWeight = value;
  56400. },
  56401. enumerable: true,
  56402. configurable: true
  56403. });
  56404. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  56405. /**
  56406. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  56407. * if vignetteEnabled is set to true.
  56408. */
  56409. get: function () {
  56410. return this.imageProcessingConfiguration.vignetteColor;
  56411. },
  56412. /**
  56413. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  56414. * if vignetteEnabled is set to true.
  56415. */
  56416. set: function (value) {
  56417. this.imageProcessingConfiguration.vignetteColor = value;
  56418. },
  56419. enumerable: true,
  56420. configurable: true
  56421. });
  56422. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  56423. /**
  56424. * Gets Camera field of view used by the Vignette effect.
  56425. */
  56426. get: function () {
  56427. return this.imageProcessingConfiguration.vignetteCameraFov;
  56428. },
  56429. /**
  56430. * Sets Camera field of view used by the Vignette effect.
  56431. */
  56432. set: function (value) {
  56433. this.imageProcessingConfiguration.vignetteCameraFov = value;
  56434. },
  56435. enumerable: true,
  56436. configurable: true
  56437. });
  56438. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  56439. /**
  56440. * Gets the vignette blend mode allowing different kind of effect.
  56441. */
  56442. get: function () {
  56443. return this.imageProcessingConfiguration.vignetteBlendMode;
  56444. },
  56445. /**
  56446. * Sets the vignette blend mode allowing different kind of effect.
  56447. */
  56448. set: function (value) {
  56449. this.imageProcessingConfiguration.vignetteBlendMode = value;
  56450. },
  56451. enumerable: true,
  56452. configurable: true
  56453. });
  56454. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  56455. /**
  56456. * Gets wether the vignette effect is enabled.
  56457. */
  56458. get: function () {
  56459. return this.imageProcessingConfiguration.vignetteEnabled;
  56460. },
  56461. /**
  56462. * Sets wether the vignette effect is enabled.
  56463. */
  56464. set: function (value) {
  56465. this.imageProcessingConfiguration.vignetteEnabled = value;
  56466. },
  56467. enumerable: true,
  56468. configurable: true
  56469. });
  56470. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  56471. /**
  56472. * Gets wether the input of the processing is in Gamma or Linear Space.
  56473. */
  56474. get: function () {
  56475. return this._fromLinearSpace;
  56476. },
  56477. /**
  56478. * Sets wether the input of the processing is in Gamma or Linear Space.
  56479. */
  56480. set: function (value) {
  56481. if (this._fromLinearSpace === value) {
  56482. return;
  56483. }
  56484. this._fromLinearSpace = value;
  56485. this._updateParameters();
  56486. },
  56487. enumerable: true,
  56488. configurable: true
  56489. });
  56490. ImageProcessingPostProcess.prototype.getClassName = function () {
  56491. return "ImageProcessingPostProcess";
  56492. };
  56493. ImageProcessingPostProcess.prototype._updateParameters = function () {
  56494. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  56495. this.imageProcessingConfiguration.prepareDefines(this._defines);
  56496. var defines = "";
  56497. for (var define in this._defines) {
  56498. if (this._defines[define]) {
  56499. defines += "#define " + define + ";\r\n";
  56500. }
  56501. }
  56502. var samplers = ["textureSampler"];
  56503. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  56504. var uniforms = ["scale"];
  56505. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  56506. this.updateEffect(defines, uniforms, samplers);
  56507. };
  56508. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  56509. _super.prototype.dispose.call(this, camera);
  56510. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  56511. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  56512. }
  56513. this.imageProcessingConfiguration.applyByPostProcess = false;
  56514. };
  56515. __decorate([
  56516. BABYLON.serialize()
  56517. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  56518. return ImageProcessingPostProcess;
  56519. }(BABYLON.PostProcess));
  56520. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  56521. })(BABYLON || (BABYLON = {}));
  56522. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  56523. var BABYLON;
  56524. (function (BABYLON) {
  56525. var BlurPostProcess = (function (_super) {
  56526. __extends(BlurPostProcess, _super);
  56527. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  56528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56529. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56530. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  56531. _this.direction = direction;
  56532. _this._packedFloat = false;
  56533. _this.onApplyObservable.add(function (effect) {
  56534. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  56535. });
  56536. _this.kernel = kernel;
  56537. return _this;
  56538. }
  56539. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  56540. /**
  56541. * Gets the length in pixels of the blur sample region
  56542. */
  56543. get: function () {
  56544. return this._idealKernel;
  56545. },
  56546. /**
  56547. * Sets the length in pixels of the blur sample region
  56548. */
  56549. set: function (v) {
  56550. if (this._idealKernel === v) {
  56551. return;
  56552. }
  56553. v = Math.max(v, 1);
  56554. this._idealKernel = v;
  56555. this._kernel = this._nearestBestKernel(v);
  56556. this._updateParameters();
  56557. },
  56558. enumerable: true,
  56559. configurable: true
  56560. });
  56561. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  56562. /**
  56563. * Gets wether or not the blur is unpacking/repacking floats
  56564. */
  56565. get: function () {
  56566. return this._packedFloat;
  56567. },
  56568. /**
  56569. * Sets wether or not the blur needs to unpack/repack floats
  56570. */
  56571. set: function (v) {
  56572. if (this._packedFloat === v) {
  56573. return;
  56574. }
  56575. this._packedFloat = v;
  56576. this._updateParameters();
  56577. },
  56578. enumerable: true,
  56579. configurable: true
  56580. });
  56581. BlurPostProcess.prototype._updateParameters = function () {
  56582. // Generate sampling offsets and weights
  56583. var N = this._kernel;
  56584. var centerIndex = (N - 1) / 2;
  56585. // Generate Gaussian sampling weights over kernel
  56586. var offsets = [];
  56587. var weights = [];
  56588. var totalWeight = 0;
  56589. for (var i = 0; i < N; i++) {
  56590. var u = i / (N - 1);
  56591. var w = this._gaussianWeight(u * 2.0 - 1);
  56592. offsets[i] = (i - centerIndex);
  56593. weights[i] = w;
  56594. totalWeight += w;
  56595. }
  56596. // Normalize weights
  56597. for (var i = 0; i < weights.length; i++) {
  56598. weights[i] /= totalWeight;
  56599. }
  56600. // Optimize: combine samples to take advantage of hardware linear sampling
  56601. // Walk from left to center, combining pairs (symmetrically)
  56602. var linearSamplingWeights = [];
  56603. var linearSamplingOffsets = [];
  56604. var linearSamplingMap = [];
  56605. for (var i = 0; i <= centerIndex; i += 2) {
  56606. var j = Math.min(i + 1, Math.floor(centerIndex));
  56607. var singleCenterSample = i === j;
  56608. if (singleCenterSample) {
  56609. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  56610. }
  56611. else {
  56612. var sharedCell = j === centerIndex;
  56613. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  56614. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  56615. if (offsetLinear === 0) {
  56616. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  56617. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  56618. }
  56619. else {
  56620. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  56621. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  56622. }
  56623. }
  56624. }
  56625. for (var i = 0; i < linearSamplingMap.length; i++) {
  56626. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  56627. linearSamplingWeights[i] = linearSamplingMap[i].w;
  56628. }
  56629. // Replace with optimized
  56630. offsets = linearSamplingOffsets;
  56631. weights = linearSamplingWeights;
  56632. // Generate shaders
  56633. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  56634. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  56635. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  56636. var defines = "";
  56637. for (var i = 0; i < varyingCount; i++) {
  56638. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  56639. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  56640. }
  56641. var depCount = 0;
  56642. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  56643. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  56644. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  56645. depCount++;
  56646. }
  56647. if (this.packedFloat) {
  56648. defines += "#define PACKEDFLOAT 1";
  56649. }
  56650. this.updateEffect(defines, null, null, {
  56651. varyingCount: varyingCount,
  56652. depCount: depCount
  56653. });
  56654. };
  56655. /**
  56656. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  56657. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  56658. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  56659. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  56660. * The gaps between physical kernels are compensated for in the weighting of the samples
  56661. * @param idealKernel Ideal blur kernel.
  56662. * @return Nearest best kernel.
  56663. */
  56664. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  56665. var v = Math.round(idealKernel);
  56666. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  56667. var k = _a[_i];
  56668. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  56669. return Math.max(k, 3);
  56670. }
  56671. }
  56672. return Math.max(v, 3);
  56673. };
  56674. /**
  56675. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  56676. * @param x The point on the Gaussian distribution to sample.
  56677. * @return the value of the Gaussian function at x.
  56678. */
  56679. BlurPostProcess.prototype._gaussianWeight = function (x) {
  56680. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  56681. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  56682. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  56683. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  56684. // truncated at around 1.3% of peak strength.
  56685. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  56686. var sigma = (1 / 3);
  56687. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  56688. var exponent = -((x * x) / (2.0 * sigma * sigma));
  56689. var weight = (1.0 / denominator) * Math.exp(exponent);
  56690. return weight;
  56691. };
  56692. /**
  56693. * Generates a string that can be used as a floating point number in GLSL.
  56694. * @param x Value to print.
  56695. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  56696. * @return GLSL float string.
  56697. */
  56698. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  56699. if (decimalFigures === void 0) { decimalFigures = 8; }
  56700. return x.toFixed(decimalFigures).replace(/0+$/, '');
  56701. };
  56702. return BlurPostProcess;
  56703. }(BABYLON.PostProcess));
  56704. BABYLON.BlurPostProcess = BlurPostProcess;
  56705. })(BABYLON || (BABYLON = {}));
  56706. //# sourceMappingURL=babylon.blurPostProcess.js.map
  56707. /// <reference path="..\babylon.node.ts" />
  56708. var BABYLON;
  56709. (function (BABYLON) {
  56710. var Bone = (function (_super) {
  56711. __extends(Bone, _super);
  56712. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  56713. if (parentBone === void 0) { parentBone = null; }
  56714. var _this = _super.call(this, name, skeleton.getScene()) || this;
  56715. _this.name = name;
  56716. _this.children = new Array();
  56717. _this.animations = new Array();
  56718. _this._worldTransform = new BABYLON.Matrix();
  56719. _this._absoluteTransform = new BABYLON.Matrix();
  56720. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  56721. _this._scaleMatrix = BABYLON.Matrix.Identity();
  56722. _this._scaleVector = BABYLON.Vector3.One();
  56723. _this._negateScaleChildren = BABYLON.Vector3.One();
  56724. _this._scalingDeterminant = 1;
  56725. _this._skeleton = skeleton;
  56726. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  56727. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  56728. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  56729. _this._index = index;
  56730. skeleton.bones.push(_this);
  56731. _this.setParent(parentBone, false);
  56732. _this._updateDifferenceMatrix();
  56733. return _this;
  56734. }
  56735. Object.defineProperty(Bone.prototype, "_matrix", {
  56736. get: function () {
  56737. return this._localMatrix;
  56738. },
  56739. set: function (val) {
  56740. if (this._localMatrix) {
  56741. this._localMatrix.copyFrom(val);
  56742. }
  56743. else {
  56744. this._localMatrix = val;
  56745. }
  56746. },
  56747. enumerable: true,
  56748. configurable: true
  56749. });
  56750. // Members
  56751. Bone.prototype.getSkeleton = function () {
  56752. return this._skeleton;
  56753. };
  56754. Bone.prototype.getParent = function () {
  56755. return this._parent;
  56756. };
  56757. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  56758. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  56759. if (this._parent === parent) {
  56760. return;
  56761. }
  56762. if (this._parent) {
  56763. var index = this._parent.children.indexOf(this);
  56764. if (index !== -1) {
  56765. this._parent.children.splice(index);
  56766. }
  56767. }
  56768. this._parent = parent;
  56769. if (this._parent) {
  56770. this._parent.children.push(this);
  56771. }
  56772. if (updateDifferenceMatrix) {
  56773. this._updateDifferenceMatrix();
  56774. }
  56775. };
  56776. Bone.prototype.getLocalMatrix = function () {
  56777. return this._localMatrix;
  56778. };
  56779. Bone.prototype.getBaseMatrix = function () {
  56780. return this._baseMatrix;
  56781. };
  56782. Bone.prototype.getRestPose = function () {
  56783. return this._restPose;
  56784. };
  56785. Bone.prototype.returnToRest = function () {
  56786. this.updateMatrix(this._restPose.clone());
  56787. };
  56788. Bone.prototype.getWorldMatrix = function () {
  56789. return this._worldTransform;
  56790. };
  56791. Bone.prototype.getInvertedAbsoluteTransform = function () {
  56792. return this._invertedAbsoluteTransform;
  56793. };
  56794. Bone.prototype.getAbsoluteTransform = function () {
  56795. return this._absoluteTransform;
  56796. };
  56797. Object.defineProperty(Bone.prototype, "position", {
  56798. // Properties (matches AbstractMesh properties)
  56799. get: function () {
  56800. return this.getPosition();
  56801. },
  56802. set: function (newPosition) {
  56803. this.setPosition(newPosition);
  56804. },
  56805. enumerable: true,
  56806. configurable: true
  56807. });
  56808. Object.defineProperty(Bone.prototype, "rotation", {
  56809. get: function () {
  56810. return this.getRotation();
  56811. },
  56812. set: function (newRotation) {
  56813. this.setRotation(newRotation);
  56814. },
  56815. enumerable: true,
  56816. configurable: true
  56817. });
  56818. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  56819. get: function () {
  56820. return this.getRotationQuaternion();
  56821. },
  56822. set: function (newRotation) {
  56823. this.setRotationQuaternion(newRotation);
  56824. },
  56825. enumerable: true,
  56826. configurable: true
  56827. });
  56828. Object.defineProperty(Bone.prototype, "scaling", {
  56829. get: function () {
  56830. return this.getScale();
  56831. },
  56832. set: function (newScaling) {
  56833. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  56834. },
  56835. enumerable: true,
  56836. configurable: true
  56837. });
  56838. // Methods
  56839. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  56840. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  56841. this._baseMatrix = matrix.clone();
  56842. this._localMatrix = matrix.clone();
  56843. this._skeleton._markAsDirty();
  56844. if (updateDifferenceMatrix) {
  56845. this._updateDifferenceMatrix();
  56846. }
  56847. };
  56848. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  56849. if (!rootMatrix) {
  56850. rootMatrix = this._baseMatrix;
  56851. }
  56852. if (this._parent) {
  56853. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  56854. }
  56855. else {
  56856. this._absoluteTransform.copyFrom(rootMatrix);
  56857. }
  56858. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  56859. for (var index = 0; index < this.children.length; index++) {
  56860. this.children[index]._updateDifferenceMatrix();
  56861. }
  56862. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  56863. };
  56864. Bone.prototype.markAsDirty = function () {
  56865. this._currentRenderId++;
  56866. this._skeleton._markAsDirty();
  56867. };
  56868. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  56869. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  56870. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  56871. // all animation may be coming from a library skeleton, so may need to create animation
  56872. if (this.animations.length === 0) {
  56873. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  56874. this.animations[0].setKeys([]);
  56875. }
  56876. // get animation info / verify there is such a range from the source bone
  56877. var sourceRange = source.animations[0].getRange(rangeName);
  56878. if (!sourceRange) {
  56879. return false;
  56880. }
  56881. var from = sourceRange.from;
  56882. var to = sourceRange.to;
  56883. var sourceKeys = source.animations[0].getKeys();
  56884. // rescaling prep
  56885. var sourceBoneLength = source.length;
  56886. var sourceParent = source.getParent();
  56887. var parent = this.getParent();
  56888. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  56889. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  56890. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  56891. var destKeys = this.animations[0].getKeys();
  56892. // loop vars declaration
  56893. var orig;
  56894. var origTranslation;
  56895. var mat;
  56896. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  56897. orig = sourceKeys[key];
  56898. if (orig.frame >= from && orig.frame <= to) {
  56899. if (rescaleAsRequired) {
  56900. mat = orig.value.clone();
  56901. // scale based on parent ratio, when bone has parent
  56902. if (parentScalingReqd) {
  56903. origTranslation = mat.getTranslation();
  56904. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  56905. // scale based on skeleton dimension ratio when root bone, and value is passed
  56906. }
  56907. else if (dimensionsScalingReqd) {
  56908. origTranslation = mat.getTranslation();
  56909. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  56910. // use original when root bone, and no data for skelDimensionsRatio
  56911. }
  56912. else {
  56913. mat = orig.value;
  56914. }
  56915. }
  56916. else {
  56917. mat = orig.value;
  56918. }
  56919. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  56920. }
  56921. }
  56922. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  56923. return true;
  56924. };
  56925. /**
  56926. * Translate the bone in local or world space.
  56927. * @param vec The amount to translate the bone.
  56928. * @param space The space that the translation is in.
  56929. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56930. */
  56931. Bone.prototype.translate = function (vec, space, mesh) {
  56932. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56933. var lm = this.getLocalMatrix();
  56934. if (space == BABYLON.Space.LOCAL) {
  56935. lm.m[12] += vec.x;
  56936. lm.m[13] += vec.y;
  56937. lm.m[14] += vec.z;
  56938. }
  56939. else {
  56940. var wm;
  56941. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56942. if (mesh) {
  56943. wm = mesh.getWorldMatrix();
  56944. }
  56945. this._skeleton.computeAbsoluteTransforms();
  56946. var tmat = Bone._tmpMats[0];
  56947. var tvec = Bone._tmpVecs[0];
  56948. if (mesh) {
  56949. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56950. tmat.multiplyToRef(wm, tmat);
  56951. }
  56952. else {
  56953. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56954. }
  56955. tmat.m[12] = 0;
  56956. tmat.m[13] = 0;
  56957. tmat.m[14] = 0;
  56958. tmat.invert();
  56959. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  56960. lm.m[12] += tvec.x;
  56961. lm.m[13] += tvec.y;
  56962. lm.m[14] += tvec.z;
  56963. }
  56964. this.markAsDirty();
  56965. };
  56966. /**
  56967. * Set the postion of the bone in local or world space.
  56968. * @param position The position to set the bone.
  56969. * @param space The space that the position is in.
  56970. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56971. */
  56972. Bone.prototype.setPosition = function (position, space, mesh) {
  56973. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56974. var lm = this.getLocalMatrix();
  56975. if (space == BABYLON.Space.LOCAL) {
  56976. lm.m[12] = position.x;
  56977. lm.m[13] = position.y;
  56978. lm.m[14] = position.z;
  56979. }
  56980. else {
  56981. var wm;
  56982. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56983. if (mesh) {
  56984. wm = mesh.getWorldMatrix();
  56985. }
  56986. this._skeleton.computeAbsoluteTransforms();
  56987. var tmat = Bone._tmpMats[0];
  56988. var vec = Bone._tmpVecs[0];
  56989. if (mesh) {
  56990. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56991. tmat.multiplyToRef(wm, tmat);
  56992. }
  56993. else {
  56994. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56995. }
  56996. tmat.invert();
  56997. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  56998. lm.m[12] = vec.x;
  56999. lm.m[13] = vec.y;
  57000. lm.m[14] = vec.z;
  57001. }
  57002. this.markAsDirty();
  57003. };
  57004. /**
  57005. * Set the absolute postion of the bone (world space).
  57006. * @param position The position to set the bone.
  57007. * @param mesh The mesh that this bone is attached to.
  57008. */
  57009. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  57010. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  57011. };
  57012. /**
  57013. * Set the scale of the bone on the x, y and z axes.
  57014. * @param x The scale of the bone on the x axis.
  57015. * @param x The scale of the bone on the y axis.
  57016. * @param z The scale of the bone on the z axis.
  57017. * @param scaleChildren Set this to true if children of the bone should be scaled.
  57018. */
  57019. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  57020. if (scaleChildren === void 0) { scaleChildren = false; }
  57021. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  57022. if (!scaleChildren) {
  57023. this._negateScaleChildren.x = 1 / x;
  57024. this._negateScaleChildren.y = 1 / y;
  57025. this._negateScaleChildren.z = 1 / z;
  57026. }
  57027. this._syncScaleVector();
  57028. }
  57029. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  57030. };
  57031. /**
  57032. * Scale the bone on the x, y and z axes.
  57033. * @param x The amount to scale the bone on the x axis.
  57034. * @param x The amount to scale the bone on the y axis.
  57035. * @param z The amount to scale the bone on the z axis.
  57036. * @param scaleChildren Set this to true if children of the bone should be scaled.
  57037. */
  57038. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  57039. if (scaleChildren === void 0) { scaleChildren = false; }
  57040. var locMat = this.getLocalMatrix();
  57041. var origLocMat = Bone._tmpMats[0];
  57042. origLocMat.copyFrom(locMat);
  57043. var origLocMatInv = Bone._tmpMats[1];
  57044. origLocMatInv.copyFrom(origLocMat);
  57045. origLocMatInv.invert();
  57046. var scaleMat = Bone._tmpMats[2];
  57047. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  57048. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  57049. this._scaleVector.x *= x;
  57050. this._scaleVector.y *= y;
  57051. this._scaleVector.z *= z;
  57052. locMat.multiplyToRef(origLocMatInv, locMat);
  57053. locMat.multiplyToRef(scaleMat, locMat);
  57054. locMat.multiplyToRef(origLocMat, locMat);
  57055. var parent = this.getParent();
  57056. if (parent) {
  57057. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  57058. }
  57059. else {
  57060. this.getAbsoluteTransform().copyFrom(locMat);
  57061. }
  57062. var len = this.children.length;
  57063. scaleMat.invert();
  57064. for (var i = 0; i < len; i++) {
  57065. var child = this.children[i];
  57066. var cm = child.getLocalMatrix();
  57067. cm.multiplyToRef(scaleMat, cm);
  57068. var lm = child.getLocalMatrix();
  57069. lm.m[12] *= x;
  57070. lm.m[13] *= y;
  57071. lm.m[14] *= z;
  57072. }
  57073. this.computeAbsoluteTransforms();
  57074. if (scaleChildren) {
  57075. for (var i = 0; i < len; i++) {
  57076. this.children[i].scale(x, y, z, scaleChildren);
  57077. }
  57078. }
  57079. this.markAsDirty();
  57080. };
  57081. /**
  57082. * Set the yaw, pitch, and roll of the bone in local or world space.
  57083. * @param yaw The rotation of the bone on the y axis.
  57084. * @param pitch The rotation of the bone on the x axis.
  57085. * @param roll The rotation of the bone on the z axis.
  57086. * @param space The space that the axes of rotation are in.
  57087. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57088. */
  57089. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  57090. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57091. var rotMat = Bone._tmpMats[0];
  57092. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  57093. var rotMatInv = Bone._tmpMats[1];
  57094. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57095. rotMatInv.multiplyToRef(rotMat, rotMat);
  57096. this._rotateWithMatrix(rotMat, space, mesh);
  57097. };
  57098. /**
  57099. * Rotate the bone on an axis in local or world space.
  57100. * @param axis The axis to rotate the bone on.
  57101. * @param amount The amount to rotate the bone.
  57102. * @param space The space that the axis is in.
  57103. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57104. */
  57105. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  57106. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57107. var rmat = Bone._tmpMats[0];
  57108. rmat.m[12] = 0;
  57109. rmat.m[13] = 0;
  57110. rmat.m[14] = 0;
  57111. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  57112. this._rotateWithMatrix(rmat, space, mesh);
  57113. };
  57114. /**
  57115. * Set the rotation of the bone to a particular axis angle in local or world space.
  57116. * @param axis The axis to rotate the bone on.
  57117. * @param angle The angle that the bone should be rotated to.
  57118. * @param space The space that the axis is in.
  57119. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57120. */
  57121. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  57122. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57123. var rotMat = Bone._tmpMats[0];
  57124. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  57125. var rotMatInv = Bone._tmpMats[1];
  57126. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57127. rotMatInv.multiplyToRef(rotMat, rotMat);
  57128. this._rotateWithMatrix(rotMat, space, mesh);
  57129. };
  57130. /**
  57131. * Set the euler rotation of the bone in local of world space.
  57132. * @param rotation The euler rotation that the bone should be set to.
  57133. * @param space The space that the rotation is in.
  57134. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57135. */
  57136. Bone.prototype.setRotation = function (rotation, space, mesh) {
  57137. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57138. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  57139. };
  57140. /**
  57141. * Set the quaternion rotation of the bone in local of world space.
  57142. * @param quat The quaternion rotation that the bone should be set to.
  57143. * @param space The space that the rotation is in.
  57144. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57145. */
  57146. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  57147. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57148. var rotMatInv = Bone._tmpMats[0];
  57149. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57150. var rotMat = Bone._tmpMats[1];
  57151. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  57152. rotMatInv.multiplyToRef(rotMat, rotMat);
  57153. this._rotateWithMatrix(rotMat, space, mesh);
  57154. };
  57155. /**
  57156. * Set the rotation matrix of the bone in local of world space.
  57157. * @param rotMat The rotation matrix that the bone should be set to.
  57158. * @param space The space that the rotation is in.
  57159. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57160. */
  57161. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  57162. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57163. var rotMatInv = Bone._tmpMats[0];
  57164. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57165. var rotMat2 = Bone._tmpMats[1];
  57166. rotMat2.copyFrom(rotMat);
  57167. rotMatInv.multiplyToRef(rotMat, rotMat2);
  57168. this._rotateWithMatrix(rotMat2, space, mesh);
  57169. };
  57170. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  57171. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57172. var lmat = this.getLocalMatrix();
  57173. var lx = lmat.m[12];
  57174. var ly = lmat.m[13];
  57175. var lz = lmat.m[14];
  57176. var parent = this.getParent();
  57177. var parentScale = Bone._tmpMats[3];
  57178. var parentScaleInv = Bone._tmpMats[4];
  57179. if (parent) {
  57180. if (space == BABYLON.Space.WORLD) {
  57181. if (mesh) {
  57182. parentScale.copyFrom(mesh.getWorldMatrix());
  57183. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  57184. }
  57185. else {
  57186. parentScale.copyFrom(parent.getAbsoluteTransform());
  57187. }
  57188. }
  57189. else {
  57190. parentScale = parent._scaleMatrix;
  57191. }
  57192. parentScaleInv.copyFrom(parentScale);
  57193. parentScaleInv.invert();
  57194. lmat.multiplyToRef(parentScale, lmat);
  57195. lmat.multiplyToRef(rmat, lmat);
  57196. lmat.multiplyToRef(parentScaleInv, lmat);
  57197. }
  57198. else {
  57199. if (space == BABYLON.Space.WORLD && mesh) {
  57200. parentScale.copyFrom(mesh.getWorldMatrix());
  57201. parentScaleInv.copyFrom(parentScale);
  57202. parentScaleInv.invert();
  57203. lmat.multiplyToRef(parentScale, lmat);
  57204. lmat.multiplyToRef(rmat, lmat);
  57205. lmat.multiplyToRef(parentScaleInv, lmat);
  57206. }
  57207. else {
  57208. lmat.multiplyToRef(rmat, lmat);
  57209. }
  57210. }
  57211. lmat.m[12] = lx;
  57212. lmat.m[13] = ly;
  57213. lmat.m[14] = lz;
  57214. this.computeAbsoluteTransforms();
  57215. this.markAsDirty();
  57216. };
  57217. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  57218. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57219. if (space == BABYLON.Space.WORLD) {
  57220. var scaleMatrix = Bone._tmpMats[2];
  57221. scaleMatrix.copyFrom(this._scaleMatrix);
  57222. rotMatInv.copyFrom(this.getAbsoluteTransform());
  57223. if (mesh) {
  57224. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  57225. var meshScale = Bone._tmpMats[3];
  57226. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  57227. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  57228. }
  57229. rotMatInv.invert();
  57230. scaleMatrix.m[0] *= this._scalingDeterminant;
  57231. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  57232. }
  57233. else {
  57234. rotMatInv.copyFrom(this.getLocalMatrix());
  57235. rotMatInv.invert();
  57236. var scaleMatrix = Bone._tmpMats[2];
  57237. scaleMatrix.copyFrom(this._scaleMatrix);
  57238. if (this._parent) {
  57239. var pscaleMatrix = Bone._tmpMats[3];
  57240. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  57241. pscaleMatrix.invert();
  57242. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  57243. }
  57244. else {
  57245. scaleMatrix.m[0] *= this._scalingDeterminant;
  57246. }
  57247. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  57248. }
  57249. };
  57250. /**
  57251. * Get the scale of the bone
  57252. * @returns the scale of the bone
  57253. */
  57254. Bone.prototype.getScale = function () {
  57255. return this._scaleVector.clone();
  57256. };
  57257. /**
  57258. * Copy the scale of the bone to a vector3.
  57259. * @param result The vector3 to copy the scale to
  57260. */
  57261. Bone.prototype.getScaleToRef = function (result) {
  57262. result.copyFrom(this._scaleVector);
  57263. };
  57264. /**
  57265. * Get the position of the bone in local or world space.
  57266. * @param space The space that the returned position is in.
  57267. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57268. * @returns The position of the bone
  57269. */
  57270. Bone.prototype.getPosition = function (space, mesh) {
  57271. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57272. var pos = BABYLON.Vector3.Zero();
  57273. this.getPositionToRef(space, mesh, pos);
  57274. return pos;
  57275. };
  57276. /**
  57277. * Copy the position of the bone to a vector3 in local or world space.
  57278. * @param space The space that the returned position is in.
  57279. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57280. * @param result The vector3 to copy the position to.
  57281. */
  57282. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  57283. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57284. if (space == BABYLON.Space.LOCAL) {
  57285. var lm = this.getLocalMatrix();
  57286. result.x = lm.m[12];
  57287. result.y = lm.m[13];
  57288. result.z = lm.m[14];
  57289. }
  57290. else {
  57291. var wm;
  57292. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57293. if (mesh) {
  57294. wm = mesh.getWorldMatrix();
  57295. }
  57296. this._skeleton.computeAbsoluteTransforms();
  57297. var tmat = Bone._tmpMats[0];
  57298. if (mesh) {
  57299. tmat.copyFrom(this.getAbsoluteTransform());
  57300. tmat.multiplyToRef(wm, tmat);
  57301. }
  57302. else {
  57303. tmat = this.getAbsoluteTransform();
  57304. }
  57305. result.x = tmat.m[12];
  57306. result.y = tmat.m[13];
  57307. result.z = tmat.m[14];
  57308. }
  57309. };
  57310. /**
  57311. * Get the absolute position of the bone (world space).
  57312. * @param mesh The mesh that this bone is attached to.
  57313. * @returns The absolute position of the bone
  57314. */
  57315. Bone.prototype.getAbsolutePosition = function (mesh) {
  57316. var pos = BABYLON.Vector3.Zero();
  57317. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  57318. return pos;
  57319. };
  57320. /**
  57321. * Copy the absolute position of the bone (world space) to the result param.
  57322. * @param mesh The mesh that this bone is attached to.
  57323. * @param result The vector3 to copy the absolute position to.
  57324. */
  57325. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  57326. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  57327. };
  57328. /**
  57329. * Compute the absolute transforms of this bone and its children.
  57330. */
  57331. Bone.prototype.computeAbsoluteTransforms = function () {
  57332. if (this._parent) {
  57333. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  57334. }
  57335. else {
  57336. this._absoluteTransform.copyFrom(this._localMatrix);
  57337. var poseMatrix = this._skeleton.getPoseMatrix();
  57338. if (poseMatrix) {
  57339. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  57340. }
  57341. }
  57342. var children = this.children;
  57343. var len = children.length;
  57344. for (var i = 0; i < len; i++) {
  57345. children[i].computeAbsoluteTransforms();
  57346. }
  57347. };
  57348. Bone.prototype._syncScaleVector = function () {
  57349. var lm = this.getLocalMatrix();
  57350. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  57351. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  57352. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  57353. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  57354. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  57355. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  57356. this._scaleVector.x = xs * Math.sqrt(xsq);
  57357. this._scaleVector.y = ys * Math.sqrt(ysq);
  57358. this._scaleVector.z = zs * Math.sqrt(zsq);
  57359. if (this._parent) {
  57360. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  57361. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  57362. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  57363. }
  57364. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  57365. };
  57366. /**
  57367. * Get the world direction from an axis that is in the local space of the bone.
  57368. * @param localAxis The local direction that is used to compute the world direction.
  57369. * @param mesh The mesh that this bone is attached to.
  57370. * @returns The world direction
  57371. */
  57372. Bone.prototype.getDirection = function (localAxis, mesh) {
  57373. var result = BABYLON.Vector3.Zero();
  57374. this.getDirectionToRef(localAxis, mesh, result);
  57375. return result;
  57376. };
  57377. /**
  57378. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  57379. * @param localAxis The local direction that is used to compute the world direction.
  57380. * @param mesh The mesh that this bone is attached to.
  57381. * @param result The vector3 that the world direction will be copied to.
  57382. */
  57383. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  57384. var wm;
  57385. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57386. if (mesh) {
  57387. wm = mesh.getWorldMatrix();
  57388. }
  57389. this._skeleton.computeAbsoluteTransforms();
  57390. var mat = Bone._tmpMats[0];
  57391. mat.copyFrom(this.getAbsoluteTransform());
  57392. if (mesh) {
  57393. mat.multiplyToRef(wm, mat);
  57394. }
  57395. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  57396. result.normalize();
  57397. };
  57398. /**
  57399. * Get the euler rotation of the bone in local or world space.
  57400. * @param space The space that the rotation should be in.
  57401. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57402. * @returns The euler rotation
  57403. */
  57404. Bone.prototype.getRotation = function (space, mesh) {
  57405. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57406. var result = BABYLON.Vector3.Zero();
  57407. this.getRotationToRef(space, mesh, result);
  57408. return result;
  57409. };
  57410. /**
  57411. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  57412. * @param space The space that the rotation should be in.
  57413. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57414. * @param result The vector3 that the rotation should be copied to.
  57415. */
  57416. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  57417. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57418. var quat = Bone._tmpQuat;
  57419. this.getRotationQuaternionToRef(space, mesh, quat);
  57420. quat.toEulerAnglesToRef(result);
  57421. };
  57422. /**
  57423. * Get the quaternion rotation of the bone in either local or world space.
  57424. * @param space The space that the rotation should be in.
  57425. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57426. * @returns The quaternion rotation
  57427. */
  57428. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  57429. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57430. var result = BABYLON.Quaternion.Identity();
  57431. this.getRotationQuaternionToRef(space, mesh, result);
  57432. return result;
  57433. };
  57434. /**
  57435. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  57436. * @param space The space that the rotation should be in.
  57437. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57438. * @param result The quaternion that the rotation should be copied to.
  57439. */
  57440. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  57441. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57442. if (space == BABYLON.Space.LOCAL) {
  57443. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  57444. }
  57445. else {
  57446. var mat = Bone._tmpMats[0];
  57447. var amat = this.getAbsoluteTransform();
  57448. if (mesh) {
  57449. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  57450. }
  57451. else {
  57452. mat.copyFrom(amat);
  57453. }
  57454. mat.m[0] *= this._scalingDeterminant;
  57455. mat.m[1] *= this._scalingDeterminant;
  57456. mat.m[2] *= this._scalingDeterminant;
  57457. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  57458. }
  57459. };
  57460. /**
  57461. * Get the rotation matrix of the bone in local or world space.
  57462. * @param space The space that the rotation should be in.
  57463. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57464. * @returns The rotation matrix
  57465. */
  57466. Bone.prototype.getRotationMatrix = function (space, mesh) {
  57467. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57468. var result = BABYLON.Matrix.Identity();
  57469. this.getRotationMatrixToRef(space, mesh, result);
  57470. return result;
  57471. };
  57472. /**
  57473. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  57474. * @param space The space that the rotation should be in.
  57475. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57476. * @param result The quaternion that the rotation should be copied to.
  57477. */
  57478. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  57479. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57480. if (space == BABYLON.Space.LOCAL) {
  57481. this.getLocalMatrix().getRotationMatrixToRef(result);
  57482. }
  57483. else {
  57484. var mat = Bone._tmpMats[0];
  57485. var amat = this.getAbsoluteTransform();
  57486. if (mesh) {
  57487. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  57488. }
  57489. else {
  57490. mat.copyFrom(amat);
  57491. }
  57492. mat.m[0] *= this._scalingDeterminant;
  57493. mat.m[1] *= this._scalingDeterminant;
  57494. mat.m[2] *= this._scalingDeterminant;
  57495. mat.getRotationMatrixToRef(result);
  57496. }
  57497. };
  57498. /**
  57499. * Get the world position of a point that is in the local space of the bone.
  57500. * @param position The local position
  57501. * @param mesh The mesh that this bone is attached to.
  57502. * @returns The world position
  57503. */
  57504. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  57505. var result = BABYLON.Vector3.Zero();
  57506. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  57507. return result;
  57508. };
  57509. /**
  57510. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  57511. * @param position The local position
  57512. * @param mesh The mesh that this bone is attached to.
  57513. * @param result The vector3 that the world position should be copied to.
  57514. */
  57515. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  57516. var wm;
  57517. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57518. if (mesh) {
  57519. wm = mesh.getWorldMatrix();
  57520. }
  57521. this._skeleton.computeAbsoluteTransforms();
  57522. var tmat = Bone._tmpMats[0];
  57523. if (mesh) {
  57524. tmat.copyFrom(this.getAbsoluteTransform());
  57525. tmat.multiplyToRef(wm, tmat);
  57526. }
  57527. else {
  57528. tmat = this.getAbsoluteTransform();
  57529. }
  57530. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  57531. };
  57532. /**
  57533. * Get the local position of a point that is in world space.
  57534. * @param position The world position
  57535. * @param mesh The mesh that this bone is attached to.
  57536. * @returns The local position
  57537. */
  57538. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  57539. var result = BABYLON.Vector3.Zero();
  57540. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  57541. return result;
  57542. };
  57543. /**
  57544. * Get the local position of a point that is in world space and copy it to the result param.
  57545. * @param position The world position
  57546. * @param mesh The mesh that this bone is attached to.
  57547. * @param result The vector3 that the local position should be copied to.
  57548. */
  57549. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  57550. var wm;
  57551. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57552. if (mesh) {
  57553. wm = mesh.getWorldMatrix();
  57554. }
  57555. this._skeleton.computeAbsoluteTransforms();
  57556. var tmat = Bone._tmpMats[0];
  57557. tmat.copyFrom(this.getAbsoluteTransform());
  57558. if (mesh) {
  57559. tmat.multiplyToRef(wm, tmat);
  57560. }
  57561. tmat.invert();
  57562. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  57563. };
  57564. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57565. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  57566. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  57567. return Bone;
  57568. }(BABYLON.Node));
  57569. BABYLON.Bone = Bone;
  57570. })(BABYLON || (BABYLON = {}));
  57571. //# sourceMappingURL=babylon.bone.js.map
  57572. var BABYLON;
  57573. (function (BABYLON) {
  57574. var BoneIKController = (function () {
  57575. function BoneIKController(mesh, bone, options) {
  57576. this.targetPosition = BABYLON.Vector3.Zero();
  57577. this.poleTargetPosition = BABYLON.Vector3.Zero();
  57578. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  57579. this.poleAngle = 0;
  57580. this.slerpAmount = 1;
  57581. this._bone1Quat = BABYLON.Quaternion.Identity();
  57582. this._bone1Mat = BABYLON.Matrix.Identity();
  57583. this._bone2Ang = Math.PI;
  57584. this._maxAngle = Math.PI;
  57585. this._rightHandedSystem = false;
  57586. this._bendAxis = BABYLON.Vector3.Right();
  57587. this._slerping = false;
  57588. this._adjustRoll = 0;
  57589. this._bone2 = bone;
  57590. this._bone1 = bone.getParent();
  57591. this.mesh = mesh;
  57592. var bonePos = bone.getPosition();
  57593. if (bone.getAbsoluteTransform().determinant() > 0) {
  57594. this._rightHandedSystem = true;
  57595. this._bendAxis.x = 0;
  57596. this._bendAxis.y = 0;
  57597. this._bendAxis.z = -1;
  57598. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  57599. this._adjustRoll = Math.PI * .5;
  57600. this._bendAxis.z = 1;
  57601. }
  57602. }
  57603. if (this._bone1.length) {
  57604. var boneScale1 = this._bone1.getScale();
  57605. var boneScale2 = this._bone2.getScale();
  57606. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  57607. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  57608. }
  57609. else if (this._bone1.children[0]) {
  57610. mesh.computeWorldMatrix(true);
  57611. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  57612. var pos2 = this._bone2.getAbsolutePosition(mesh);
  57613. var pos3 = this._bone1.getAbsolutePosition(mesh);
  57614. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  57615. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  57616. }
  57617. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  57618. this.maxAngle = Math.PI;
  57619. if (options) {
  57620. if (options.targetMesh) {
  57621. this.targetMesh = options.targetMesh;
  57622. this.targetMesh.computeWorldMatrix(true);
  57623. }
  57624. if (options.poleTargetMesh) {
  57625. this.poleTargetMesh = options.poleTargetMesh;
  57626. this.poleTargetMesh.computeWorldMatrix(true);
  57627. }
  57628. else if (options.poleTargetBone) {
  57629. this.poleTargetBone = options.poleTargetBone;
  57630. }
  57631. else if (this._bone1.getParent()) {
  57632. this.poleTargetBone = this._bone1.getParent();
  57633. }
  57634. if (options.poleTargetLocalOffset) {
  57635. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  57636. }
  57637. if (options.poleAngle) {
  57638. this.poleAngle = options.poleAngle;
  57639. }
  57640. if (options.bendAxis) {
  57641. this._bendAxis.copyFrom(options.bendAxis);
  57642. }
  57643. if (options.maxAngle) {
  57644. this.maxAngle = options.maxAngle;
  57645. }
  57646. if (options.slerpAmount) {
  57647. this.slerpAmount = options.slerpAmount;
  57648. }
  57649. }
  57650. }
  57651. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  57652. get: function () {
  57653. return this._maxAngle;
  57654. },
  57655. set: function (value) {
  57656. this._setMaxAngle(value);
  57657. },
  57658. enumerable: true,
  57659. configurable: true
  57660. });
  57661. BoneIKController.prototype._setMaxAngle = function (ang) {
  57662. if (ang < 0) {
  57663. ang = 0;
  57664. }
  57665. if (ang > Math.PI || ang == undefined) {
  57666. ang = Math.PI;
  57667. }
  57668. this._maxAngle = ang;
  57669. var a = this._bone1Length;
  57670. var b = this._bone2Length;
  57671. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  57672. };
  57673. BoneIKController.prototype.update = function () {
  57674. var bone1 = this._bone1;
  57675. var target = this.targetPosition;
  57676. var poleTarget = this.poleTargetPosition;
  57677. var mat1 = BoneIKController._tmpMats[0];
  57678. var mat2 = BoneIKController._tmpMats[1];
  57679. if (this.targetMesh) {
  57680. target.copyFrom(this.targetMesh.getAbsolutePosition());
  57681. }
  57682. if (this.poleTargetBone) {
  57683. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  57684. }
  57685. else if (this.poleTargetMesh) {
  57686. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  57687. }
  57688. var bonePos = BoneIKController._tmpVecs[0];
  57689. var zaxis = BoneIKController._tmpVecs[1];
  57690. var xaxis = BoneIKController._tmpVecs[2];
  57691. var yaxis = BoneIKController._tmpVecs[3];
  57692. var upAxis = BoneIKController._tmpVecs[4];
  57693. var _tmpQuat = BoneIKController._tmpQuat;
  57694. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  57695. poleTarget.subtractToRef(bonePos, upAxis);
  57696. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  57697. upAxis.y = 1;
  57698. }
  57699. else {
  57700. upAxis.normalize();
  57701. }
  57702. target.subtractToRef(bonePos, yaxis);
  57703. yaxis.normalize();
  57704. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  57705. zaxis.normalize();
  57706. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  57707. xaxis.normalize();
  57708. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  57709. var a = this._bone1Length;
  57710. var b = this._bone2Length;
  57711. var c = BABYLON.Vector3.Distance(bonePos, target);
  57712. if (this._maxReach > 0) {
  57713. c = Math.min(this._maxReach, c);
  57714. }
  57715. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  57716. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  57717. if (acosa > 1) {
  57718. acosa = 1;
  57719. }
  57720. if (acosb > 1) {
  57721. acosb = 1;
  57722. }
  57723. if (acosa < -1) {
  57724. acosa = -1;
  57725. }
  57726. if (acosb < -1) {
  57727. acosb = -1;
  57728. }
  57729. var angA = Math.acos(acosa);
  57730. var angB = Math.acos(acosb);
  57731. var angC = -angA - angB;
  57732. if (this._rightHandedSystem) {
  57733. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  57734. mat2.multiplyToRef(mat1, mat1);
  57735. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  57736. mat2.multiplyToRef(mat1, mat1);
  57737. }
  57738. else {
  57739. var _tmpVec = BoneIKController._tmpVecs[5];
  57740. _tmpVec.copyFrom(this._bendAxis);
  57741. _tmpVec.x *= -1;
  57742. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  57743. mat2.multiplyToRef(mat1, mat1);
  57744. }
  57745. if (this.poleAngle) {
  57746. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  57747. mat1.multiplyToRef(mat2, mat1);
  57748. }
  57749. if (this.slerpAmount < 1) {
  57750. if (!this._slerping) {
  57751. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  57752. }
  57753. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  57754. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  57755. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  57756. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  57757. this._slerping = true;
  57758. }
  57759. else {
  57760. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  57761. this._bone1Mat.copyFrom(mat1);
  57762. this._slerping = false;
  57763. }
  57764. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  57765. this._bone2Ang = angC;
  57766. };
  57767. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57768. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  57769. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  57770. return BoneIKController;
  57771. }());
  57772. BABYLON.BoneIKController = BoneIKController;
  57773. })(BABYLON || (BABYLON = {}));
  57774. //# sourceMappingURL=babylon.boneIKController.js.map
  57775. var BABYLON;
  57776. (function (BABYLON) {
  57777. var BoneLookController = (function () {
  57778. /**
  57779. * Create a BoneLookController
  57780. * @param mesh the mesh that the bone belongs to
  57781. * @param bone the bone that will be looking to the target
  57782. * @param target the target Vector3 to look at
  57783. * @param settings optional settings:
  57784. * - maxYaw: the maximum angle the bone will yaw to
  57785. * - minYaw: the minimum angle the bone will yaw to
  57786. * - maxPitch: the maximum angle the bone will pitch to
  57787. * - minPitch: the minimum angle the bone will yaw to
  57788. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  57789. * - upAxis: the up axis of the coordinate system
  57790. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  57791. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  57792. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  57793. * - adjustYaw: used to make an adjustment to the yaw of the bone
  57794. * - adjustPitch: used to make an adjustment to the pitch of the bone
  57795. * - adjustRoll: used to make an adjustment to the roll of the bone
  57796. **/
  57797. function BoneLookController(mesh, bone, target, options) {
  57798. /**
  57799. * The up axis of the coordinate system that is used when the bone is rotated.
  57800. */
  57801. this.upAxis = BABYLON.Vector3.Up();
  57802. /**
  57803. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  57804. */
  57805. this.upAxisSpace = BABYLON.Space.LOCAL;
  57806. /**
  57807. * Used to make an adjustment to the yaw of the bone.
  57808. */
  57809. this.adjustYaw = 0;
  57810. /**
  57811. * Used to make an adjustment to the pitch of the bone.
  57812. */
  57813. this.adjustPitch = 0;
  57814. /**
  57815. * Used to make an adjustment to the roll of the bone.
  57816. */
  57817. this.adjustRoll = 0;
  57818. /**
  57819. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp).
  57820. */
  57821. this.slerpAmount = 1;
  57822. this._boneQuat = BABYLON.Quaternion.Identity();
  57823. this._slerping = false;
  57824. this._firstFrameSkipped = false;
  57825. this._fowardAxis = BABYLON.Vector3.Forward();
  57826. this.mesh = mesh;
  57827. this.bone = bone;
  57828. this.target = target;
  57829. if (options) {
  57830. if (options.adjustYaw) {
  57831. this.adjustYaw = options.adjustYaw;
  57832. }
  57833. if (options.adjustPitch) {
  57834. this.adjustPitch = options.adjustPitch;
  57835. }
  57836. if (options.adjustRoll) {
  57837. this.adjustRoll = options.adjustRoll;
  57838. }
  57839. if (options.maxYaw != null) {
  57840. this.maxYaw = options.maxYaw;
  57841. }
  57842. else {
  57843. this.maxYaw = Math.PI;
  57844. }
  57845. if (options.minYaw != null) {
  57846. this.minYaw = options.minYaw;
  57847. }
  57848. else {
  57849. this.minYaw = -Math.PI;
  57850. }
  57851. if (options.maxPitch != null) {
  57852. this.maxPitch = options.maxPitch;
  57853. }
  57854. else {
  57855. this.maxPitch = Math.PI;
  57856. }
  57857. if (options.minPitch != null) {
  57858. this.minPitch = options.minPitch;
  57859. }
  57860. else {
  57861. this.minPitch = -Math.PI;
  57862. }
  57863. if (options.slerpAmount != null) {
  57864. this.slerpAmount = options.slerpAmount;
  57865. }
  57866. if (options.upAxis != null) {
  57867. this.upAxis = options.upAxis;
  57868. }
  57869. if (options.upAxisSpace != null) {
  57870. this.upAxisSpace = options.upAxisSpace;
  57871. }
  57872. if (options.yawAxis != null || options.pitchAxis != null) {
  57873. var newYawAxis = BABYLON.Axis.Y;
  57874. var newPitchAxis = BABYLON.Axis.X;
  57875. if (options.yawAxis != null) {
  57876. newYawAxis = options.yawAxis.clone();
  57877. newYawAxis.normalize();
  57878. }
  57879. if (options.pitchAxis != null) {
  57880. newPitchAxis = options.pitchAxis.clone();
  57881. newPitchAxis.normalize();
  57882. }
  57883. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  57884. this._transformYawPitch = BABYLON.Matrix.Identity();
  57885. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  57886. this._transformYawPitchInv = this._transformYawPitch.clone();
  57887. this._transformYawPitch.invert();
  57888. }
  57889. }
  57890. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  57891. this.upAxisSpace = BABYLON.Space.LOCAL;
  57892. }
  57893. }
  57894. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  57895. /**
  57896. * Get/set the minimum yaw angle that the bone can look to.
  57897. */
  57898. get: function () {
  57899. return this._minYaw;
  57900. },
  57901. set: function (value) {
  57902. this._minYaw = value;
  57903. this._minYawSin = Math.sin(value);
  57904. this._minYawCos = Math.cos(value);
  57905. if (this._maxYaw != null) {
  57906. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  57907. this._yawRange = this._maxYaw - this._minYaw;
  57908. }
  57909. },
  57910. enumerable: true,
  57911. configurable: true
  57912. });
  57913. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  57914. /**
  57915. * Get/set the maximum yaw angle that the bone can look to.
  57916. */
  57917. get: function () {
  57918. return this._maxYaw;
  57919. },
  57920. set: function (value) {
  57921. this._maxYaw = value;
  57922. this._maxYawSin = Math.sin(value);
  57923. this._maxYawCos = Math.cos(value);
  57924. if (this._minYaw != null) {
  57925. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  57926. this._yawRange = this._maxYaw - this._minYaw;
  57927. }
  57928. },
  57929. enumerable: true,
  57930. configurable: true
  57931. });
  57932. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  57933. /**
  57934. * Get/set the minimum pitch angle that the bone can look to.
  57935. */
  57936. get: function () {
  57937. return this._minPitch;
  57938. },
  57939. set: function (value) {
  57940. this._minPitch = value;
  57941. this._minPitchTan = Math.tan(value);
  57942. },
  57943. enumerable: true,
  57944. configurable: true
  57945. });
  57946. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  57947. /**
  57948. * Get/set the maximum pitch angle that the bone can look to.
  57949. */
  57950. get: function () {
  57951. return this._maxPitch;
  57952. },
  57953. set: function (value) {
  57954. this._maxPitch = value;
  57955. this._maxPitchTan = Math.tan(value);
  57956. },
  57957. enumerable: true,
  57958. configurable: true
  57959. });
  57960. /**
  57961. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  57962. */
  57963. BoneLookController.prototype.update = function () {
  57964. //skip the first frame when slerping so that the mesh rotation is correct
  57965. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  57966. this._firstFrameSkipped = true;
  57967. return;
  57968. }
  57969. var bone = this.bone;
  57970. var bonePos = BoneLookController._tmpVecs[0];
  57971. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  57972. var target = this.target;
  57973. var _tmpMat1 = BoneLookController._tmpMats[0];
  57974. var _tmpMat2 = BoneLookController._tmpMats[1];
  57975. var mesh = this.mesh;
  57976. var parentBone = bone.getParent();
  57977. var upAxis = BoneLookController._tmpVecs[1];
  57978. upAxis.copyFrom(this.upAxis);
  57979. if (this.upAxisSpace == BABYLON.Space.BONE) {
  57980. if (this._transformYawPitch) {
  57981. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  57982. }
  57983. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  57984. }
  57985. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  57986. mesh.getDirectionToRef(upAxis, upAxis);
  57987. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  57988. upAxis.normalize();
  57989. }
  57990. }
  57991. var checkYaw = false;
  57992. var checkPitch = false;
  57993. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  57994. checkYaw = true;
  57995. }
  57996. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  57997. checkPitch = true;
  57998. }
  57999. if (checkYaw || checkPitch) {
  58000. var spaceMat = BoneLookController._tmpMats[2];
  58001. var spaceMatInv = BoneLookController._tmpMats[3];
  58002. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  58003. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  58004. }
  58005. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  58006. spaceMat.copyFrom(mesh.getWorldMatrix());
  58007. }
  58008. else {
  58009. var forwardAxis = BoneLookController._tmpVecs[2];
  58010. forwardAxis.copyFrom(this._fowardAxis);
  58011. if (this._transformYawPitch) {
  58012. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  58013. }
  58014. if (parentBone) {
  58015. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  58016. }
  58017. else {
  58018. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  58019. }
  58020. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  58021. rightAxis.normalize();
  58022. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  58023. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  58024. }
  58025. spaceMat.invertToRef(spaceMatInv);
  58026. var xzlen;
  58027. if (checkPitch) {
  58028. var localTarget = BoneLookController._tmpVecs[3];
  58029. target.subtractToRef(bonePos, localTarget);
  58030. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  58031. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  58032. var pitch = Math.atan2(localTarget.y, xzlen);
  58033. var newPitch = pitch;
  58034. if (pitch > this._maxPitch) {
  58035. localTarget.y = this._maxPitchTan * xzlen;
  58036. newPitch = this._maxPitch;
  58037. }
  58038. else if (pitch < this._minPitch) {
  58039. localTarget.y = this._minPitchTan * xzlen;
  58040. newPitch = this._minPitch;
  58041. }
  58042. if (pitch != newPitch) {
  58043. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  58044. localTarget.addInPlace(bonePos);
  58045. target = localTarget;
  58046. }
  58047. }
  58048. if (checkYaw) {
  58049. var localTarget = BoneLookController._tmpVecs[4];
  58050. target.subtractToRef(bonePos, localTarget);
  58051. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  58052. var yaw = Math.atan2(localTarget.x, localTarget.z);
  58053. var newYaw = yaw;
  58054. if (yaw > this._maxYaw || yaw < this._minYaw) {
  58055. if (xzlen == null) {
  58056. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  58057. }
  58058. if (this._yawRange > Math.PI) {
  58059. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  58060. localTarget.z = this._maxYawCos * xzlen;
  58061. localTarget.x = this._maxYawSin * xzlen;
  58062. newYaw = this._maxYaw;
  58063. }
  58064. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  58065. localTarget.z = this._minYawCos * xzlen;
  58066. localTarget.x = this._minYawSin * xzlen;
  58067. newYaw = this._minYaw;
  58068. }
  58069. }
  58070. else {
  58071. if (yaw > this._maxYaw) {
  58072. localTarget.z = this._maxYawCos * xzlen;
  58073. localTarget.x = this._maxYawSin * xzlen;
  58074. newYaw = this._maxYaw;
  58075. }
  58076. else if (yaw < this._minYaw) {
  58077. localTarget.z = this._minYawCos * xzlen;
  58078. localTarget.x = this._minYawSin * xzlen;
  58079. newYaw = this._minYaw;
  58080. }
  58081. }
  58082. }
  58083. if (this._slerping && this._yawRange > Math.PI) {
  58084. //are we going to be crossing into the min/max region?
  58085. var boneFwd = BoneLookController._tmpVecs[8];
  58086. boneFwd.copyFrom(BABYLON.Axis.Z);
  58087. if (this._transformYawPitch) {
  58088. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  58089. }
  58090. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  58091. this._boneQuat.toRotationMatrix(boneRotMat);
  58092. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  58093. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  58094. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  58095. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  58096. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  58097. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  58098. if (angBtwTar > angBtwMidYaw) {
  58099. if (xzlen == null) {
  58100. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  58101. }
  58102. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  58103. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  58104. if (angBtwMin < angBtwMax) {
  58105. newYaw = boneYaw + Math.PI * .75;
  58106. localTarget.z = Math.cos(newYaw) * xzlen;
  58107. localTarget.x = Math.sin(newYaw) * xzlen;
  58108. }
  58109. else {
  58110. newYaw = boneYaw - Math.PI * .75;
  58111. localTarget.z = Math.cos(newYaw) * xzlen;
  58112. localTarget.x = Math.sin(newYaw) * xzlen;
  58113. }
  58114. }
  58115. }
  58116. if (yaw != newYaw) {
  58117. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  58118. localTarget.addInPlace(bonePos);
  58119. target = localTarget;
  58120. }
  58121. }
  58122. }
  58123. var zaxis = BoneLookController._tmpVecs[5];
  58124. var xaxis = BoneLookController._tmpVecs[6];
  58125. var yaxis = BoneLookController._tmpVecs[7];
  58126. var _tmpQuat = BoneLookController._tmpQuat;
  58127. target.subtractToRef(bonePos, zaxis);
  58128. zaxis.normalize();
  58129. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  58130. xaxis.normalize();
  58131. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  58132. yaxis.normalize();
  58133. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  58134. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  58135. return;
  58136. }
  58137. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  58138. return;
  58139. }
  58140. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  58141. return;
  58142. }
  58143. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  58144. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  58145. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  58146. }
  58147. if (this.slerpAmount < 1) {
  58148. if (!this._slerping) {
  58149. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  58150. }
  58151. if (this._transformYawPitch) {
  58152. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  58153. }
  58154. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  58155. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  58156. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  58157. this._slerping = true;
  58158. }
  58159. else {
  58160. if (this._transformYawPitch) {
  58161. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  58162. }
  58163. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  58164. this._slerping = false;
  58165. }
  58166. };
  58167. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  58168. var angDiff = ang2 - ang1;
  58169. angDiff %= Math.PI * 2;
  58170. if (angDiff > Math.PI) {
  58171. angDiff -= Math.PI * 2;
  58172. }
  58173. else if (angDiff < -Math.PI) {
  58174. angDiff += Math.PI * 2;
  58175. }
  58176. return angDiff;
  58177. };
  58178. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  58179. ang1 %= (2 * Math.PI);
  58180. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  58181. ang2 %= (2 * Math.PI);
  58182. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  58183. var ab = 0;
  58184. if (ang1 < ang2) {
  58185. ab = ang2 - ang1;
  58186. }
  58187. else {
  58188. ab = ang1 - ang2;
  58189. }
  58190. if (ab > Math.PI) {
  58191. ab = Math.PI * 2 - ab;
  58192. }
  58193. return ab;
  58194. };
  58195. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  58196. ang %= (2 * Math.PI);
  58197. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  58198. ang1 %= (2 * Math.PI);
  58199. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  58200. ang2 %= (2 * Math.PI);
  58201. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  58202. if (ang1 < ang2) {
  58203. if (ang > ang1 && ang < ang2) {
  58204. return true;
  58205. }
  58206. }
  58207. else {
  58208. if (ang > ang2 && ang < ang1) {
  58209. return true;
  58210. }
  58211. }
  58212. return false;
  58213. };
  58214. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58215. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  58216. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  58217. return BoneLookController;
  58218. }());
  58219. BABYLON.BoneLookController = BoneLookController;
  58220. })(BABYLON || (BABYLON = {}));
  58221. //# sourceMappingURL=babylon.boneLookController.js.map
  58222. var BABYLON;
  58223. (function (BABYLON) {
  58224. var Skeleton = (function () {
  58225. function Skeleton(name, id, scene) {
  58226. this.name = name;
  58227. this.id = id;
  58228. this.bones = new Array();
  58229. this.needInitialSkinMatrix = false;
  58230. this._isDirty = true;
  58231. this._meshesWithPoseMatrix = new Array();
  58232. this._identity = BABYLON.Matrix.Identity();
  58233. this._ranges = {};
  58234. this._lastAbsoluteTransformsUpdateId = -1;
  58235. // Events
  58236. /**
  58237. * An event triggered before computing the skeleton's matrices
  58238. * @type {BABYLON.Observable}
  58239. */
  58240. this.onBeforeComputeObservable = new BABYLON.Observable();
  58241. this.bones = [];
  58242. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58243. scene.skeletons.push(this);
  58244. //make sure it will recalculate the matrix next time prepare is called.
  58245. this._isDirty = true;
  58246. }
  58247. // Members
  58248. Skeleton.prototype.getTransformMatrices = function (mesh) {
  58249. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  58250. return mesh._bonesTransformMatrices;
  58251. }
  58252. if (!this._transformMatrices) {
  58253. this.prepare();
  58254. }
  58255. return this._transformMatrices;
  58256. };
  58257. Skeleton.prototype.getScene = function () {
  58258. return this._scene;
  58259. };
  58260. // Methods
  58261. /**
  58262. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  58263. */
  58264. Skeleton.prototype.toString = function (fullDetails) {
  58265. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  58266. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  58267. if (fullDetails) {
  58268. ret += ", Ranges: {";
  58269. var first = true;
  58270. for (var name_1 in this._ranges) {
  58271. if (first) {
  58272. ret += ", ";
  58273. first = false;
  58274. }
  58275. ret += name_1;
  58276. }
  58277. ret += "}";
  58278. }
  58279. return ret;
  58280. };
  58281. /**
  58282. * Get bone's index searching by name
  58283. * @param {string} name is bone's name to search for
  58284. * @return {number} Indice of the bone. Returns -1 if not found
  58285. */
  58286. Skeleton.prototype.getBoneIndexByName = function (name) {
  58287. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  58288. if (this.bones[boneIndex].name === name) {
  58289. return boneIndex;
  58290. }
  58291. }
  58292. return -1;
  58293. };
  58294. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  58295. // check name not already in use
  58296. if (!this._ranges[name]) {
  58297. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  58298. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58299. if (this.bones[i].animations[0]) {
  58300. this.bones[i].animations[0].createRange(name, from, to);
  58301. }
  58302. }
  58303. }
  58304. };
  58305. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  58306. if (deleteFrames === void 0) { deleteFrames = true; }
  58307. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58308. if (this.bones[i].animations[0]) {
  58309. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  58310. }
  58311. }
  58312. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  58313. };
  58314. Skeleton.prototype.getAnimationRange = function (name) {
  58315. return this._ranges[name];
  58316. };
  58317. /**
  58318. * Returns as an Array, all AnimationRanges defined on this skeleton
  58319. */
  58320. Skeleton.prototype.getAnimationRanges = function () {
  58321. var animationRanges = [];
  58322. var name;
  58323. var i = 0;
  58324. for (name in this._ranges) {
  58325. animationRanges[i] = this._ranges[name];
  58326. i++;
  58327. }
  58328. return animationRanges;
  58329. };
  58330. /**
  58331. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  58332. */
  58333. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  58334. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  58335. if (this._ranges[name] || !source.getAnimationRange(name)) {
  58336. return false;
  58337. }
  58338. var ret = true;
  58339. var frameOffset = this._getHighestAnimationFrame() + 1;
  58340. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  58341. var boneDict = {};
  58342. var sourceBones = source.bones;
  58343. var nBones;
  58344. var i;
  58345. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  58346. boneDict[sourceBones[i].name] = sourceBones[i];
  58347. }
  58348. if (this.bones.length !== sourceBones.length) {
  58349. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  58350. ret = false;
  58351. }
  58352. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  58353. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  58354. var boneName = this.bones[i].name;
  58355. var sourceBone = boneDict[boneName];
  58356. if (sourceBone) {
  58357. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  58358. }
  58359. else {
  58360. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  58361. ret = false;
  58362. }
  58363. }
  58364. // do not call createAnimationRange(), since it also is done to bones, which was already done
  58365. var range = source.getAnimationRange(name);
  58366. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  58367. return ret;
  58368. };
  58369. Skeleton.prototype.returnToRest = function () {
  58370. for (var index = 0; index < this.bones.length; index++) {
  58371. this.bones[index].returnToRest();
  58372. }
  58373. };
  58374. Skeleton.prototype._getHighestAnimationFrame = function () {
  58375. var ret = 0;
  58376. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58377. if (this.bones[i].animations[0]) {
  58378. var highest = this.bones[i].animations[0].getHighestFrame();
  58379. if (ret < highest) {
  58380. ret = highest;
  58381. }
  58382. }
  58383. }
  58384. return ret;
  58385. };
  58386. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  58387. var range = this.getAnimationRange(name);
  58388. if (!range) {
  58389. return null;
  58390. }
  58391. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  58392. };
  58393. Skeleton.prototype._markAsDirty = function () {
  58394. this._isDirty = true;
  58395. };
  58396. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  58397. this._meshesWithPoseMatrix.push(mesh);
  58398. };
  58399. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  58400. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  58401. if (index > -1) {
  58402. this._meshesWithPoseMatrix.splice(index, 1);
  58403. }
  58404. };
  58405. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  58406. this.onBeforeComputeObservable.notifyObservers(this);
  58407. for (var index = 0; index < this.bones.length; index++) {
  58408. var bone = this.bones[index];
  58409. var parentBone = bone.getParent();
  58410. if (parentBone) {
  58411. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  58412. }
  58413. else {
  58414. if (initialSkinMatrix) {
  58415. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  58416. }
  58417. else {
  58418. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  58419. }
  58420. }
  58421. if (bone._index !== -1) {
  58422. var mappedIndex = bone._index === undefined ? index : bone._index;
  58423. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  58424. }
  58425. }
  58426. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  58427. };
  58428. Skeleton.prototype.prepare = function () {
  58429. if (!this._isDirty) {
  58430. return;
  58431. }
  58432. if (this.needInitialSkinMatrix) {
  58433. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  58434. var mesh = this._meshesWithPoseMatrix[index];
  58435. var poseMatrix = mesh.getPoseMatrix();
  58436. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  58437. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  58438. }
  58439. if (this._synchronizedWithMesh !== mesh) {
  58440. this._synchronizedWithMesh = mesh;
  58441. // Prepare bones
  58442. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  58443. var bone = this.bones[boneIndex];
  58444. if (!bone.getParent()) {
  58445. var matrix = bone.getBaseMatrix();
  58446. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  58447. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  58448. }
  58449. }
  58450. }
  58451. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  58452. }
  58453. }
  58454. else {
  58455. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  58456. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  58457. }
  58458. this._computeTransformMatrices(this._transformMatrices, null);
  58459. }
  58460. this._isDirty = false;
  58461. this._scene._activeBones.addCount(this.bones.length, false);
  58462. };
  58463. Skeleton.prototype.getAnimatables = function () {
  58464. if (!this._animatables || this._animatables.length !== this.bones.length) {
  58465. this._animatables = [];
  58466. for (var index = 0; index < this.bones.length; index++) {
  58467. this._animatables.push(this.bones[index]);
  58468. }
  58469. }
  58470. return this._animatables;
  58471. };
  58472. Skeleton.prototype.clone = function (name, id) {
  58473. var result = new Skeleton(name, id || name, this._scene);
  58474. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  58475. for (var index = 0; index < this.bones.length; index++) {
  58476. var source = this.bones[index];
  58477. var parentBone = null;
  58478. if (source.getParent()) {
  58479. var parentIndex = this.bones.indexOf(source.getParent());
  58480. parentBone = result.bones[parentIndex];
  58481. }
  58482. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  58483. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  58484. }
  58485. if (this._ranges) {
  58486. result._ranges = {};
  58487. for (var rangeName in this._ranges) {
  58488. result._ranges[rangeName] = this._ranges[rangeName].clone();
  58489. }
  58490. }
  58491. this._isDirty = true;
  58492. return result;
  58493. };
  58494. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  58495. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  58496. this.bones.forEach(function (bone) {
  58497. bone.animations.forEach(function (animation) {
  58498. animation.enableBlending = true;
  58499. animation.blendingSpeed = blendingSpeed;
  58500. });
  58501. });
  58502. };
  58503. Skeleton.prototype.dispose = function () {
  58504. this._meshesWithPoseMatrix = [];
  58505. // Animations
  58506. this.getScene().stopAnimation(this);
  58507. // Remove from scene
  58508. this.getScene().removeSkeleton(this);
  58509. };
  58510. Skeleton.prototype.serialize = function () {
  58511. var serializationObject = {};
  58512. serializationObject.name = this.name;
  58513. serializationObject.id = this.id;
  58514. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  58515. serializationObject.bones = [];
  58516. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  58517. for (var index = 0; index < this.bones.length; index++) {
  58518. var bone = this.bones[index];
  58519. var serializedBone = {
  58520. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  58521. name: bone.name,
  58522. matrix: bone.getBaseMatrix().toArray(),
  58523. rest: bone.getRestPose().toArray()
  58524. };
  58525. serializationObject.bones.push(serializedBone);
  58526. if (bone.length) {
  58527. serializedBone.length = bone.length;
  58528. }
  58529. if (bone.animations && bone.animations.length > 0) {
  58530. serializedBone.animation = bone.animations[0].serialize();
  58531. }
  58532. serializationObject.ranges = [];
  58533. for (var name in this._ranges) {
  58534. var range = {};
  58535. range.name = name;
  58536. range.from = this._ranges[name].from;
  58537. range.to = this._ranges[name].to;
  58538. serializationObject.ranges.push(range);
  58539. }
  58540. }
  58541. return serializationObject;
  58542. };
  58543. Skeleton.Parse = function (parsedSkeleton, scene) {
  58544. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  58545. if (parsedSkeleton.dimensionsAtRest) {
  58546. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  58547. }
  58548. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  58549. var index;
  58550. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  58551. var parsedBone = parsedSkeleton.bones[index];
  58552. var parentBone = null;
  58553. if (parsedBone.parentBoneIndex > -1) {
  58554. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  58555. }
  58556. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  58557. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  58558. if (parsedBone.length) {
  58559. bone.length = parsedBone.length;
  58560. }
  58561. if (parsedBone.animation) {
  58562. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  58563. }
  58564. }
  58565. // placed after bones, so createAnimationRange can cascade down
  58566. if (parsedSkeleton.ranges) {
  58567. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  58568. var data = parsedSkeleton.ranges[index];
  58569. skeleton.createAnimationRange(data.name, data.from, data.to);
  58570. }
  58571. }
  58572. return skeleton;
  58573. };
  58574. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  58575. if (forceUpdate === void 0) { forceUpdate = false; }
  58576. var renderId = this._scene.getRenderId();
  58577. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  58578. this.bones[0].computeAbsoluteTransforms();
  58579. this._lastAbsoluteTransformsUpdateId = renderId;
  58580. }
  58581. };
  58582. Skeleton.prototype.getPoseMatrix = function () {
  58583. var poseMatrix;
  58584. if (this._meshesWithPoseMatrix.length > 0) {
  58585. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  58586. }
  58587. return poseMatrix;
  58588. };
  58589. Skeleton.prototype.sortBones = function () {
  58590. var bones = new Array();
  58591. var visited = new Array(this.bones.length);
  58592. for (var index = 0; index < this.bones.length; index++) {
  58593. this._sortBones(index, bones, visited);
  58594. }
  58595. this.bones = bones;
  58596. };
  58597. Skeleton.prototype._sortBones = function (index, bones, visited) {
  58598. if (visited[index]) {
  58599. return;
  58600. }
  58601. visited[index] = true;
  58602. var bone = this.bones[index];
  58603. if (bone._index === undefined) {
  58604. bone._index = index;
  58605. }
  58606. var parentBone = bone.getParent();
  58607. if (parentBone) {
  58608. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  58609. }
  58610. bones.push(bone);
  58611. };
  58612. return Skeleton;
  58613. }());
  58614. BABYLON.Skeleton = Skeleton;
  58615. })(BABYLON || (BABYLON = {}));
  58616. //# sourceMappingURL=babylon.skeleton.js.map
  58617. var BABYLON;
  58618. (function (BABYLON) {
  58619. var SphericalPolynomial = (function () {
  58620. function SphericalPolynomial() {
  58621. this.x = BABYLON.Vector3.Zero();
  58622. this.y = BABYLON.Vector3.Zero();
  58623. this.z = BABYLON.Vector3.Zero();
  58624. this.xx = BABYLON.Vector3.Zero();
  58625. this.yy = BABYLON.Vector3.Zero();
  58626. this.zz = BABYLON.Vector3.Zero();
  58627. this.xy = BABYLON.Vector3.Zero();
  58628. this.yz = BABYLON.Vector3.Zero();
  58629. this.zx = BABYLON.Vector3.Zero();
  58630. }
  58631. SphericalPolynomial.prototype.addAmbient = function (color) {
  58632. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  58633. this.xx = this.xx.add(colorVector);
  58634. this.yy = this.yy.add(colorVector);
  58635. this.zz = this.zz.add(colorVector);
  58636. };
  58637. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  58638. var result = new SphericalPolynomial();
  58639. result.x = harmonics.L11.scale(1.02333);
  58640. result.y = harmonics.L1_1.scale(1.02333);
  58641. result.z = harmonics.L10.scale(1.02333);
  58642. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  58643. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  58644. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  58645. result.yz = harmonics.L2_1.scale(0.858086);
  58646. result.zx = harmonics.L21.scale(0.858086);
  58647. result.xy = harmonics.L2_2.scale(0.858086);
  58648. result.scale(1.0 / Math.PI);
  58649. return result;
  58650. };
  58651. SphericalPolynomial.prototype.scale = function (scale) {
  58652. this.x = this.x.scale(scale);
  58653. this.y = this.y.scale(scale);
  58654. this.z = this.z.scale(scale);
  58655. this.xx = this.xx.scale(scale);
  58656. this.yy = this.yy.scale(scale);
  58657. this.zz = this.zz.scale(scale);
  58658. this.yz = this.yz.scale(scale);
  58659. this.zx = this.zx.scale(scale);
  58660. this.xy = this.xy.scale(scale);
  58661. };
  58662. return SphericalPolynomial;
  58663. }());
  58664. BABYLON.SphericalPolynomial = SphericalPolynomial;
  58665. var SphericalHarmonics = (function () {
  58666. function SphericalHarmonics() {
  58667. this.L00 = BABYLON.Vector3.Zero();
  58668. this.L1_1 = BABYLON.Vector3.Zero();
  58669. this.L10 = BABYLON.Vector3.Zero();
  58670. this.L11 = BABYLON.Vector3.Zero();
  58671. this.L2_2 = BABYLON.Vector3.Zero();
  58672. this.L2_1 = BABYLON.Vector3.Zero();
  58673. this.L20 = BABYLON.Vector3.Zero();
  58674. this.L21 = BABYLON.Vector3.Zero();
  58675. this.L22 = BABYLON.Vector3.Zero();
  58676. }
  58677. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  58678. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  58679. var c = colorVector.scale(deltaSolidAngle);
  58680. this.L00 = this.L00.add(c.scale(0.282095));
  58681. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  58682. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  58683. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  58684. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  58685. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  58686. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  58687. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  58688. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  58689. };
  58690. SphericalHarmonics.prototype.scale = function (scale) {
  58691. this.L00 = this.L00.scale(scale);
  58692. this.L1_1 = this.L1_1.scale(scale);
  58693. this.L10 = this.L10.scale(scale);
  58694. this.L11 = this.L11.scale(scale);
  58695. this.L2_2 = this.L2_2.scale(scale);
  58696. this.L2_1 = this.L2_1.scale(scale);
  58697. this.L20 = this.L20.scale(scale);
  58698. this.L21 = this.L21.scale(scale);
  58699. this.L22 = this.L22.scale(scale);
  58700. };
  58701. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  58702. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  58703. //
  58704. // E_lm = A_l * L_lm
  58705. //
  58706. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  58707. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  58708. // the scaling factors are given in equation 9.
  58709. // Constant (Band 0)
  58710. this.L00 = this.L00.scale(3.141593);
  58711. // Linear (Band 1)
  58712. this.L1_1 = this.L1_1.scale(2.094395);
  58713. this.L10 = this.L10.scale(2.094395);
  58714. this.L11 = this.L11.scale(2.094395);
  58715. // Quadratic (Band 2)
  58716. this.L2_2 = this.L2_2.scale(0.785398);
  58717. this.L2_1 = this.L2_1.scale(0.785398);
  58718. this.L20 = this.L20.scale(0.785398);
  58719. this.L21 = this.L21.scale(0.785398);
  58720. this.L22 = this.L22.scale(0.785398);
  58721. };
  58722. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  58723. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  58724. // L = (1/pi) * E * rho
  58725. //
  58726. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  58727. this.scale(1.0 / Math.PI);
  58728. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  58729. // (The pixel shader must apply albedo after texture fetches, etc).
  58730. };
  58731. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  58732. var result = new SphericalHarmonics();
  58733. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  58734. result.L1_1 = polynomial.y.scale(0.977204);
  58735. result.L10 = polynomial.z.scale(0.977204);
  58736. result.L11 = polynomial.x.scale(0.977204);
  58737. result.L2_2 = polynomial.xy.scale(1.16538);
  58738. result.L2_1 = polynomial.yz.scale(1.16538);
  58739. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  58740. result.L21 = polynomial.zx.scale(1.16538);
  58741. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  58742. result.scale(Math.PI);
  58743. return result;
  58744. };
  58745. return SphericalHarmonics;
  58746. }());
  58747. BABYLON.SphericalHarmonics = SphericalHarmonics;
  58748. })(BABYLON || (BABYLON = {}));
  58749. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  58750. var BABYLON;
  58751. (function (BABYLON) {
  58752. var Internals;
  58753. (function (Internals) {
  58754. var FileFaceOrientation = (function () {
  58755. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  58756. this.name = name;
  58757. this.worldAxisForNormal = worldAxisForNormal;
  58758. this.worldAxisForFileX = worldAxisForFileX;
  58759. this.worldAxisForFileY = worldAxisForFileY;
  58760. }
  58761. return FileFaceOrientation;
  58762. }());
  58763. ;
  58764. /**
  58765. * Helper class dealing with the extraction of spherical polynomial dataArray
  58766. * from a cube map.
  58767. */
  58768. var CubeMapToSphericalPolynomialTools = (function () {
  58769. function CubeMapToSphericalPolynomialTools() {
  58770. }
  58771. /**
  58772. * Converts a texture to the according Spherical Polynomial data.
  58773. * This extracts the first 3 orders only as they are the only one used in the lighting.
  58774. *
  58775. * @param texture The texture to extract the information from.
  58776. * @return The Spherical Polynomial data.
  58777. */
  58778. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  58779. if (!texture.isCube) {
  58780. // Only supports cube Textures currently.
  58781. return null;
  58782. }
  58783. var size = texture.getSize().width;
  58784. var right = texture.readPixels(0);
  58785. var left = texture.readPixels(1);
  58786. var up;
  58787. var down;
  58788. if (texture.isRenderTarget) {
  58789. up = texture.readPixels(3);
  58790. down = texture.readPixels(2);
  58791. }
  58792. else {
  58793. up = texture.readPixels(2);
  58794. down = texture.readPixels(3);
  58795. }
  58796. var front = texture.readPixels(4);
  58797. var back = texture.readPixels(5);
  58798. var gammaSpace = texture.gammaSpace;
  58799. // Always read as RGBA.
  58800. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  58801. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58802. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58803. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58804. }
  58805. var cubeInfo = {
  58806. size: size,
  58807. right: right,
  58808. left: left,
  58809. up: up,
  58810. down: down,
  58811. front: front,
  58812. back: back,
  58813. format: format,
  58814. type: type,
  58815. gammaSpace: gammaSpace,
  58816. };
  58817. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  58818. };
  58819. /**
  58820. * Converts a cubemap to the according Spherical Polynomial data.
  58821. * This extracts the first 3 orders only as they are the only one used in the lighting.
  58822. *
  58823. * @param cubeInfo The Cube map to extract the information from.
  58824. * @return The Spherical Polynomial data.
  58825. */
  58826. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  58827. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  58828. var totalSolidAngle = 0.0;
  58829. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  58830. var du = 2.0 / cubeInfo.size;
  58831. var dv = du;
  58832. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  58833. var minUV = du * 0.5 - 1.0;
  58834. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58835. var fileFace = this.FileFaces[faceIndex];
  58836. var dataArray = cubeInfo[fileFace.name];
  58837. var v = minUV;
  58838. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  58839. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  58840. // Because SP is still linear, so summation is fine in that basis.
  58841. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  58842. for (var y = 0; y < cubeInfo.size; y++) {
  58843. var u = minUV;
  58844. for (var x = 0; x < cubeInfo.size; x++) {
  58845. // World direction (not normalised)
  58846. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  58847. worldDirection.normalize();
  58848. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  58849. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  58850. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  58851. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  58852. // Handle Integer types.
  58853. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58854. r /= 255;
  58855. g /= 255;
  58856. b /= 255;
  58857. }
  58858. // Handle Gamma space textures.
  58859. if (cubeInfo.gammaSpace) {
  58860. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  58861. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  58862. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  58863. }
  58864. var color = new BABYLON.Color3(r, g, b);
  58865. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58866. totalSolidAngle += deltaSolidAngle;
  58867. u += du;
  58868. }
  58869. v += dv;
  58870. }
  58871. }
  58872. // Solid angle for entire sphere is 4*pi
  58873. var sphereSolidAngle = 4.0 * Math.PI;
  58874. // Adjust the solid angle to allow for how many faces we processed.
  58875. var facesProcessed = 6.0;
  58876. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  58877. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  58878. // This is needed because the numerical integration over the cube uses a
  58879. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  58880. // and also to compensate for accumulative error due to float precision in the summation.
  58881. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  58882. sphericalHarmonics.scale(correctionFactor);
  58883. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  58884. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  58885. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  58886. };
  58887. CubeMapToSphericalPolynomialTools.FileFaces = [
  58888. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  58889. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  58890. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  58891. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  58892. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  58893. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  58894. ];
  58895. return CubeMapToSphericalPolynomialTools;
  58896. }());
  58897. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  58898. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58899. })(BABYLON || (BABYLON = {}));
  58900. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  58901. var BABYLON;
  58902. (function (BABYLON) {
  58903. var Internals;
  58904. (function (Internals) {
  58905. /**
  58906. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  58907. */
  58908. var PanoramaToCubeMapTools = (function () {
  58909. function PanoramaToCubeMapTools() {
  58910. }
  58911. /**
  58912. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  58913. *
  58914. * @param float32Array The source data.
  58915. * @param inputWidth The width of the input panorama.
  58916. * @param inputhHeight The height of the input panorama.
  58917. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  58918. * @return The cubemap data
  58919. */
  58920. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  58921. if (!float32Array) {
  58922. throw "ConvertPanoramaToCubemap: input cannot be null";
  58923. }
  58924. if (float32Array.length != inputWidth * inputHeight * 3) {
  58925. throw "ConvertPanoramaToCubemap: input size is wrong";
  58926. }
  58927. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  58928. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  58929. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  58930. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  58931. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  58932. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  58933. return {
  58934. front: textureFront,
  58935. back: textureBack,
  58936. left: textureLeft,
  58937. right: textureRight,
  58938. up: textureUp,
  58939. down: textureDown,
  58940. size: size,
  58941. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  58942. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  58943. gammaSpace: false,
  58944. };
  58945. };
  58946. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  58947. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  58948. var textureArray = new Float32Array(buffer);
  58949. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  58950. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  58951. var dy = 1 / texSize;
  58952. var fy = 0;
  58953. for (var y = 0; y < texSize; y++) {
  58954. var xv1 = faceData[0];
  58955. var xv2 = faceData[2];
  58956. for (var x = 0; x < texSize; x++) {
  58957. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  58958. v.normalize();
  58959. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  58960. // 3 channels per pixels
  58961. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  58962. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  58963. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  58964. xv1 = xv1.add(rotDX1);
  58965. xv2 = xv2.add(rotDX2);
  58966. }
  58967. fy += dy;
  58968. }
  58969. return textureArray;
  58970. };
  58971. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  58972. var theta = Math.atan2(vDir.z, vDir.x);
  58973. var phi = Math.acos(vDir.y);
  58974. while (theta < -Math.PI)
  58975. theta += 2 * Math.PI;
  58976. while (theta > Math.PI)
  58977. theta -= 2 * Math.PI;
  58978. var dx = theta / Math.PI;
  58979. var dy = phi / Math.PI;
  58980. // recenter.
  58981. dx = dx * 0.5 + 0.5;
  58982. var px = Math.round(dx * inputWidth);
  58983. if (px < 0)
  58984. px = 0;
  58985. else if (px >= inputWidth)
  58986. px = inputWidth - 1;
  58987. var py = Math.round(dy * inputHeight);
  58988. if (py < 0)
  58989. py = 0;
  58990. else if (py >= inputHeight)
  58991. py = inputHeight - 1;
  58992. var inputY = (inputHeight - py - 1);
  58993. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  58994. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  58995. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  58996. return {
  58997. r: r,
  58998. g: g,
  58999. b: b
  59000. };
  59001. };
  59002. PanoramaToCubeMapTools.FACE_FRONT = [
  59003. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  59004. new BABYLON.Vector3(1.0, -1.0, -1.0),
  59005. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  59006. new BABYLON.Vector3(1.0, 1.0, -1.0)
  59007. ];
  59008. PanoramaToCubeMapTools.FACE_BACK = [
  59009. new BABYLON.Vector3(1.0, -1.0, 1.0),
  59010. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  59011. new BABYLON.Vector3(1.0, 1.0, 1.0),
  59012. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  59013. ];
  59014. PanoramaToCubeMapTools.FACE_RIGHT = [
  59015. new BABYLON.Vector3(1.0, -1.0, -1.0),
  59016. new BABYLON.Vector3(1.0, -1.0, 1.0),
  59017. new BABYLON.Vector3(1.0, 1.0, -1.0),
  59018. new BABYLON.Vector3(1.0, 1.0, 1.0)
  59019. ];
  59020. PanoramaToCubeMapTools.FACE_LEFT = [
  59021. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  59022. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  59023. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  59024. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  59025. ];
  59026. PanoramaToCubeMapTools.FACE_DOWN = [
  59027. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  59028. new BABYLON.Vector3(1.0, 1.0, -1.0),
  59029. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  59030. new BABYLON.Vector3(1.0, 1.0, 1.0)
  59031. ];
  59032. PanoramaToCubeMapTools.FACE_UP = [
  59033. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  59034. new BABYLON.Vector3(1.0, -1.0, 1.0),
  59035. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  59036. new BABYLON.Vector3(1.0, -1.0, -1.0)
  59037. ];
  59038. return PanoramaToCubeMapTools;
  59039. }());
  59040. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  59041. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59042. })(BABYLON || (BABYLON = {}));
  59043. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  59044. var BABYLON;
  59045. (function (BABYLON) {
  59046. var Internals;
  59047. (function (Internals) {
  59048. ;
  59049. /**
  59050. * This groups tools to convert HDR texture to native colors array.
  59051. */
  59052. var HDRTools = (function () {
  59053. function HDRTools() {
  59054. }
  59055. HDRTools.Ldexp = function (mantissa, exponent) {
  59056. if (exponent > 1023) {
  59057. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  59058. }
  59059. if (exponent < -1074) {
  59060. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  59061. }
  59062. return mantissa * Math.pow(2, exponent);
  59063. };
  59064. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  59065. if (exponent > 0) {
  59066. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  59067. float32array[index + 0] = red * exponent;
  59068. float32array[index + 1] = green * exponent;
  59069. float32array[index + 2] = blue * exponent;
  59070. }
  59071. else {
  59072. float32array[index + 0] = 0;
  59073. float32array[index + 1] = 0;
  59074. float32array[index + 2] = 0;
  59075. }
  59076. };
  59077. HDRTools.readStringLine = function (uint8array, startIndex) {
  59078. var line = "";
  59079. var character = "";
  59080. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  59081. character = String.fromCharCode(uint8array[i]);
  59082. if (character == "\n") {
  59083. break;
  59084. }
  59085. line += character;
  59086. }
  59087. return line;
  59088. };
  59089. /**
  59090. * Reads header information from an RGBE texture stored in a native array.
  59091. * More information on this format are available here:
  59092. * https://en.wikipedia.org/wiki/RGBE_image_format
  59093. *
  59094. * @param uint8array The binary file stored in native array.
  59095. * @return The header information.
  59096. */
  59097. HDRTools.RGBE_ReadHeader = function (uint8array) {
  59098. var height = 0;
  59099. var width = 0;
  59100. var line = this.readStringLine(uint8array, 0);
  59101. if (line[0] != '#' || line[1] != '?') {
  59102. throw "Bad HDR Format.";
  59103. }
  59104. var endOfHeader = false;
  59105. var findFormat = false;
  59106. var lineIndex = 0;
  59107. do {
  59108. lineIndex += (line.length + 1);
  59109. line = this.readStringLine(uint8array, lineIndex);
  59110. if (line == "FORMAT=32-bit_rle_rgbe") {
  59111. findFormat = true;
  59112. }
  59113. else if (line.length == 0) {
  59114. endOfHeader = true;
  59115. }
  59116. } while (!endOfHeader);
  59117. if (!findFormat) {
  59118. throw "HDR Bad header format, unsupported FORMAT";
  59119. }
  59120. lineIndex += (line.length + 1);
  59121. line = this.readStringLine(uint8array, lineIndex);
  59122. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  59123. var match = sizeRegexp.exec(line);
  59124. // TODO. Support +Y and -X if needed.
  59125. if (match.length < 3) {
  59126. throw "HDR Bad header format, no size";
  59127. }
  59128. width = parseInt(match[2]);
  59129. height = parseInt(match[1]);
  59130. if (width < 8 || width > 0x7fff) {
  59131. throw "HDR Bad header format, unsupported size";
  59132. }
  59133. lineIndex += (line.length + 1);
  59134. return {
  59135. height: height,
  59136. width: width,
  59137. dataPosition: lineIndex
  59138. };
  59139. };
  59140. /**
  59141. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  59142. * This RGBE texture needs to store the information as a panorama.
  59143. *
  59144. * More information on this format are available here:
  59145. * https://en.wikipedia.org/wiki/RGBE_image_format
  59146. *
  59147. * @param buffer The binary file stored in an array buffer.
  59148. * @param size The expected size of the extracted cubemap.
  59149. * @return The Cube Map information.
  59150. */
  59151. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  59152. var uint8array = new Uint8Array(buffer);
  59153. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  59154. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  59155. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  59156. return cubeMapData;
  59157. };
  59158. /**
  59159. * Returns the pixels data extracted from an RGBE texture.
  59160. * This pixels will be stored left to right up to down in the R G B order in one array.
  59161. *
  59162. * More information on this format are available here:
  59163. * https://en.wikipedia.org/wiki/RGBE_image_format
  59164. *
  59165. * @param uint8array The binary file stored in an array buffer.
  59166. * @param hdrInfo The header information of the file.
  59167. * @return The pixels data in RGB right to left up to down order.
  59168. */
  59169. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  59170. // Keep for multi format supports.
  59171. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  59172. };
  59173. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  59174. var num_scanlines = hdrInfo.height;
  59175. var scanline_width = hdrInfo.width;
  59176. var a, b, c, d, count;
  59177. var dataIndex = hdrInfo.dataPosition;
  59178. var index = 0, endIndex = 0, i = 0;
  59179. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  59180. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  59181. // 3 channels of 4 bytes per pixel in float.
  59182. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  59183. var resultArray = new Float32Array(resultBuffer);
  59184. // read in each successive scanline
  59185. while (num_scanlines > 0) {
  59186. a = uint8array[dataIndex++];
  59187. b = uint8array[dataIndex++];
  59188. c = uint8array[dataIndex++];
  59189. d = uint8array[dataIndex++];
  59190. if (a != 2 || b != 2 || (c & 0x80)) {
  59191. // this file is not run length encoded
  59192. throw "HDR Bad header format, not RLE";
  59193. }
  59194. if (((c << 8) | d) != scanline_width) {
  59195. throw "HDR Bad header format, wrong scan line width";
  59196. }
  59197. index = 0;
  59198. // read each of the four channels for the scanline into the buffer
  59199. for (i = 0; i < 4; i++) {
  59200. endIndex = (i + 1) * scanline_width;
  59201. while (index < endIndex) {
  59202. a = uint8array[dataIndex++];
  59203. b = uint8array[dataIndex++];
  59204. if (a > 128) {
  59205. // a run of the same value
  59206. count = a - 128;
  59207. if ((count == 0) || (count > endIndex - index)) {
  59208. throw "HDR Bad Format, bad scanline data (run)";
  59209. }
  59210. while (count-- > 0) {
  59211. scanLineArray[index++] = b;
  59212. }
  59213. }
  59214. else {
  59215. // a non-run
  59216. count = a;
  59217. if ((count == 0) || (count > endIndex - index)) {
  59218. throw "HDR Bad Format, bad scanline data (non-run)";
  59219. }
  59220. scanLineArray[index++] = b;
  59221. if (--count > 0) {
  59222. for (var j = 0; j < count; j++) {
  59223. scanLineArray[index++] = uint8array[dataIndex++];
  59224. }
  59225. }
  59226. }
  59227. }
  59228. }
  59229. // now convert data from buffer into floats
  59230. for (i = 0; i < scanline_width; i++) {
  59231. a = scanLineArray[i];
  59232. b = scanLineArray[i + scanline_width];
  59233. c = scanLineArray[i + 2 * scanline_width];
  59234. d = scanLineArray[i + 3 * scanline_width];
  59235. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  59236. }
  59237. num_scanlines--;
  59238. }
  59239. return resultArray;
  59240. };
  59241. return HDRTools;
  59242. }());
  59243. Internals.HDRTools = HDRTools;
  59244. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59245. })(BABYLON || (BABYLON = {}));
  59246. //# sourceMappingURL=babylon.hdr.js.map
  59247. var BABYLON;
  59248. (function (BABYLON) {
  59249. /**
  59250. * This represents a texture coming from an HDR input.
  59251. *
  59252. * The only supported format is currently panorama picture stored in RGBE format.
  59253. * Example of such files can be found on HDRLib: http://hdrlib.com/
  59254. */
  59255. var HDRCubeTexture = (function (_super) {
  59256. __extends(HDRCubeTexture, _super);
  59257. /**
  59258. * Instantiates an HDRTexture from the following parameters.
  59259. *
  59260. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  59261. * @param scene The scene the texture will be used in
  59262. * @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.
  59263. * @param noMipmap Forces to not generate the mipmap if true
  59264. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  59265. * @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)
  59266. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  59267. */
  59268. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  59269. if (noMipmap === void 0) { noMipmap = false; }
  59270. if (generateHarmonics === void 0) { generateHarmonics = true; }
  59271. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  59272. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  59273. if (onLoad === void 0) { onLoad = null; }
  59274. if (onError === void 0) { onError = null; }
  59275. var _this = _super.call(this, scene) || this;
  59276. _this._useInGammaSpace = false;
  59277. _this._generateHarmonics = true;
  59278. _this._isBABYLONPreprocessed = false;
  59279. _this._onLoad = null;
  59280. _this._onError = null;
  59281. /**
  59282. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  59283. */
  59284. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  59285. /**
  59286. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  59287. * This is usefull at run time to apply the good shader.
  59288. */
  59289. _this.isPMREM = false;
  59290. _this._isBlocking = true;
  59291. if (!url) {
  59292. return _this;
  59293. }
  59294. _this.name = url;
  59295. _this.url = url;
  59296. _this.hasAlpha = false;
  59297. _this.isCube = true;
  59298. _this._textureMatrix = BABYLON.Matrix.Identity();
  59299. _this._onLoad = onLoad;
  59300. _this._onError = onError;
  59301. _this.gammaSpace = false;
  59302. if (size) {
  59303. _this._isBABYLONPreprocessed = false;
  59304. _this._noMipmap = noMipmap;
  59305. _this._size = size;
  59306. _this._useInGammaSpace = useInGammaSpace;
  59307. _this._usePMREMGenerator = usePMREMGenerator &&
  59308. scene.getEngine().getCaps().textureLOD &&
  59309. _this.getScene().getEngine().getCaps().textureFloat &&
  59310. !_this._useInGammaSpace;
  59311. }
  59312. else {
  59313. _this._isBABYLONPreprocessed = true;
  59314. _this._noMipmap = false;
  59315. _this._useInGammaSpace = false;
  59316. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  59317. _this.getScene().getEngine().getCaps().textureFloat &&
  59318. !_this._useInGammaSpace;
  59319. }
  59320. _this.isPMREM = _this._usePMREMGenerator;
  59321. _this._texture = _this._getFromCache(url, _this._noMipmap);
  59322. if (!_this._texture) {
  59323. if (!scene.useDelayedTextureLoading) {
  59324. _this.loadTexture();
  59325. }
  59326. else {
  59327. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59328. }
  59329. }
  59330. return _this;
  59331. }
  59332. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  59333. /**
  59334. * Gets wether or not the texture is blocking during loading.
  59335. */
  59336. get: function () {
  59337. return this._isBlocking;
  59338. },
  59339. /**
  59340. * Sets wether or not the texture is blocking during loading.
  59341. */
  59342. set: function (value) {
  59343. this._isBlocking = value;
  59344. },
  59345. enumerable: true,
  59346. configurable: true
  59347. });
  59348. /**
  59349. * Occurs when the file is a preprocessed .babylon.hdr file.
  59350. */
  59351. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  59352. var _this = this;
  59353. var mipLevels = 0;
  59354. var floatArrayView = null;
  59355. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  59356. var mips = [];
  59357. var startIndex = 30;
  59358. for (var level = 0; level < mipLevels; level++) {
  59359. mips.push([]);
  59360. // Fill each pixel of the mip level.
  59361. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  59362. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59363. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  59364. mips[level].push(faceData);
  59365. startIndex += faceSize;
  59366. }
  59367. }
  59368. return mips;
  59369. } : null;
  59370. var callback = function (buffer) {
  59371. // Create Native Array Views
  59372. var intArrayView = new Int32Array(buffer);
  59373. floatArrayView = new Float32Array(buffer);
  59374. // Fill header.
  59375. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  59376. _this._size = intArrayView[1]; // CubeMap max mip face size.
  59377. // Update Texture Information.
  59378. _this._texture.updateSize(_this._size, _this._size);
  59379. // Fill polynomial information.
  59380. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  59381. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  59382. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  59383. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  59384. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  59385. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  59386. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  59387. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  59388. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  59389. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  59390. _this.sphericalPolynomial = sphericalPolynomial;
  59391. // Fill pixel data.
  59392. mipLevels = intArrayView[29]; // Number of mip levels.
  59393. var startIndex = 30;
  59394. var data = [];
  59395. var faceSize = Math.pow(_this._size, 2) * 3;
  59396. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59397. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  59398. startIndex += faceSize;
  59399. }
  59400. var results = [];
  59401. var byteArray = null;
  59402. // Push each faces.
  59403. for (var k = 0; k < 6; k++) {
  59404. var dataFace = null;
  59405. // To be deprecated.
  59406. if (version === 1) {
  59407. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  59408. dataFace = data[j];
  59409. }
  59410. // If special cases.
  59411. if (!mipmapGenerator) {
  59412. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59413. // 3 channels of 1 bytes per pixel in bytes.
  59414. var byteBuffer = new ArrayBuffer(faceSize);
  59415. byteArray = new Uint8Array(byteBuffer);
  59416. }
  59417. for (var i = 0; i < _this._size * _this._size; i++) {
  59418. // Put in gamma space if requested.
  59419. if (_this._useInGammaSpace) {
  59420. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59421. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59422. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59423. }
  59424. // Convert to int texture for fallback.
  59425. if (byteArray) {
  59426. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59427. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59428. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59429. // May use luminance instead if the result is not accurate.
  59430. var max = Math.max(Math.max(r, g), b);
  59431. if (max > 255) {
  59432. var scale = 255 / max;
  59433. r *= scale;
  59434. g *= scale;
  59435. b *= scale;
  59436. }
  59437. byteArray[(i * 3) + 0] = r;
  59438. byteArray[(i * 3) + 1] = g;
  59439. byteArray[(i * 3) + 2] = b;
  59440. }
  59441. }
  59442. }
  59443. // Fill the array accordingly.
  59444. if (byteArray) {
  59445. results.push(byteArray);
  59446. }
  59447. else {
  59448. results.push(dataFace);
  59449. }
  59450. }
  59451. return results;
  59452. };
  59453. 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);
  59454. };
  59455. /**
  59456. * Occurs when the file is raw .hdr file.
  59457. */
  59458. HDRCubeTexture.prototype.loadHDRTexture = function () {
  59459. var _this = this;
  59460. var callback = function (buffer) {
  59461. // Extract the raw linear data.
  59462. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  59463. // Generate harmonics if needed.
  59464. if (_this._generateHarmonics) {
  59465. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  59466. _this.sphericalPolynomial = sphericalPolynomial;
  59467. }
  59468. var results = [];
  59469. var byteArray = null;
  59470. // Push each faces.
  59471. for (var j = 0; j < 6; j++) {
  59472. // Create uintarray fallback.
  59473. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59474. // 3 channels of 1 bytes per pixel in bytes.
  59475. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  59476. byteArray = new Uint8Array(byteBuffer);
  59477. }
  59478. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  59479. // If special cases.
  59480. if (_this._useInGammaSpace || byteArray) {
  59481. for (var i = 0; i < _this._size * _this._size; i++) {
  59482. // Put in gamma space if requested.
  59483. if (_this._useInGammaSpace) {
  59484. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59485. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59486. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59487. }
  59488. // Convert to int texture for fallback.
  59489. if (byteArray) {
  59490. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59491. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59492. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59493. // May use luminance instead if the result is not accurate.
  59494. var max = Math.max(Math.max(r, g), b);
  59495. if (max > 255) {
  59496. var scale = 255 / max;
  59497. r *= scale;
  59498. g *= scale;
  59499. b *= scale;
  59500. }
  59501. byteArray[(i * 3) + 0] = r;
  59502. byteArray[(i * 3) + 1] = g;
  59503. byteArray[(i * 3) + 2] = b;
  59504. }
  59505. }
  59506. }
  59507. if (byteArray) {
  59508. results.push(byteArray);
  59509. }
  59510. else {
  59511. results.push(dataFace);
  59512. }
  59513. }
  59514. return results;
  59515. };
  59516. var mipmapGenerator = null;
  59517. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  59518. // if (!this._noMipmap &&
  59519. // this._usePMREMGenerator) {
  59520. // mipmapGenerator = (data: ArrayBufferView[]) => {
  59521. // // Custom setup of the generator matching with the PBR shader values.
  59522. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  59523. // this._size,
  59524. // this._size,
  59525. // 0,
  59526. // 3,
  59527. // this.getScene().getEngine().getCaps().textureFloat,
  59528. // 2048,
  59529. // 0.25,
  59530. // false,
  59531. // true);
  59532. // return generator.filterCubeMap();
  59533. // };
  59534. // }
  59535. 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);
  59536. };
  59537. /**
  59538. * Starts the loading process of the texture.
  59539. */
  59540. HDRCubeTexture.prototype.loadTexture = function () {
  59541. if (this._isBABYLONPreprocessed) {
  59542. this.loadBabylonTexture();
  59543. }
  59544. else {
  59545. this.loadHDRTexture();
  59546. }
  59547. };
  59548. HDRCubeTexture.prototype.clone = function () {
  59549. var size = this._isBABYLONPreprocessed ? null : this._size;
  59550. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  59551. // Base texture
  59552. newTexture.level = this.level;
  59553. newTexture.wrapU = this.wrapU;
  59554. newTexture.wrapV = this.wrapV;
  59555. newTexture.coordinatesIndex = this.coordinatesIndex;
  59556. newTexture.coordinatesMode = this.coordinatesMode;
  59557. return newTexture;
  59558. };
  59559. // Methods
  59560. HDRCubeTexture.prototype.delayLoad = function () {
  59561. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59562. return;
  59563. }
  59564. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59565. this._texture = this._getFromCache(this.url, this._noMipmap);
  59566. if (!this._texture) {
  59567. this.loadTexture();
  59568. }
  59569. };
  59570. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  59571. return this._textureMatrix;
  59572. };
  59573. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  59574. this._textureMatrix = value;
  59575. };
  59576. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59577. var texture = null;
  59578. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59579. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  59580. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  59581. texture.name = parsedTexture.name;
  59582. texture.hasAlpha = parsedTexture.hasAlpha;
  59583. texture.level = parsedTexture.level;
  59584. texture.coordinatesMode = parsedTexture.coordinatesMode;
  59585. texture.isBlocking = parsedTexture.isBlocking;
  59586. }
  59587. return texture;
  59588. };
  59589. HDRCubeTexture.prototype.serialize = function () {
  59590. if (!this.name) {
  59591. return null;
  59592. }
  59593. var serializationObject = {};
  59594. serializationObject.name = this.name;
  59595. serializationObject.hasAlpha = this.hasAlpha;
  59596. serializationObject.isCube = true;
  59597. serializationObject.level = this.level;
  59598. serializationObject.size = this._size;
  59599. serializationObject.coordinatesMode = this.coordinatesMode;
  59600. serializationObject.useInGammaSpace = this._useInGammaSpace;
  59601. serializationObject.generateHarmonics = this._generateHarmonics;
  59602. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  59603. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  59604. serializationObject.customType = "BABYLON.HDRCubeTexture";
  59605. serializationObject.noMipmap = this._noMipmap;
  59606. serializationObject.isBlocking = this._isBlocking;
  59607. return serializationObject;
  59608. };
  59609. /**
  59610. * Saves as a file the data contained in the texture in a binary format.
  59611. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59612. * as the spherical used in the lighting.
  59613. * @param url The HDR file url.
  59614. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59615. * @param onError Method called if any error happens during download.
  59616. * @return The packed binary data.
  59617. */
  59618. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  59619. if (onError === void 0) { onError = null; }
  59620. var callback = function (buffer) {
  59621. var data = new Blob([buffer], { type: 'application/octet-stream' });
  59622. // Returns a URL you can use as a href.
  59623. var objUrl = window.URL.createObjectURL(data);
  59624. // Simulates a link to it and click to dowload.
  59625. var a = document.createElement("a");
  59626. document.body.appendChild(a);
  59627. a.style.display = "none";
  59628. a.href = objUrl;
  59629. a.download = "envmap.babylon.hdr";
  59630. a.click();
  59631. };
  59632. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  59633. };
  59634. /**
  59635. * Serializes the data contained in the texture in a binary format.
  59636. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59637. * as the spherical used in the lighting.
  59638. * @param url The HDR file url.
  59639. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59640. * @param onError Method called if any error happens during download.
  59641. * @return The packed binary data.
  59642. */
  59643. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  59644. if (onError === void 0) { onError = null; }
  59645. // Needs the url tho create the texture.
  59646. if (!url) {
  59647. return null;
  59648. }
  59649. // Check Power of two size.
  59650. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  59651. return null;
  59652. }
  59653. // Coming Back in 3.1.
  59654. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  59655. return null;
  59656. };
  59657. HDRCubeTexture._facesMapping = [
  59658. "right",
  59659. "left",
  59660. "up",
  59661. "down",
  59662. "front",
  59663. "back"
  59664. ];
  59665. return HDRCubeTexture;
  59666. }(BABYLON.BaseTexture));
  59667. BABYLON.HDRCubeTexture = HDRCubeTexture;
  59668. })(BABYLON || (BABYLON = {}));
  59669. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  59670. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  59671. // Huge respect for a such great lib.
  59672. // Earcut license:
  59673. // Copyright (c) 2016, Mapbox
  59674. //
  59675. // Permission to use, copy, modify, and/or distribute this software for any purpose
  59676. // with or without fee is hereby granted, provided that the above copyright notice
  59677. // and this permission notice appear in all copies.
  59678. //
  59679. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  59680. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  59681. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  59682. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  59683. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  59684. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  59685. // THIS SOFTWARE.
  59686. var Earcut;
  59687. (function (Earcut) {
  59688. /**
  59689. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  59690. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  59691. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  59692. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  59693. */
  59694. function earcut(data, holeIndices, dim) {
  59695. dim = dim || 2;
  59696. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  59697. if (!outerNode)
  59698. return triangles;
  59699. var minX, minY, maxX, maxY, x, y, size;
  59700. if (hasHoles)
  59701. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  59702. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  59703. if (data.length > 80 * dim) {
  59704. minX = maxX = data[0];
  59705. minY = maxY = data[1];
  59706. for (var i = dim; i < outerLen; i += dim) {
  59707. x = data[i];
  59708. y = data[i + 1];
  59709. if (x < minX)
  59710. minX = x;
  59711. if (y < minY)
  59712. minY = y;
  59713. if (x > maxX)
  59714. maxX = x;
  59715. if (y > maxY)
  59716. maxY = y;
  59717. }
  59718. // minX, minY and size are later used to transform coords into integers for z-order calculation
  59719. size = Math.max(maxX - minX, maxY - minY);
  59720. }
  59721. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  59722. return triangles;
  59723. }
  59724. Earcut.earcut = earcut;
  59725. // create a circular doubly linked list from polygon points in the specified winding order
  59726. function linkedList(data, start, end, dim, clockwise) {
  59727. var i, last;
  59728. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  59729. for (i = start; i < end; i += dim)
  59730. last = insertNode(i, data[i], data[i + 1], last);
  59731. }
  59732. else {
  59733. for (i = end - dim; i >= start; i -= dim)
  59734. last = insertNode(i, data[i], data[i + 1], last);
  59735. }
  59736. if (last && equals(last, last.next)) {
  59737. removeNode(last);
  59738. last = last.next;
  59739. }
  59740. return last;
  59741. }
  59742. // eliminate colinear or duplicate points
  59743. function filterPoints(start, end) {
  59744. if (!start)
  59745. return start;
  59746. if (!end)
  59747. end = start;
  59748. var p = start, again;
  59749. do {
  59750. again = false;
  59751. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  59752. removeNode(p);
  59753. p = end = p.prev;
  59754. if (p === p.next)
  59755. return null;
  59756. again = true;
  59757. }
  59758. else {
  59759. p = p.next;
  59760. }
  59761. } while (again || p !== end);
  59762. return end;
  59763. }
  59764. // main ear slicing loop which triangulates a polygon (given as a linked list)
  59765. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  59766. if (!ear)
  59767. return;
  59768. // interlink polygon nodes in z-order
  59769. if (!pass && size)
  59770. indexCurve(ear, minX, minY, size);
  59771. var stop = ear, prev, next;
  59772. // iterate through ears, slicing them one by one
  59773. while (ear.prev !== ear.next) {
  59774. prev = ear.prev;
  59775. next = ear.next;
  59776. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  59777. // cut off the triangle
  59778. triangles.push(prev.i / dim);
  59779. triangles.push(ear.i / dim);
  59780. triangles.push(next.i / dim);
  59781. removeNode(ear);
  59782. // skipping the next vertice leads to less sliver triangles
  59783. ear = next.next;
  59784. stop = next.next;
  59785. continue;
  59786. }
  59787. ear = next;
  59788. // if we looped through the whole remaining polygon and can't find any more ears
  59789. if (ear === stop) {
  59790. // try filtering points and slicing again
  59791. if (!pass) {
  59792. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  59793. // if this didn't work, try curing all small self-intersections locally
  59794. }
  59795. else if (pass === 1) {
  59796. ear = cureLocalIntersections(ear, triangles, dim);
  59797. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  59798. // as a last resort, try splitting the remaining polygon into two
  59799. }
  59800. else if (pass === 2) {
  59801. splitEarcut(ear, triangles, dim, minX, minY, size);
  59802. }
  59803. break;
  59804. }
  59805. }
  59806. }
  59807. // check whether a polygon node forms a valid ear with adjacent nodes
  59808. function isEar(ear) {
  59809. var a = ear.prev, b = ear, c = ear.next;
  59810. if (area(a, b, c) >= 0)
  59811. return false; // reflex, can't be an ear
  59812. // now make sure we don't have other points inside the potential ear
  59813. var p = ear.next.next;
  59814. while (p !== ear.prev) {
  59815. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59816. area(p.prev, p, p.next) >= 0)
  59817. return false;
  59818. p = p.next;
  59819. }
  59820. return true;
  59821. }
  59822. function isEarHashed(ear, minX, minY, size) {
  59823. var a = ear.prev, b = ear, c = ear.next;
  59824. if (area(a, b, c) >= 0)
  59825. return false; // reflex, can't be an ear
  59826. // triangle bbox; min & max are calculated like this for speed
  59827. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  59828. // z-order range for the current triangle bbox;
  59829. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  59830. // first look for points inside the triangle in increasing z-order
  59831. var p = ear.nextZ;
  59832. while (p && p.z <= maxZ) {
  59833. if (p !== ear.prev &&
  59834. p !== ear.next &&
  59835. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59836. area(p.prev, p, p.next) >= 0)
  59837. return false;
  59838. p = p.nextZ;
  59839. }
  59840. // then look for points in decreasing z-order
  59841. p = ear.prevZ;
  59842. while (p && p.z >= minZ) {
  59843. if (p !== ear.prev &&
  59844. p !== ear.next &&
  59845. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59846. area(p.prev, p, p.next) >= 0)
  59847. return false;
  59848. p = p.prevZ;
  59849. }
  59850. return true;
  59851. }
  59852. // go through all polygon nodes and cure small local self-intersections
  59853. function cureLocalIntersections(start, triangles, dim) {
  59854. var p = start;
  59855. do {
  59856. var a = p.prev, b = p.next.next;
  59857. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  59858. triangles.push(a.i / dim);
  59859. triangles.push(p.i / dim);
  59860. triangles.push(b.i / dim);
  59861. // remove two nodes involved
  59862. removeNode(p);
  59863. removeNode(p.next);
  59864. p = start = b;
  59865. }
  59866. p = p.next;
  59867. } while (p !== start);
  59868. return p;
  59869. }
  59870. // try splitting polygon into two and triangulate them independently
  59871. function splitEarcut(start, triangles, dim, minX, minY, size) {
  59872. // look for a valid diagonal that divides the polygon into two
  59873. var a = start;
  59874. do {
  59875. var b = a.next.next;
  59876. while (b !== a.prev) {
  59877. if (a.i !== b.i && isValidDiagonal(a, b)) {
  59878. // split the polygon in two by the diagonal
  59879. var c = splitPolygon(a, b);
  59880. // filter colinear points around the cuts
  59881. a = filterPoints(a, a.next);
  59882. c = filterPoints(c, c.next);
  59883. // run earcut on each half
  59884. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  59885. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  59886. return;
  59887. }
  59888. b = b.next;
  59889. }
  59890. a = a.next;
  59891. } while (a !== start);
  59892. }
  59893. // link every hole into the outer loop, producing a single-ring polygon without holes
  59894. function eliminateHoles(data, holeIndices, outerNode, dim) {
  59895. var queue = [], i, len, start, end, list;
  59896. for (i = 0, len = holeIndices.length; i < len; i++) {
  59897. start = holeIndices[i] * dim;
  59898. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  59899. list = linkedList(data, start, end, dim, false);
  59900. if (list === list.next)
  59901. list.steiner = true;
  59902. queue.push(getLeftmost(list));
  59903. }
  59904. queue.sort(compareX);
  59905. // process holes from left to right
  59906. for (i = 0; i < queue.length; i++) {
  59907. eliminateHole(queue[i], outerNode);
  59908. outerNode = filterPoints(outerNode, outerNode.next);
  59909. }
  59910. return outerNode;
  59911. }
  59912. function compareX(a, b) {
  59913. return a.x - b.x;
  59914. }
  59915. // find a bridge between vertices that connects hole with an outer ring and and link it
  59916. function eliminateHole(hole, outerNode) {
  59917. outerNode = findHoleBridge(hole, outerNode);
  59918. if (outerNode) {
  59919. var b = splitPolygon(outerNode, hole);
  59920. filterPoints(b, b.next);
  59921. }
  59922. }
  59923. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  59924. function findHoleBridge(hole, outerNode) {
  59925. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  59926. // find a segment intersected by a ray from the hole's leftmost point to the left;
  59927. // segment's endpoint with lesser x will be potential connection point
  59928. do {
  59929. if (hy <= p.y && hy >= p.next.y) {
  59930. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  59931. if (x <= hx && x > qx) {
  59932. qx = x;
  59933. if (x === hx) {
  59934. if (hy === p.y)
  59935. return p;
  59936. if (hy === p.next.y)
  59937. return p.next;
  59938. }
  59939. m = p.x < p.next.x ? p : p.next;
  59940. }
  59941. }
  59942. p = p.next;
  59943. } while (p !== outerNode);
  59944. if (!m)
  59945. return null;
  59946. if (hx === qx)
  59947. return m.prev; // hole touches outer segment; pick lower endpoint
  59948. // look for points inside the triangle of hole point, segment intersection and endpoint;
  59949. // if there are no points found, we have a valid connection;
  59950. // otherwise choose the point of the minimum angle with the ray as connection point
  59951. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  59952. p = m.next;
  59953. while (p !== stop) {
  59954. if (hx >= p.x &&
  59955. p.x >= mx &&
  59956. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  59957. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  59958. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  59959. m = p;
  59960. tanMin = tan;
  59961. }
  59962. }
  59963. p = p.next;
  59964. }
  59965. return m;
  59966. }
  59967. // interlink polygon nodes in z-order
  59968. function indexCurve(start, minX, minY, size) {
  59969. var p = start;
  59970. do {
  59971. if (p.z === null)
  59972. p.z = zOrder(p.x, p.y, minX, minY, size);
  59973. p.prevZ = p.prev;
  59974. p.nextZ = p.next;
  59975. p = p.next;
  59976. } while (p !== start);
  59977. p.prevZ.nextZ = null;
  59978. p.prevZ = null;
  59979. sortLinked(p);
  59980. }
  59981. // Simon Tatham's linked list merge sort algorithm
  59982. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  59983. function sortLinked(list) {
  59984. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  59985. do {
  59986. p = list;
  59987. list = null;
  59988. tail = null;
  59989. numMerges = 0;
  59990. while (p) {
  59991. numMerges++;
  59992. q = p;
  59993. pSize = 0;
  59994. for (i = 0; i < inSize; i++) {
  59995. pSize++;
  59996. q = q.nextZ;
  59997. if (!q)
  59998. break;
  59999. }
  60000. qSize = inSize;
  60001. while (pSize > 0 || (qSize > 0 && q)) {
  60002. if (pSize === 0) {
  60003. e = q;
  60004. q = q.nextZ;
  60005. qSize--;
  60006. }
  60007. else if (qSize === 0 || !q) {
  60008. e = p;
  60009. p = p.nextZ;
  60010. pSize--;
  60011. }
  60012. else if (p.z <= q.z) {
  60013. e = p;
  60014. p = p.nextZ;
  60015. pSize--;
  60016. }
  60017. else {
  60018. e = q;
  60019. q = q.nextZ;
  60020. qSize--;
  60021. }
  60022. if (tail)
  60023. tail.nextZ = e;
  60024. else
  60025. list = e;
  60026. e.prevZ = tail;
  60027. tail = e;
  60028. }
  60029. p = q;
  60030. }
  60031. tail.nextZ = null;
  60032. inSize *= 2;
  60033. } while (numMerges > 1);
  60034. return list;
  60035. }
  60036. // z-order of a point given coords and size of the data bounding box
  60037. function zOrder(x, y, minX, minY, size) {
  60038. // coords are transformed into non-negative 15-bit integer range
  60039. x = 32767 * (x - minX) / size;
  60040. y = 32767 * (y - minY) / size;
  60041. x = (x | (x << 8)) & 0x00FF00FF;
  60042. x = (x | (x << 4)) & 0x0F0F0F0F;
  60043. x = (x | (x << 2)) & 0x33333333;
  60044. x = (x | (x << 1)) & 0x55555555;
  60045. y = (y | (y << 8)) & 0x00FF00FF;
  60046. y = (y | (y << 4)) & 0x0F0F0F0F;
  60047. y = (y | (y << 2)) & 0x33333333;
  60048. y = (y | (y << 1)) & 0x55555555;
  60049. return x | (y << 1);
  60050. }
  60051. // find the leftmost node of a polygon ring
  60052. function getLeftmost(start) {
  60053. var p = start, leftmost = start;
  60054. do {
  60055. if (p.x < leftmost.x)
  60056. leftmost = p;
  60057. p = p.next;
  60058. } while (p !== start);
  60059. return leftmost;
  60060. }
  60061. // check if a point lies within a convex triangle
  60062. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  60063. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  60064. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  60065. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  60066. }
  60067. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  60068. function isValidDiagonal(a, b) {
  60069. return a.next.i !== b.i &&
  60070. a.prev.i !== b.i &&
  60071. !intersectsPolygon(a, b) &&
  60072. locallyInside(a, b) &&
  60073. locallyInside(b, a) &&
  60074. middleInside(a, b);
  60075. }
  60076. // signed area of a triangle
  60077. function area(p, q, r) {
  60078. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  60079. }
  60080. // check if two points are equal
  60081. function equals(p1, p2) {
  60082. return p1.x === p2.x && p1.y === p2.y;
  60083. }
  60084. // check if two segments intersect
  60085. function intersects(p1, q1, p2, q2) {
  60086. if ((equals(p1, q1) && equals(p2, q2)) ||
  60087. (equals(p1, q2) && equals(p2, q1)))
  60088. return true;
  60089. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  60090. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  60091. }
  60092. // check if a polygon diagonal intersects any polygon segments
  60093. function intersectsPolygon(a, b) {
  60094. var p = a;
  60095. do {
  60096. if (p.i !== a.i &&
  60097. p.next.i !== a.i &&
  60098. p.i !== b.i &&
  60099. p.next.i !== b.i &&
  60100. intersects(p, p.next, a, b))
  60101. return true;
  60102. p = p.next;
  60103. } while (p !== a);
  60104. return false;
  60105. }
  60106. // check if a polygon diagonal is locally inside the polygon
  60107. function locallyInside(a, b) {
  60108. return area(a.prev, a, a.next) < 0
  60109. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  60110. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  60111. }
  60112. // check if the middle point of a polygon diagonal is inside the polygon
  60113. function middleInside(a, b) {
  60114. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  60115. do {
  60116. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  60117. inside = !inside;
  60118. p = p.next;
  60119. } while (p !== a);
  60120. return inside;
  60121. }
  60122. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  60123. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  60124. function splitPolygon(a, b) {
  60125. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  60126. a.next = b;
  60127. b.prev = a;
  60128. a2.next = an;
  60129. an.prev = a2;
  60130. b2.next = a2;
  60131. a2.prev = b2;
  60132. bp.next = b2;
  60133. b2.prev = bp;
  60134. return b2;
  60135. }
  60136. // create a node and optionally link it with previous one (in a circular doubly linked list)
  60137. function insertNode(i, x, y, last) {
  60138. var p = new Node(i, x, y);
  60139. if (!last) {
  60140. p.prev = p;
  60141. p.next = p;
  60142. }
  60143. else {
  60144. p.next = last.next;
  60145. p.prev = last;
  60146. last.next.prev = p;
  60147. last.next = p;
  60148. }
  60149. return p;
  60150. }
  60151. function removeNode(p) {
  60152. p.next.prev = p.prev;
  60153. p.prev.next = p.next;
  60154. if (p.prevZ)
  60155. p.prevZ.nextZ = p.nextZ;
  60156. if (p.nextZ)
  60157. p.nextZ.prevZ = p.prevZ;
  60158. }
  60159. function Node(i, x, y) {
  60160. // vertice index in coordinates array
  60161. this.i = i;
  60162. // vertex coordinates
  60163. this.x = x;
  60164. this.y = y;
  60165. // previous and next vertice nodes in a polygon ring
  60166. this.prev = null;
  60167. this.next = null;
  60168. // z-order curve value
  60169. this.z = null;
  60170. // previous and next nodes in z-order
  60171. this.prevZ = null;
  60172. this.nextZ = null;
  60173. // indicates whether this is a steiner point
  60174. this.steiner = false;
  60175. }
  60176. /**
  60177. * return a percentage difference between the polygon area and its triangulation area;
  60178. * used to verify correctness of triangulation
  60179. */
  60180. function deviation(data, holeIndices, dim, triangles) {
  60181. var hasHoles = holeIndices && holeIndices.length;
  60182. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  60183. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  60184. if (hasHoles) {
  60185. for (var i = 0, len = holeIndices.length; i < len; i++) {
  60186. var start = holeIndices[i] * dim;
  60187. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  60188. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  60189. }
  60190. }
  60191. var trianglesArea = 0;
  60192. for (i = 0; i < triangles.length; i += 3) {
  60193. var a = triangles[i] * dim;
  60194. var b = triangles[i + 1] * dim;
  60195. var c = triangles[i + 2] * dim;
  60196. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  60197. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  60198. }
  60199. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  60200. }
  60201. Earcut.deviation = deviation;
  60202. ;
  60203. function signedArea(data, start, end, dim) {
  60204. var sum = 0;
  60205. for (var i = start, j = end - dim; i < end; i += dim) {
  60206. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  60207. j = i;
  60208. }
  60209. return sum;
  60210. }
  60211. /**
  60212. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  60213. */
  60214. function flatten(data) {
  60215. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  60216. for (var i = 0; i < data.length; i++) {
  60217. for (var j = 0; j < data[i].length; j++) {
  60218. for (var d = 0; d < dim; d++)
  60219. result.vertices.push(data[i][j][d]);
  60220. }
  60221. if (i > 0) {
  60222. holeIndex += data[i - 1].length;
  60223. result.holes.push(holeIndex);
  60224. }
  60225. }
  60226. return result;
  60227. }
  60228. Earcut.flatten = flatten;
  60229. ;
  60230. })(Earcut || (Earcut = {}));
  60231. //# sourceMappingURL=babylon.earcut.js.map
  60232. /// <reference path="..\Math\babylon.math.ts" />
  60233. var BABYLON;
  60234. (function (BABYLON) {
  60235. var IndexedVector2 = (function (_super) {
  60236. __extends(IndexedVector2, _super);
  60237. function IndexedVector2(original, index) {
  60238. var _this = _super.call(this, original.x, original.y) || this;
  60239. _this.index = index;
  60240. return _this;
  60241. }
  60242. return IndexedVector2;
  60243. }(BABYLON.Vector2));
  60244. var PolygonPoints = (function () {
  60245. function PolygonPoints() {
  60246. this.elements = new Array();
  60247. }
  60248. PolygonPoints.prototype.add = function (originalPoints) {
  60249. var _this = this;
  60250. var result = new Array();
  60251. originalPoints.forEach(function (point) {
  60252. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  60253. var newPoint = new IndexedVector2(point, _this.elements.length);
  60254. result.push(newPoint);
  60255. _this.elements.push(newPoint);
  60256. }
  60257. });
  60258. return result;
  60259. };
  60260. PolygonPoints.prototype.computeBounds = function () {
  60261. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  60262. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  60263. this.elements.forEach(function (point) {
  60264. // x
  60265. if (point.x < lmin.x) {
  60266. lmin.x = point.x;
  60267. }
  60268. else if (point.x > lmax.x) {
  60269. lmax.x = point.x;
  60270. }
  60271. // y
  60272. if (point.y < lmin.y) {
  60273. lmin.y = point.y;
  60274. }
  60275. else if (point.y > lmax.y) {
  60276. lmax.y = point.y;
  60277. }
  60278. });
  60279. return {
  60280. min: lmin,
  60281. max: lmax,
  60282. width: lmax.x - lmin.x,
  60283. height: lmax.y - lmin.y
  60284. };
  60285. };
  60286. return PolygonPoints;
  60287. }());
  60288. var Polygon = (function () {
  60289. function Polygon() {
  60290. }
  60291. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  60292. return [
  60293. new BABYLON.Vector2(xmin, ymin),
  60294. new BABYLON.Vector2(xmax, ymin),
  60295. new BABYLON.Vector2(xmax, ymax),
  60296. new BABYLON.Vector2(xmin, ymax)
  60297. ];
  60298. };
  60299. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  60300. if (cx === void 0) { cx = 0; }
  60301. if (cy === void 0) { cy = 0; }
  60302. if (numberOfSides === void 0) { numberOfSides = 32; }
  60303. var result = new Array();
  60304. var angle = 0;
  60305. var increment = (Math.PI * 2) / numberOfSides;
  60306. for (var i = 0; i < numberOfSides; i++) {
  60307. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  60308. angle -= increment;
  60309. }
  60310. return result;
  60311. };
  60312. Polygon.Parse = function (input) {
  60313. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  60314. var i, result = [];
  60315. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  60316. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  60317. }
  60318. return result;
  60319. };
  60320. Polygon.StartingAt = function (x, y) {
  60321. return BABYLON.Path2.StartingAt(x, y);
  60322. };
  60323. return Polygon;
  60324. }());
  60325. BABYLON.Polygon = Polygon;
  60326. var PolygonMeshBuilder = (function () {
  60327. function PolygonMeshBuilder(name, contours, scene) {
  60328. this._points = new PolygonPoints();
  60329. this._outlinepoints = new PolygonPoints();
  60330. this._holes = [];
  60331. this._epoints = new Array();
  60332. this._eholes = new Array();
  60333. this._name = name;
  60334. this._scene = scene;
  60335. var points;
  60336. if (contours instanceof BABYLON.Path2) {
  60337. points = contours.getPoints();
  60338. }
  60339. else {
  60340. points = contours;
  60341. }
  60342. this._addToepoint(points);
  60343. this._points.add(points);
  60344. this._outlinepoints.add(points);
  60345. }
  60346. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  60347. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  60348. var p = points_1[_i];
  60349. this._epoints.push(p.x, p.y);
  60350. }
  60351. };
  60352. PolygonMeshBuilder.prototype.addHole = function (hole) {
  60353. this._points.add(hole);
  60354. var holepoints = new PolygonPoints();
  60355. holepoints.add(hole);
  60356. this._holes.push(holepoints);
  60357. this._eholes.push(this._epoints.length / 2);
  60358. this._addToepoint(hole);
  60359. return this;
  60360. };
  60361. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  60362. var _this = this;
  60363. if (updatable === void 0) { updatable = false; }
  60364. var result = new BABYLON.Mesh(this._name, this._scene);
  60365. var normals = [];
  60366. var positions = [];
  60367. var uvs = [];
  60368. var bounds = this._points.computeBounds();
  60369. this._points.elements.forEach(function (p) {
  60370. normals.push(0, 1.0, 0);
  60371. positions.push(p.x, 0, p.y);
  60372. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  60373. });
  60374. var indices = [];
  60375. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  60376. for (var i = 0; i < res.length; i++) {
  60377. indices.push(res[i]);
  60378. }
  60379. if (depth > 0) {
  60380. var positionscount = (positions.length / 3); //get the current pointcount
  60381. this._points.elements.forEach(function (p) {
  60382. normals.push(0, -1.0, 0);
  60383. positions.push(p.x, -depth, p.y);
  60384. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  60385. });
  60386. var totalCount = indices.length;
  60387. for (var i = 0; i < totalCount; i += 3) {
  60388. var i0 = indices[i + 0];
  60389. var i1 = indices[i + 1];
  60390. var i2 = indices[i + 2];
  60391. indices.push(i2 + positionscount);
  60392. indices.push(i1 + positionscount);
  60393. indices.push(i0 + positionscount);
  60394. }
  60395. //Add the sides
  60396. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  60397. this._holes.forEach(function (hole) {
  60398. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  60399. });
  60400. }
  60401. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  60402. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  60403. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  60404. result.setIndices(indices);
  60405. return result;
  60406. };
  60407. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  60408. var StartIndex = positions.length / 3;
  60409. var ulength = 0;
  60410. for (var i = 0; i < points.elements.length; i++) {
  60411. var p = points.elements[i];
  60412. var p1;
  60413. if ((i + 1) > points.elements.length - 1) {
  60414. p1 = points.elements[0];
  60415. }
  60416. else {
  60417. p1 = points.elements[i + 1];
  60418. }
  60419. positions.push(p.x, 0, p.y);
  60420. positions.push(p.x, -depth, p.y);
  60421. positions.push(p1.x, 0, p1.y);
  60422. positions.push(p1.x, -depth, p1.y);
  60423. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  60424. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  60425. var v3 = v2.subtract(v1);
  60426. var v4 = new BABYLON.Vector3(0, 1, 0);
  60427. var vn = BABYLON.Vector3.Cross(v3, v4);
  60428. vn = vn.normalize();
  60429. uvs.push(ulength / bounds.width, 0);
  60430. uvs.push(ulength / bounds.width, 1);
  60431. ulength += v3.length();
  60432. uvs.push((ulength / bounds.width), 0);
  60433. uvs.push((ulength / bounds.width), 1);
  60434. if (!flip) {
  60435. normals.push(-vn.x, -vn.y, -vn.z);
  60436. normals.push(-vn.x, -vn.y, -vn.z);
  60437. normals.push(-vn.x, -vn.y, -vn.z);
  60438. normals.push(-vn.x, -vn.y, -vn.z);
  60439. indices.push(StartIndex);
  60440. indices.push(StartIndex + 1);
  60441. indices.push(StartIndex + 2);
  60442. indices.push(StartIndex + 1);
  60443. indices.push(StartIndex + 3);
  60444. indices.push(StartIndex + 2);
  60445. }
  60446. else {
  60447. normals.push(vn.x, vn.y, vn.z);
  60448. normals.push(vn.x, vn.y, vn.z);
  60449. normals.push(vn.x, vn.y, vn.z);
  60450. normals.push(vn.x, vn.y, vn.z);
  60451. indices.push(StartIndex);
  60452. indices.push(StartIndex + 2);
  60453. indices.push(StartIndex + 1);
  60454. indices.push(StartIndex + 1);
  60455. indices.push(StartIndex + 2);
  60456. indices.push(StartIndex + 3);
  60457. }
  60458. StartIndex += 4;
  60459. }
  60460. ;
  60461. };
  60462. return PolygonMeshBuilder;
  60463. }());
  60464. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  60465. })(BABYLON || (BABYLON = {}));
  60466. //# sourceMappingURL=babylon.polygonMesh.js.map
  60467. var BABYLON;
  60468. (function (BABYLON) {
  60469. // Unique ID when we import meshes from Babylon to CSG
  60470. var currentCSGMeshId = 0;
  60471. // # class Vertex
  60472. // Represents a vertex of a polygon. Use your own vertex class instead of this
  60473. // one to provide additional features like texture coordinates and vertex
  60474. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  60475. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  60476. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  60477. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  60478. // is not used anywhere else.
  60479. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  60480. var Vertex = (function () {
  60481. function Vertex(pos, normal, uv) {
  60482. this.pos = pos;
  60483. this.normal = normal;
  60484. this.uv = uv;
  60485. }
  60486. Vertex.prototype.clone = function () {
  60487. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  60488. };
  60489. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  60490. // orientation of a polygon is flipped.
  60491. Vertex.prototype.flip = function () {
  60492. this.normal = this.normal.scale(-1);
  60493. };
  60494. // Create a new vertex between this vertex and `other` by linearly
  60495. // interpolating all properties using a parameter of `t`. Subclasses should
  60496. // override this to interpolate additional properties.
  60497. Vertex.prototype.interpolate = function (other, t) {
  60498. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  60499. };
  60500. return Vertex;
  60501. }());
  60502. // # class Plane
  60503. // Represents a plane in 3D space.
  60504. var Plane = (function () {
  60505. function Plane(normal, w) {
  60506. this.normal = normal;
  60507. this.w = w;
  60508. }
  60509. Plane.FromPoints = function (a, b, c) {
  60510. var v0 = c.subtract(a);
  60511. var v1 = b.subtract(a);
  60512. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  60513. return null;
  60514. }
  60515. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  60516. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  60517. };
  60518. Plane.prototype.clone = function () {
  60519. return new Plane(this.normal.clone(), this.w);
  60520. };
  60521. Plane.prototype.flip = function () {
  60522. this.normal.scaleInPlace(-1);
  60523. this.w = -this.w;
  60524. };
  60525. // Split `polygon` by this plane if needed, then put the polygon or polygon
  60526. // fragments in the appropriate lists. Coplanar polygons go into either
  60527. // `coplanarFront` or `coplanarBack` depending on their orientation with
  60528. // respect to this plane. Polygons in front or in back of this plane go into
  60529. // either `front` or `back`.
  60530. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  60531. var COPLANAR = 0;
  60532. var FRONT = 1;
  60533. var BACK = 2;
  60534. var SPANNING = 3;
  60535. // Classify each point as well as the entire polygon into one of the above
  60536. // four classes.
  60537. var polygonType = 0;
  60538. var types = [];
  60539. var i;
  60540. var t;
  60541. for (i = 0; i < polygon.vertices.length; i++) {
  60542. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  60543. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  60544. polygonType |= type;
  60545. types.push(type);
  60546. }
  60547. // Put the polygon in the correct list, splitting it when necessary.
  60548. switch (polygonType) {
  60549. case COPLANAR:
  60550. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  60551. break;
  60552. case FRONT:
  60553. front.push(polygon);
  60554. break;
  60555. case BACK:
  60556. back.push(polygon);
  60557. break;
  60558. case SPANNING:
  60559. var f = [], b = [];
  60560. for (i = 0; i < polygon.vertices.length; i++) {
  60561. var j = (i + 1) % polygon.vertices.length;
  60562. var ti = types[i], tj = types[j];
  60563. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  60564. if (ti !== BACK)
  60565. f.push(vi);
  60566. if (ti !== FRONT)
  60567. b.push(ti !== BACK ? vi.clone() : vi);
  60568. if ((ti | tj) === SPANNING) {
  60569. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  60570. var v = vi.interpolate(vj, t);
  60571. f.push(v);
  60572. b.push(v.clone());
  60573. }
  60574. }
  60575. var poly;
  60576. if (f.length >= 3) {
  60577. poly = new Polygon(f, polygon.shared);
  60578. if (poly.plane)
  60579. front.push(poly);
  60580. }
  60581. if (b.length >= 3) {
  60582. poly = new Polygon(b, polygon.shared);
  60583. if (poly.plane)
  60584. back.push(poly);
  60585. }
  60586. break;
  60587. }
  60588. };
  60589. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  60590. // point is on the plane.
  60591. Plane.EPSILON = 1e-5;
  60592. return Plane;
  60593. }());
  60594. // # class Polygon
  60595. // Represents a convex polygon. The vertices used to initialize a polygon must
  60596. // be coplanar and form a convex loop.
  60597. //
  60598. // Each convex polygon has a `shared` property, which is shared between all
  60599. // polygons that are clones of each other or were split from the same polygon.
  60600. // This can be used to define per-polygon properties (such as surface color).
  60601. var Polygon = (function () {
  60602. function Polygon(vertices, shared) {
  60603. this.vertices = vertices;
  60604. this.shared = shared;
  60605. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  60606. }
  60607. Polygon.prototype.clone = function () {
  60608. var vertices = this.vertices.map(function (v) { return v.clone(); });
  60609. return new Polygon(vertices, this.shared);
  60610. };
  60611. Polygon.prototype.flip = function () {
  60612. this.vertices.reverse().map(function (v) { v.flip(); });
  60613. this.plane.flip();
  60614. };
  60615. return Polygon;
  60616. }());
  60617. // # class Node
  60618. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  60619. // by picking a polygon to split along. That polygon (and all other coplanar
  60620. // polygons) are added directly to that node and the other polygons are added to
  60621. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  60622. // no distinction between internal and leaf nodes.
  60623. var Node = (function () {
  60624. function Node(polygons) {
  60625. this.plane = null;
  60626. this.front = null;
  60627. this.back = null;
  60628. this.polygons = [];
  60629. if (polygons) {
  60630. this.build(polygons);
  60631. }
  60632. }
  60633. Node.prototype.clone = function () {
  60634. var node = new Node();
  60635. node.plane = this.plane && this.plane.clone();
  60636. node.front = this.front && this.front.clone();
  60637. node.back = this.back && this.back.clone();
  60638. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  60639. return node;
  60640. };
  60641. // Convert solid space to empty space and empty space to solid space.
  60642. Node.prototype.invert = function () {
  60643. for (var i = 0; i < this.polygons.length; i++) {
  60644. this.polygons[i].flip();
  60645. }
  60646. if (this.plane) {
  60647. this.plane.flip();
  60648. }
  60649. if (this.front) {
  60650. this.front.invert();
  60651. }
  60652. if (this.back) {
  60653. this.back.invert();
  60654. }
  60655. var temp = this.front;
  60656. this.front = this.back;
  60657. this.back = temp;
  60658. };
  60659. // Recursively remove all polygons in `polygons` that are inside this BSP
  60660. // tree.
  60661. Node.prototype.clipPolygons = function (polygons) {
  60662. if (!this.plane)
  60663. return polygons.slice();
  60664. var front = [], back = [];
  60665. for (var i = 0; i < polygons.length; i++) {
  60666. this.plane.splitPolygon(polygons[i], front, back, front, back);
  60667. }
  60668. if (this.front) {
  60669. front = this.front.clipPolygons(front);
  60670. }
  60671. if (this.back) {
  60672. back = this.back.clipPolygons(back);
  60673. }
  60674. else {
  60675. back = [];
  60676. }
  60677. return front.concat(back);
  60678. };
  60679. // Remove all polygons in this BSP tree that are inside the other BSP tree
  60680. // `bsp`.
  60681. Node.prototype.clipTo = function (bsp) {
  60682. this.polygons = bsp.clipPolygons(this.polygons);
  60683. if (this.front)
  60684. this.front.clipTo(bsp);
  60685. if (this.back)
  60686. this.back.clipTo(bsp);
  60687. };
  60688. // Return a list of all polygons in this BSP tree.
  60689. Node.prototype.allPolygons = function () {
  60690. var polygons = this.polygons.slice();
  60691. if (this.front)
  60692. polygons = polygons.concat(this.front.allPolygons());
  60693. if (this.back)
  60694. polygons = polygons.concat(this.back.allPolygons());
  60695. return polygons;
  60696. };
  60697. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  60698. // new polygons are filtered down to the bottom of the tree and become new
  60699. // nodes there. Each set of polygons is partitioned using the first polygon
  60700. // (no heuristic is used to pick a good split).
  60701. Node.prototype.build = function (polygons) {
  60702. if (!polygons.length)
  60703. return;
  60704. if (!this.plane)
  60705. this.plane = polygons[0].plane.clone();
  60706. var front = [], back = [];
  60707. for (var i = 0; i < polygons.length; i++) {
  60708. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  60709. }
  60710. if (front.length) {
  60711. if (!this.front)
  60712. this.front = new Node();
  60713. this.front.build(front);
  60714. }
  60715. if (back.length) {
  60716. if (!this.back)
  60717. this.back = new Node();
  60718. this.back.build(back);
  60719. }
  60720. };
  60721. return Node;
  60722. }());
  60723. var CSG = (function () {
  60724. function CSG() {
  60725. this.polygons = new Array();
  60726. }
  60727. // Convert BABYLON.Mesh to BABYLON.CSG
  60728. CSG.FromMesh = function (mesh) {
  60729. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  60730. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  60731. if (mesh instanceof BABYLON.Mesh) {
  60732. mesh.computeWorldMatrix(true);
  60733. matrix = mesh.getWorldMatrix();
  60734. meshPosition = mesh.position.clone();
  60735. meshRotation = mesh.rotation.clone();
  60736. if (mesh.rotationQuaternion) {
  60737. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  60738. }
  60739. meshScaling = mesh.scaling.clone();
  60740. }
  60741. else {
  60742. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  60743. }
  60744. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60745. var subMeshes = mesh.subMeshes;
  60746. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  60747. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  60748. vertices = [];
  60749. for (var j = 0; j < 3; j++) {
  60750. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  60751. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  60752. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  60753. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  60754. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  60755. vertex = new Vertex(position, normal, uv);
  60756. vertices.push(vertex);
  60757. }
  60758. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  60759. // To handle the case of degenerated triangle
  60760. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  60761. if (polygon.plane)
  60762. polygons.push(polygon);
  60763. }
  60764. }
  60765. var csg = CSG.FromPolygons(polygons);
  60766. csg.matrix = matrix;
  60767. csg.position = meshPosition;
  60768. csg.rotation = meshRotation;
  60769. csg.scaling = meshScaling;
  60770. csg.rotationQuaternion = meshRotationQuaternion;
  60771. currentCSGMeshId++;
  60772. return csg;
  60773. };
  60774. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  60775. CSG.FromPolygons = function (polygons) {
  60776. var csg = new CSG();
  60777. csg.polygons = polygons;
  60778. return csg;
  60779. };
  60780. CSG.prototype.clone = function () {
  60781. var csg = new CSG();
  60782. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  60783. csg.copyTransformAttributes(this);
  60784. return csg;
  60785. };
  60786. CSG.prototype.toPolygons = function () {
  60787. return this.polygons;
  60788. };
  60789. CSG.prototype.union = function (csg) {
  60790. var a = new Node(this.clone().polygons);
  60791. var b = new Node(csg.clone().polygons);
  60792. a.clipTo(b);
  60793. b.clipTo(a);
  60794. b.invert();
  60795. b.clipTo(a);
  60796. b.invert();
  60797. a.build(b.allPolygons());
  60798. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60799. };
  60800. CSG.prototype.unionInPlace = function (csg) {
  60801. var a = new Node(this.polygons);
  60802. var b = new Node(csg.polygons);
  60803. a.clipTo(b);
  60804. b.clipTo(a);
  60805. b.invert();
  60806. b.clipTo(a);
  60807. b.invert();
  60808. a.build(b.allPolygons());
  60809. this.polygons = a.allPolygons();
  60810. };
  60811. CSG.prototype.subtract = function (csg) {
  60812. var a = new Node(this.clone().polygons);
  60813. var b = new Node(csg.clone().polygons);
  60814. a.invert();
  60815. a.clipTo(b);
  60816. b.clipTo(a);
  60817. b.invert();
  60818. b.clipTo(a);
  60819. b.invert();
  60820. a.build(b.allPolygons());
  60821. a.invert();
  60822. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60823. };
  60824. CSG.prototype.subtractInPlace = function (csg) {
  60825. var a = new Node(this.polygons);
  60826. var b = new Node(csg.polygons);
  60827. a.invert();
  60828. a.clipTo(b);
  60829. b.clipTo(a);
  60830. b.invert();
  60831. b.clipTo(a);
  60832. b.invert();
  60833. a.build(b.allPolygons());
  60834. a.invert();
  60835. this.polygons = a.allPolygons();
  60836. };
  60837. CSG.prototype.intersect = function (csg) {
  60838. var a = new Node(this.clone().polygons);
  60839. var b = new Node(csg.clone().polygons);
  60840. a.invert();
  60841. b.clipTo(a);
  60842. b.invert();
  60843. a.clipTo(b);
  60844. b.clipTo(a);
  60845. a.build(b.allPolygons());
  60846. a.invert();
  60847. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60848. };
  60849. CSG.prototype.intersectInPlace = function (csg) {
  60850. var a = new Node(this.polygons);
  60851. var b = new Node(csg.polygons);
  60852. a.invert();
  60853. b.clipTo(a);
  60854. b.invert();
  60855. a.clipTo(b);
  60856. b.clipTo(a);
  60857. a.build(b.allPolygons());
  60858. a.invert();
  60859. this.polygons = a.allPolygons();
  60860. };
  60861. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  60862. // not modified.
  60863. CSG.prototype.inverse = function () {
  60864. var csg = this.clone();
  60865. csg.inverseInPlace();
  60866. return csg;
  60867. };
  60868. CSG.prototype.inverseInPlace = function () {
  60869. this.polygons.map(function (p) { p.flip(); });
  60870. };
  60871. // This is used to keep meshes transformations so they can be restored
  60872. // when we build back a Babylon Mesh
  60873. // NB : All CSG operations are performed in world coordinates
  60874. CSG.prototype.copyTransformAttributes = function (csg) {
  60875. this.matrix = csg.matrix;
  60876. this.position = csg.position;
  60877. this.rotation = csg.rotation;
  60878. this.scaling = csg.scaling;
  60879. this.rotationQuaternion = csg.rotationQuaternion;
  60880. return this;
  60881. };
  60882. // Build Raw mesh from CSG
  60883. // Coordinates here are in world space
  60884. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  60885. var matrix = this.matrix.clone();
  60886. matrix.invert();
  60887. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  60888. if (keepSubMeshes) {
  60889. // Sort Polygons, since subMeshes are indices range
  60890. polygons.sort(function (a, b) {
  60891. if (a.shared.meshId === b.shared.meshId) {
  60892. return a.shared.subMeshId - b.shared.subMeshId;
  60893. }
  60894. else {
  60895. return a.shared.meshId - b.shared.meshId;
  60896. }
  60897. });
  60898. }
  60899. for (var i = 0, il = polygons.length; i < il; i++) {
  60900. polygon = polygons[i];
  60901. // Building SubMeshes
  60902. if (!subMesh_dict[polygon.shared.meshId]) {
  60903. subMesh_dict[polygon.shared.meshId] = {};
  60904. }
  60905. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  60906. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  60907. indexStart: +Infinity,
  60908. indexEnd: -Infinity,
  60909. materialIndex: polygon.shared.materialIndex
  60910. };
  60911. }
  60912. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  60913. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  60914. polygonIndices[0] = 0;
  60915. polygonIndices[1] = j - 1;
  60916. polygonIndices[2] = j;
  60917. for (var k = 0; k < 3; k++) {
  60918. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  60919. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  60920. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  60921. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  60922. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  60923. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  60924. // Check if 2 points can be merged
  60925. if (!(typeof vertex_idx !== 'undefined' &&
  60926. normals[vertex_idx * 3] === localNormal.x &&
  60927. normals[vertex_idx * 3 + 1] === localNormal.y &&
  60928. normals[vertex_idx * 3 + 2] === localNormal.z &&
  60929. uvs[vertex_idx * 2] === uv.x &&
  60930. uvs[vertex_idx * 2 + 1] === uv.y)) {
  60931. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  60932. uvs.push(uv.x, uv.y);
  60933. normals.push(normal.x, normal.y, normal.z);
  60934. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  60935. }
  60936. indices.push(vertex_idx);
  60937. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  60938. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  60939. currentIndex++;
  60940. }
  60941. }
  60942. }
  60943. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  60944. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  60945. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  60946. mesh.setIndices(indices);
  60947. if (keepSubMeshes) {
  60948. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  60949. var materialIndexOffset = 0, materialMaxIndex;
  60950. mesh.subMeshes = new Array();
  60951. for (var m in subMesh_dict) {
  60952. materialMaxIndex = -1;
  60953. for (var sm in subMesh_dict[m]) {
  60954. subMesh_obj = subMesh_dict[m][sm];
  60955. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  60956. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  60957. }
  60958. materialIndexOffset += ++materialMaxIndex;
  60959. }
  60960. }
  60961. return mesh;
  60962. };
  60963. // Build Mesh from CSG taking material and transforms into account
  60964. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  60965. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  60966. mesh.material = material;
  60967. mesh.position.copyFrom(this.position);
  60968. mesh.rotation.copyFrom(this.rotation);
  60969. if (this.rotationQuaternion) {
  60970. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  60971. }
  60972. mesh.scaling.copyFrom(this.scaling);
  60973. mesh.computeWorldMatrix(true);
  60974. return mesh;
  60975. };
  60976. return CSG;
  60977. }());
  60978. BABYLON.CSG = CSG;
  60979. })(BABYLON || (BABYLON = {}));
  60980. //# sourceMappingURL=babylon.csg.js.map
  60981. var BABYLON;
  60982. (function (BABYLON) {
  60983. var LensFlare = (function () {
  60984. function LensFlare(size, position, color, imgUrl, system) {
  60985. this.size = size;
  60986. this.position = position;
  60987. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  60988. this.dispose = function () {
  60989. if (this.texture) {
  60990. this.texture.dispose();
  60991. }
  60992. // Remove from scene
  60993. var index = this._system.lensFlares.indexOf(this);
  60994. this._system.lensFlares.splice(index, 1);
  60995. };
  60996. this.color = color || new BABYLON.Color3(1, 1, 1);
  60997. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  60998. this._system = system;
  60999. system.lensFlares.push(this);
  61000. }
  61001. return LensFlare;
  61002. }());
  61003. BABYLON.LensFlare = LensFlare;
  61004. })(BABYLON || (BABYLON = {}));
  61005. //# sourceMappingURL=babylon.lensFlare.js.map
  61006. var BABYLON;
  61007. (function (BABYLON) {
  61008. var LensFlareSystem = (function () {
  61009. function LensFlareSystem(name, emitter, scene) {
  61010. this.name = name;
  61011. this.lensFlares = new Array();
  61012. this.borderLimit = 300;
  61013. this.viewportBorder = 0;
  61014. this.layerMask = 0x0FFFFFFF;
  61015. this._vertexBuffers = {};
  61016. this._isEnabled = true;
  61017. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61018. this._emitter = emitter;
  61019. this.id = name;
  61020. scene.lensFlareSystems.push(this);
  61021. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  61022. var engine = scene.getEngine();
  61023. // VBO
  61024. var vertices = [];
  61025. vertices.push(1, 1);
  61026. vertices.push(-1, 1);
  61027. vertices.push(-1, -1);
  61028. vertices.push(1, -1);
  61029. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61030. // Indices
  61031. var indices = [];
  61032. indices.push(0);
  61033. indices.push(1);
  61034. indices.push(2);
  61035. indices.push(0);
  61036. indices.push(2);
  61037. indices.push(3);
  61038. this._indexBuffer = engine.createIndexBuffer(indices);
  61039. // Effects
  61040. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  61041. }
  61042. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  61043. get: function () {
  61044. return this._isEnabled;
  61045. },
  61046. set: function (value) {
  61047. this._isEnabled = value;
  61048. },
  61049. enumerable: true,
  61050. configurable: true
  61051. });
  61052. LensFlareSystem.prototype.getScene = function () {
  61053. return this._scene;
  61054. };
  61055. LensFlareSystem.prototype.getEmitter = function () {
  61056. return this._emitter;
  61057. };
  61058. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  61059. this._emitter = newEmitter;
  61060. };
  61061. LensFlareSystem.prototype.getEmitterPosition = function () {
  61062. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  61063. };
  61064. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  61065. var position = this.getEmitterPosition();
  61066. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  61067. this._positionX = position.x;
  61068. this._positionY = position.y;
  61069. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  61070. if (this.viewportBorder > 0) {
  61071. globalViewport.x -= this.viewportBorder;
  61072. globalViewport.y -= this.viewportBorder;
  61073. globalViewport.width += this.viewportBorder * 2;
  61074. globalViewport.height += this.viewportBorder * 2;
  61075. position.x += this.viewportBorder;
  61076. position.y += this.viewportBorder;
  61077. this._positionX += this.viewportBorder;
  61078. this._positionY += this.viewportBorder;
  61079. }
  61080. if (position.z > 0) {
  61081. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  61082. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  61083. return true;
  61084. }
  61085. return true;
  61086. }
  61087. return false;
  61088. };
  61089. LensFlareSystem.prototype._isVisible = function () {
  61090. if (!this._isEnabled) {
  61091. return false;
  61092. }
  61093. var emitterPosition = this.getEmitterPosition();
  61094. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  61095. var distance = direction.length();
  61096. direction.normalize();
  61097. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  61098. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  61099. return !pickInfo.hit || pickInfo.distance > distance;
  61100. };
  61101. LensFlareSystem.prototype.render = function () {
  61102. if (!this._effect.isReady())
  61103. return false;
  61104. var engine = this._scene.getEngine();
  61105. var viewport = this._scene.activeCamera.viewport;
  61106. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  61107. // Position
  61108. if (!this.computeEffectivePosition(globalViewport)) {
  61109. return false;
  61110. }
  61111. // Visibility
  61112. if (!this._isVisible()) {
  61113. return false;
  61114. }
  61115. // Intensity
  61116. var awayX;
  61117. var awayY;
  61118. if (this._positionX < this.borderLimit + globalViewport.x) {
  61119. awayX = this.borderLimit + globalViewport.x - this._positionX;
  61120. }
  61121. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  61122. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  61123. }
  61124. else {
  61125. awayX = 0;
  61126. }
  61127. if (this._positionY < this.borderLimit + globalViewport.y) {
  61128. awayY = this.borderLimit + globalViewport.y - this._positionY;
  61129. }
  61130. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  61131. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  61132. }
  61133. else {
  61134. awayY = 0;
  61135. }
  61136. var away = (awayX > awayY) ? awayX : awayY;
  61137. away -= this.viewportBorder;
  61138. if (away > this.borderLimit) {
  61139. away = this.borderLimit;
  61140. }
  61141. var intensity = 1.0 - (away / this.borderLimit);
  61142. if (intensity < 0) {
  61143. return false;
  61144. }
  61145. if (intensity > 1.0) {
  61146. intensity = 1.0;
  61147. }
  61148. if (this.viewportBorder > 0) {
  61149. globalViewport.x += this.viewportBorder;
  61150. globalViewport.y += this.viewportBorder;
  61151. globalViewport.width -= this.viewportBorder * 2;
  61152. globalViewport.height -= this.viewportBorder * 2;
  61153. this._positionX -= this.viewportBorder;
  61154. this._positionY -= this.viewportBorder;
  61155. }
  61156. // Position
  61157. var centerX = globalViewport.x + globalViewport.width / 2;
  61158. var centerY = globalViewport.y + globalViewport.height / 2;
  61159. var distX = centerX - this._positionX;
  61160. var distY = centerY - this._positionY;
  61161. // Effects
  61162. engine.enableEffect(this._effect);
  61163. engine.setState(false);
  61164. engine.setDepthBuffer(false);
  61165. // VBOs
  61166. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  61167. // Flares
  61168. for (var index = 0; index < this.lensFlares.length; index++) {
  61169. var flare = this.lensFlares[index];
  61170. engine.setAlphaMode(flare.alphaMode);
  61171. var x = centerX - (distX * flare.position);
  61172. var y = centerY - (distY * flare.position);
  61173. var cw = flare.size;
  61174. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  61175. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  61176. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  61177. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  61178. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  61179. // Texture
  61180. this._effect.setTexture("textureSampler", flare.texture);
  61181. // Color
  61182. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  61183. // Draw order
  61184. engine.draw(true, 0, 6);
  61185. }
  61186. engine.setDepthBuffer(true);
  61187. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61188. return true;
  61189. };
  61190. LensFlareSystem.prototype.dispose = function () {
  61191. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61192. if (vertexBuffer) {
  61193. vertexBuffer.dispose();
  61194. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61195. }
  61196. if (this._indexBuffer) {
  61197. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61198. this._indexBuffer = null;
  61199. }
  61200. while (this.lensFlares.length) {
  61201. this.lensFlares[0].dispose();
  61202. }
  61203. // Remove from scene
  61204. var index = this._scene.lensFlareSystems.indexOf(this);
  61205. this._scene.lensFlareSystems.splice(index, 1);
  61206. };
  61207. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  61208. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  61209. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  61210. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  61211. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  61212. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  61213. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  61214. var parsedFlare = parsedLensFlareSystem.flares[index];
  61215. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  61216. }
  61217. return lensFlareSystem;
  61218. };
  61219. LensFlareSystem.prototype.serialize = function () {
  61220. var serializationObject = {};
  61221. serializationObject.id = this.id;
  61222. serializationObject.name = this.name;
  61223. serializationObject.emitterId = this.getEmitter().id;
  61224. serializationObject.borderLimit = this.borderLimit;
  61225. serializationObject.flares = [];
  61226. for (var index = 0; index < this.lensFlares.length; index++) {
  61227. var flare = this.lensFlares[index];
  61228. serializationObject.flares.push({
  61229. size: flare.size,
  61230. position: flare.position,
  61231. color: flare.color.asArray(),
  61232. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  61233. });
  61234. }
  61235. return serializationObject;
  61236. };
  61237. return LensFlareSystem;
  61238. }());
  61239. BABYLON.LensFlareSystem = LensFlareSystem;
  61240. })(BABYLON || (BABYLON = {}));
  61241. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  61242. var BABYLON;
  61243. (function (BABYLON) {
  61244. /**
  61245. * This is a holder class for the physics joint created by the physics plugin.
  61246. * It holds a set of functions to control the underlying joint.
  61247. */
  61248. var PhysicsJoint = (function () {
  61249. function PhysicsJoint(type, jointData) {
  61250. this.type = type;
  61251. this.jointData = jointData;
  61252. jointData.nativeParams = jointData.nativeParams || {};
  61253. }
  61254. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  61255. get: function () {
  61256. return this._physicsJoint;
  61257. },
  61258. set: function (newJoint) {
  61259. if (this._physicsJoint) {
  61260. //remove from the wolrd
  61261. }
  61262. this._physicsJoint = newJoint;
  61263. },
  61264. enumerable: true,
  61265. configurable: true
  61266. });
  61267. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  61268. set: function (physicsPlugin) {
  61269. this._physicsPlugin = physicsPlugin;
  61270. },
  61271. enumerable: true,
  61272. configurable: true
  61273. });
  61274. /**
  61275. * Execute a function that is physics-plugin specific.
  61276. * @param {Function} func the function that will be executed.
  61277. * It accepts two parameters: the physics world and the physics joint.
  61278. */
  61279. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  61280. func(this._physicsPlugin.world, this._physicsJoint);
  61281. };
  61282. //TODO check if the native joints are the same
  61283. //Joint Types
  61284. PhysicsJoint.DistanceJoint = 0;
  61285. PhysicsJoint.HingeJoint = 1;
  61286. PhysicsJoint.BallAndSocketJoint = 2;
  61287. PhysicsJoint.WheelJoint = 3;
  61288. PhysicsJoint.SliderJoint = 4;
  61289. //OIMO
  61290. PhysicsJoint.PrismaticJoint = 5;
  61291. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  61292. PhysicsJoint.UniversalJoint = 6;
  61293. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  61294. //Cannon
  61295. //Similar to a Ball-Joint. Different in params
  61296. PhysicsJoint.PointToPointJoint = 8;
  61297. //Cannon only at the moment
  61298. PhysicsJoint.SpringJoint = 9;
  61299. PhysicsJoint.LockJoint = 10;
  61300. return PhysicsJoint;
  61301. }());
  61302. BABYLON.PhysicsJoint = PhysicsJoint;
  61303. /**
  61304. * A class representing a physics distance joint.
  61305. */
  61306. var DistanceJoint = (function (_super) {
  61307. __extends(DistanceJoint, _super);
  61308. function DistanceJoint(jointData) {
  61309. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  61310. }
  61311. /**
  61312. * Update the predefined distance.
  61313. */
  61314. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  61315. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  61316. };
  61317. return DistanceJoint;
  61318. }(PhysicsJoint));
  61319. BABYLON.DistanceJoint = DistanceJoint;
  61320. var MotorEnabledJoint = (function (_super) {
  61321. __extends(MotorEnabledJoint, _super);
  61322. function MotorEnabledJoint(type, jointData) {
  61323. return _super.call(this, type, jointData) || this;
  61324. }
  61325. /**
  61326. * Set the motor values.
  61327. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61328. * @param {number} force the force to apply
  61329. * @param {number} maxForce max force for this motor.
  61330. */
  61331. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  61332. this._physicsPlugin.setMotor(this, force, maxForce);
  61333. };
  61334. /**
  61335. * Set the motor's limits.
  61336. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61337. */
  61338. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  61339. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  61340. };
  61341. return MotorEnabledJoint;
  61342. }(PhysicsJoint));
  61343. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  61344. /**
  61345. * This class represents a single hinge physics joint
  61346. */
  61347. var HingeJoint = (function (_super) {
  61348. __extends(HingeJoint, _super);
  61349. function HingeJoint(jointData) {
  61350. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  61351. }
  61352. /**
  61353. * Set the motor values.
  61354. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61355. * @param {number} force the force to apply
  61356. * @param {number} maxForce max force for this motor.
  61357. */
  61358. HingeJoint.prototype.setMotor = function (force, maxForce) {
  61359. this._physicsPlugin.setMotor(this, force, maxForce);
  61360. };
  61361. /**
  61362. * Set the motor's limits.
  61363. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61364. */
  61365. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  61366. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  61367. };
  61368. return HingeJoint;
  61369. }(MotorEnabledJoint));
  61370. BABYLON.HingeJoint = HingeJoint;
  61371. /**
  61372. * This class represents a dual hinge physics joint (same as wheel joint)
  61373. */
  61374. var Hinge2Joint = (function (_super) {
  61375. __extends(Hinge2Joint, _super);
  61376. function Hinge2Joint(jointData) {
  61377. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  61378. }
  61379. /**
  61380. * Set the motor values.
  61381. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61382. * @param {number} force the force to apply
  61383. * @param {number} maxForce max force for this motor.
  61384. * @param {motorIndex} the motor's index, 0 or 1.
  61385. */
  61386. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  61387. if (motorIndex === void 0) { motorIndex = 0; }
  61388. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  61389. };
  61390. /**
  61391. * Set the motor limits.
  61392. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61393. * @param {number} upperLimit the upper limit
  61394. * @param {number} lowerLimit lower limit
  61395. * @param {motorIndex} the motor's index, 0 or 1.
  61396. */
  61397. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  61398. if (motorIndex === void 0) { motorIndex = 0; }
  61399. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  61400. };
  61401. return Hinge2Joint;
  61402. }(MotorEnabledJoint));
  61403. BABYLON.Hinge2Joint = Hinge2Joint;
  61404. })(BABYLON || (BABYLON = {}));
  61405. //# sourceMappingURL=babylon.physicsJoint.js.map
  61406. var BABYLON;
  61407. (function (BABYLON) {
  61408. var PhysicsImpostor = (function () {
  61409. function PhysicsImpostor(object, type, _options, _scene) {
  61410. if (_options === void 0) { _options = { mass: 0 }; }
  61411. var _this = this;
  61412. this.object = object;
  61413. this.type = type;
  61414. this._options = _options;
  61415. this._scene = _scene;
  61416. this._bodyUpdateRequired = false;
  61417. this._onBeforePhysicsStepCallbacks = new Array();
  61418. this._onAfterPhysicsStepCallbacks = new Array();
  61419. this._onPhysicsCollideCallbacks = [];
  61420. this._deltaPosition = BABYLON.Vector3.Zero();
  61421. this._isDisposed = false;
  61422. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  61423. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  61424. /**
  61425. * this function is executed by the physics engine.
  61426. */
  61427. this.beforeStep = function () {
  61428. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  61429. //conjugate deltaRotation
  61430. if (_this._deltaRotationConjugated) {
  61431. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  61432. }
  61433. else {
  61434. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  61435. }
  61436. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  61437. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  61438. func(_this);
  61439. });
  61440. };
  61441. /**
  61442. * this function is executed by the physics engine.
  61443. */
  61444. this.afterStep = function () {
  61445. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  61446. func(_this);
  61447. });
  61448. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  61449. _this.object.position.addInPlace(_this._deltaPosition);
  61450. if (_this._deltaRotation) {
  61451. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  61452. }
  61453. };
  61454. /**
  61455. * Legacy collision detection event support
  61456. */
  61457. this.onCollideEvent = null;
  61458. //event and body object due to cannon's event-based architecture.
  61459. this.onCollide = function (e) {
  61460. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  61461. return;
  61462. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  61463. if (otherImpostor) {
  61464. // Legacy collision detection event support
  61465. if (_this.onCollideEvent) {
  61466. _this.onCollideEvent(_this, otherImpostor);
  61467. }
  61468. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  61469. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  61470. }).forEach(function (obj) {
  61471. obj.callback(_this, otherImpostor);
  61472. });
  61473. }
  61474. };
  61475. //sanity check!
  61476. if (!this.object) {
  61477. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  61478. return;
  61479. }
  61480. //legacy support for old syntax.
  61481. if (!this._scene && object.getScene) {
  61482. this._scene = object.getScene();
  61483. }
  61484. this._physicsEngine = this._scene.getPhysicsEngine();
  61485. if (!this._physicsEngine) {
  61486. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  61487. }
  61488. else {
  61489. //set the object's quaternion, if not set
  61490. if (!this.object.rotationQuaternion) {
  61491. if (this.object.rotation) {
  61492. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  61493. }
  61494. else {
  61495. this.object.rotationQuaternion = new BABYLON.Quaternion();
  61496. }
  61497. }
  61498. //default options params
  61499. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  61500. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  61501. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  61502. this._joints = [];
  61503. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  61504. if (!this.object.parent) {
  61505. this._init();
  61506. }
  61507. else if (this.object.parent.physicsImpostor) {
  61508. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  61509. }
  61510. }
  61511. }
  61512. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  61513. get: function () {
  61514. return this._isDisposed;
  61515. },
  61516. enumerable: true,
  61517. configurable: true
  61518. });
  61519. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  61520. get: function () {
  61521. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  61522. },
  61523. set: function (value) {
  61524. this.setMass(value);
  61525. },
  61526. enumerable: true,
  61527. configurable: true
  61528. });
  61529. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  61530. get: function () {
  61531. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  61532. },
  61533. set: function (value) {
  61534. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  61535. },
  61536. enumerable: true,
  61537. configurable: true
  61538. });
  61539. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  61540. get: function () {
  61541. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  61542. },
  61543. set: function (value) {
  61544. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  61545. },
  61546. enumerable: true,
  61547. configurable: true
  61548. });
  61549. /**
  61550. * This function will completly initialize this impostor.
  61551. * It will create a new body - but only if this mesh has no parent.
  61552. * If it has, this impostor will not be used other than to define the impostor
  61553. * of the child mesh.
  61554. */
  61555. PhysicsImpostor.prototype._init = function () {
  61556. this._physicsEngine.removeImpostor(this);
  61557. this.physicsBody = null;
  61558. this._parent = this._parent || this._getPhysicsParent();
  61559. if (!this.parent) {
  61560. this._physicsEngine.addImpostor(this);
  61561. }
  61562. };
  61563. PhysicsImpostor.prototype._getPhysicsParent = function () {
  61564. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  61565. var parentMesh = this.object.parent;
  61566. return parentMesh.physicsImpostor;
  61567. }
  61568. return;
  61569. };
  61570. /**
  61571. * Should a new body be generated.
  61572. */
  61573. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  61574. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  61575. };
  61576. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  61577. this.forceUpdate();
  61578. };
  61579. /**
  61580. * Force a regeneration of this or the parent's impostor's body.
  61581. * Use under cautious - This will remove all joints already implemented.
  61582. */
  61583. PhysicsImpostor.prototype.forceUpdate = function () {
  61584. this._init();
  61585. if (this.parent) {
  61586. this.parent.forceUpdate();
  61587. }
  61588. };
  61589. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  61590. /*public get mesh(): AbstractMesh {
  61591. return this._mesh;
  61592. }*/
  61593. /**
  61594. * Gets the body that holds this impostor. Either its own, or its parent.
  61595. */
  61596. get: function () {
  61597. return this._parent ? this._parent.physicsBody : this._physicsBody;
  61598. },
  61599. /**
  61600. * Set the physics body. Used mainly by the physics engine/plugin
  61601. */
  61602. set: function (physicsBody) {
  61603. if (this._physicsBody) {
  61604. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  61605. }
  61606. this._physicsBody = physicsBody;
  61607. this.resetUpdateFlags();
  61608. },
  61609. enumerable: true,
  61610. configurable: true
  61611. });
  61612. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  61613. get: function () {
  61614. return this._parent;
  61615. },
  61616. set: function (value) {
  61617. this._parent = value;
  61618. },
  61619. enumerable: true,
  61620. configurable: true
  61621. });
  61622. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  61623. this._bodyUpdateRequired = false;
  61624. };
  61625. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  61626. if (this.object.getBoundingInfo) {
  61627. var q = this.object.rotationQuaternion;
  61628. //reset rotation
  61629. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  61630. //calculate the world matrix with no rotation
  61631. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  61632. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  61633. //bring back the rotation
  61634. this.object.rotationQuaternion = q;
  61635. //calculate the world matrix with the new rotation
  61636. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  61637. return size;
  61638. }
  61639. else {
  61640. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  61641. }
  61642. };
  61643. PhysicsImpostor.prototype.getObjectCenter = function () {
  61644. if (this.object.getBoundingInfo) {
  61645. return this.object.getBoundingInfo().boundingBox.centerWorld;
  61646. }
  61647. else {
  61648. return this.object.position;
  61649. }
  61650. };
  61651. /**
  61652. * Get a specific parametes from the options parameter.
  61653. */
  61654. PhysicsImpostor.prototype.getParam = function (paramName) {
  61655. return this._options[paramName];
  61656. };
  61657. /**
  61658. * Sets a specific parameter in the options given to the physics plugin
  61659. */
  61660. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  61661. this._options[paramName] = value;
  61662. this._bodyUpdateRequired = true;
  61663. };
  61664. /**
  61665. * Specifically change the body's mass option. Won't recreate the physics body object
  61666. */
  61667. PhysicsImpostor.prototype.setMass = function (mass) {
  61668. if (this.getParam("mass") !== mass) {
  61669. this.setParam("mass", mass);
  61670. }
  61671. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  61672. };
  61673. PhysicsImpostor.prototype.getLinearVelocity = function () {
  61674. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  61675. };
  61676. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  61677. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  61678. };
  61679. PhysicsImpostor.prototype.getAngularVelocity = function () {
  61680. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  61681. };
  61682. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  61683. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  61684. };
  61685. /**
  61686. * Execute a function with the physics plugin native code.
  61687. * Provide a function the will have two variables - the world object and the physics body object.
  61688. */
  61689. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  61690. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  61691. };
  61692. /**
  61693. * Register a function that will be executed before the physics world is stepping forward.
  61694. */
  61695. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  61696. this._onBeforePhysicsStepCallbacks.push(func);
  61697. };
  61698. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  61699. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  61700. if (index > -1) {
  61701. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  61702. }
  61703. else {
  61704. BABYLON.Tools.Warn("Function to remove was not found");
  61705. }
  61706. };
  61707. /**
  61708. * Register a function that will be executed after the physics step
  61709. */
  61710. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  61711. this._onAfterPhysicsStepCallbacks.push(func);
  61712. };
  61713. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  61714. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  61715. if (index > -1) {
  61716. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  61717. }
  61718. else {
  61719. BABYLON.Tools.Warn("Function to remove was not found");
  61720. }
  61721. };
  61722. /**
  61723. * register a function that will be executed when this impostor collides against a different body.
  61724. */
  61725. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  61726. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  61727. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  61728. };
  61729. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  61730. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  61731. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  61732. if (index > -1) {
  61733. this._onPhysicsCollideCallbacks.splice(index, 1);
  61734. }
  61735. else {
  61736. BABYLON.Tools.Warn("Function to remove was not found");
  61737. }
  61738. };
  61739. /**
  61740. * Apply a force
  61741. */
  61742. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  61743. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  61744. };
  61745. /**
  61746. * Apply an impulse
  61747. */
  61748. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  61749. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  61750. };
  61751. /**
  61752. * A help function to create a joint.
  61753. */
  61754. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  61755. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  61756. this.addJoint(otherImpostor, joint);
  61757. };
  61758. /**
  61759. * Add a joint to this impostor with a different impostor.
  61760. */
  61761. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  61762. this._joints.push({
  61763. otherImpostor: otherImpostor,
  61764. joint: joint
  61765. });
  61766. this._physicsEngine.addJoint(this, otherImpostor, joint);
  61767. };
  61768. /**
  61769. * Will keep this body still, in a sleep mode.
  61770. */
  61771. PhysicsImpostor.prototype.sleep = function () {
  61772. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  61773. };
  61774. /**
  61775. * Wake the body up.
  61776. */
  61777. PhysicsImpostor.prototype.wakeUp = function () {
  61778. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  61779. };
  61780. PhysicsImpostor.prototype.clone = function (newObject) {
  61781. if (!newObject)
  61782. return null;
  61783. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  61784. };
  61785. PhysicsImpostor.prototype.dispose = function () {
  61786. var _this = this;
  61787. //no dispose if no physics engine is available.
  61788. if (!this._physicsEngine) {
  61789. return;
  61790. }
  61791. this._joints.forEach(function (j) {
  61792. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  61793. });
  61794. //dispose the physics body
  61795. this._physicsEngine.removeImpostor(this);
  61796. if (this.parent) {
  61797. this.parent.forceUpdate();
  61798. }
  61799. else {
  61800. /*this._object.getChildMeshes().forEach(function(mesh) {
  61801. if (mesh.physicsImpostor) {
  61802. if (disposeChildren) {
  61803. mesh.physicsImpostor.dispose();
  61804. mesh.physicsImpostor = null;
  61805. }
  61806. }
  61807. })*/
  61808. }
  61809. this._isDisposed = true;
  61810. };
  61811. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  61812. this._deltaPosition.copyFrom(position);
  61813. };
  61814. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  61815. if (!this._deltaRotation) {
  61816. this._deltaRotation = new BABYLON.Quaternion();
  61817. }
  61818. this._deltaRotation.copyFrom(rotation);
  61819. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  61820. };
  61821. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  61822. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  61823. };
  61824. PhysicsImpostor.prototype.getRadius = function () {
  61825. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  61826. };
  61827. /**
  61828. * Sync a bone with this impostor
  61829. * @param bone The bone to sync to the impostor.
  61830. * @param boneMesh The mesh that the bone is influencing.
  61831. * @param jointPivot The pivot of the joint / bone in local space.
  61832. * @param distToJoint Optional distance from the impostor to the joint.
  61833. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  61834. */
  61835. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  61836. var tempVec = PhysicsImpostor._tmpVecs[0];
  61837. var mesh = this.object;
  61838. if (adjustRotation) {
  61839. var tempQuat = PhysicsImpostor._tmpQuat;
  61840. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  61841. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  61842. }
  61843. else {
  61844. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  61845. }
  61846. tempVec.x = 0;
  61847. tempVec.y = 0;
  61848. tempVec.z = 0;
  61849. if (jointPivot) {
  61850. tempVec.x = jointPivot.x;
  61851. tempVec.y = jointPivot.y;
  61852. tempVec.z = jointPivot.z;
  61853. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  61854. if (distToJoint === undefined || distToJoint === null) {
  61855. distToJoint = jointPivot.length();
  61856. }
  61857. tempVec.x *= distToJoint;
  61858. tempVec.y *= distToJoint;
  61859. tempVec.z *= distToJoint;
  61860. }
  61861. if (bone.getParent()) {
  61862. tempVec.addInPlace(mesh.getAbsolutePosition());
  61863. bone.setAbsolutePosition(tempVec, boneMesh);
  61864. }
  61865. else {
  61866. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  61867. boneMesh.position.x -= tempVec.x;
  61868. boneMesh.position.y -= tempVec.y;
  61869. boneMesh.position.z -= tempVec.z;
  61870. }
  61871. };
  61872. /**
  61873. * Sync impostor to a bone
  61874. * @param bone The bone that the impostor will be synced to.
  61875. * @param boneMesh The mesh that the bone is influencing.
  61876. * @param jointPivot The pivot of the joint / bone in local space.
  61877. * @param distToJoint Optional distance from the impostor to the joint.
  61878. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  61879. * @param boneAxis Optional vector3 axis the bone is aligned with
  61880. */
  61881. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  61882. var mesh = this.object;
  61883. if (adjustRotation) {
  61884. var tempQuat = PhysicsImpostor._tmpQuat;
  61885. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  61886. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  61887. }
  61888. else {
  61889. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  61890. }
  61891. var pos = PhysicsImpostor._tmpVecs[0];
  61892. var boneDir = PhysicsImpostor._tmpVecs[1];
  61893. if (!boneAxis) {
  61894. boneAxis = PhysicsImpostor._tmpVecs[2];
  61895. boneAxis.x = 0;
  61896. boneAxis.y = 1;
  61897. boneAxis.z = 0;
  61898. }
  61899. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  61900. bone.getAbsolutePositionToRef(boneMesh, pos);
  61901. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  61902. distToJoint = jointPivot.length();
  61903. }
  61904. if (distToJoint !== undefined && distToJoint !== null) {
  61905. pos.x += boneDir.x * distToJoint;
  61906. pos.y += boneDir.y * distToJoint;
  61907. pos.z += boneDir.z * distToJoint;
  61908. }
  61909. mesh.setAbsolutePosition(pos);
  61910. };
  61911. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  61912. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  61913. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61914. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  61915. //Impostor types
  61916. PhysicsImpostor.NoImpostor = 0;
  61917. PhysicsImpostor.SphereImpostor = 1;
  61918. PhysicsImpostor.BoxImpostor = 2;
  61919. PhysicsImpostor.PlaneImpostor = 3;
  61920. PhysicsImpostor.MeshImpostor = 4;
  61921. PhysicsImpostor.CylinderImpostor = 7;
  61922. PhysicsImpostor.ParticleImpostor = 8;
  61923. PhysicsImpostor.HeightmapImpostor = 9;
  61924. return PhysicsImpostor;
  61925. }());
  61926. BABYLON.PhysicsImpostor = PhysicsImpostor;
  61927. })(BABYLON || (BABYLON = {}));
  61928. //# sourceMappingURL=babylon.physicsImpostor.js.map
  61929. var BABYLON;
  61930. (function (BABYLON) {
  61931. var PhysicsEngine = (function () {
  61932. function PhysicsEngine(gravity, _physicsPlugin) {
  61933. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  61934. this._physicsPlugin = _physicsPlugin;
  61935. //new methods and parameters
  61936. this._impostors = [];
  61937. this._joints = [];
  61938. if (!this._physicsPlugin.isSupported()) {
  61939. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  61940. + "Please make sure it is included.");
  61941. }
  61942. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  61943. this.setGravity(gravity);
  61944. this.setTimeStep();
  61945. }
  61946. PhysicsEngine.prototype.setGravity = function (gravity) {
  61947. this.gravity = gravity;
  61948. this._physicsPlugin.setGravity(this.gravity);
  61949. };
  61950. /**
  61951. * Set the time step of the physics engine.
  61952. * default is 1/60.
  61953. * To slow it down, enter 1/600 for example.
  61954. * To speed it up, 1/30
  61955. * @param {number} newTimeStep the new timestep to apply to this world.
  61956. */
  61957. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  61958. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  61959. this._physicsPlugin.setTimeStep(newTimeStep);
  61960. };
  61961. /**
  61962. * Get the time step of the physics engine.
  61963. */
  61964. PhysicsEngine.prototype.getTimeStep = function () {
  61965. return this._physicsPlugin.getTimeStep();
  61966. };
  61967. PhysicsEngine.prototype.dispose = function () {
  61968. this._impostors.forEach(function (impostor) {
  61969. impostor.dispose();
  61970. });
  61971. this._physicsPlugin.dispose();
  61972. };
  61973. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  61974. return this._physicsPlugin.name;
  61975. };
  61976. /**
  61977. * Adding a new impostor for the impostor tracking.
  61978. * This will be done by the impostor itself.
  61979. * @param {PhysicsImpostor} impostor the impostor to add
  61980. */
  61981. PhysicsEngine.prototype.addImpostor = function (impostor) {
  61982. impostor.uniqueId = this._impostors.push(impostor);
  61983. //if no parent, generate the body
  61984. if (!impostor.parent) {
  61985. this._physicsPlugin.generatePhysicsBody(impostor);
  61986. }
  61987. };
  61988. /**
  61989. * Remove an impostor from the engine.
  61990. * This impostor and its mesh will not longer be updated by the physics engine.
  61991. * @param {PhysicsImpostor} impostor the impostor to remove
  61992. */
  61993. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  61994. var index = this._impostors.indexOf(impostor);
  61995. if (index > -1) {
  61996. var removed = this._impostors.splice(index, 1);
  61997. //Is it needed?
  61998. if (removed.length) {
  61999. //this will also remove it from the world.
  62000. removed[0].physicsBody = null;
  62001. }
  62002. }
  62003. };
  62004. /**
  62005. * Add a joint to the physics engine
  62006. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  62007. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  62008. * @param {PhysicsJoint} the joint that will connect both impostors.
  62009. */
  62010. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  62011. var impostorJoint = {
  62012. mainImpostor: mainImpostor,
  62013. connectedImpostor: connectedImpostor,
  62014. joint: joint
  62015. };
  62016. joint.physicsPlugin = this._physicsPlugin;
  62017. this._joints.push(impostorJoint);
  62018. this._physicsPlugin.generateJoint(impostorJoint);
  62019. };
  62020. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  62021. var matchingJoints = this._joints.filter(function (impostorJoint) {
  62022. return (impostorJoint.connectedImpostor === connectedImpostor
  62023. && impostorJoint.joint === joint
  62024. && impostorJoint.mainImpostor === mainImpostor);
  62025. });
  62026. if (matchingJoints.length) {
  62027. this._physicsPlugin.removeJoint(matchingJoints[0]);
  62028. //TODO remove it from the list as well
  62029. }
  62030. };
  62031. /**
  62032. * Called by the scene. no need to call it.
  62033. */
  62034. PhysicsEngine.prototype._step = function (delta) {
  62035. var _this = this;
  62036. //check if any mesh has no body / requires an update
  62037. this._impostors.forEach(function (impostor) {
  62038. if (impostor.isBodyInitRequired()) {
  62039. _this._physicsPlugin.generatePhysicsBody(impostor);
  62040. }
  62041. });
  62042. if (delta > 0.1) {
  62043. delta = 0.1;
  62044. }
  62045. else if (delta <= 0) {
  62046. delta = 1.0 / 60.0;
  62047. }
  62048. this._physicsPlugin.executeStep(delta, this._impostors);
  62049. };
  62050. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  62051. return this._physicsPlugin;
  62052. };
  62053. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  62054. for (var i = 0; i < this._impostors.length; ++i) {
  62055. if (this._impostors[i].object === object) {
  62056. return this._impostors[i];
  62057. }
  62058. }
  62059. };
  62060. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  62061. for (var i = 0; i < this._impostors.length; ++i) {
  62062. if (this._impostors[i].physicsBody === body) {
  62063. return this._impostors[i];
  62064. }
  62065. }
  62066. };
  62067. // Statics
  62068. PhysicsEngine.Epsilon = 0.001;
  62069. return PhysicsEngine;
  62070. }());
  62071. BABYLON.PhysicsEngine = PhysicsEngine;
  62072. })(BABYLON || (BABYLON = {}));
  62073. //# sourceMappingURL=babylon.physicsEngine.js.map
  62074. var BABYLON;
  62075. (function (BABYLON) {
  62076. var CannonJSPlugin = (function () {
  62077. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  62078. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  62079. if (iterations === void 0) { iterations = 10; }
  62080. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  62081. this.name = "CannonJSPlugin";
  62082. this._physicsMaterials = [];
  62083. this._fixedTimeStep = 1 / 60;
  62084. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  62085. this._currentCollisionGroup = 2;
  62086. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  62087. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  62088. this._tmpPosition = BABYLON.Vector3.Zero();
  62089. this._tmpQuaternion = new BABYLON.Quaternion();
  62090. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  62091. this._tmpDeltaRotation = new BABYLON.Quaternion();
  62092. this._tmpUnityRotation = new BABYLON.Quaternion();
  62093. if (!this.isSupported()) {
  62094. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  62095. return;
  62096. }
  62097. this.world = new CANNON.World();
  62098. this.world.broadphase = new CANNON.NaiveBroadphase();
  62099. this.world.solver.iterations = iterations;
  62100. }
  62101. CannonJSPlugin.prototype.setGravity = function (gravity) {
  62102. this.world.gravity.copy(gravity);
  62103. };
  62104. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  62105. this._fixedTimeStep = timeStep;
  62106. };
  62107. CannonJSPlugin.prototype.getTimeStep = function () {
  62108. return this._fixedTimeStep;
  62109. };
  62110. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  62111. // Delta is in seconds, should be provided in milliseconds
  62112. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  62113. };
  62114. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  62115. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  62116. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  62117. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  62118. };
  62119. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  62120. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  62121. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  62122. impostor.physicsBody.applyForce(impulse, worldPoint);
  62123. };
  62124. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  62125. //parent-child relationship. Does this impostor has a parent impostor?
  62126. if (impostor.parent) {
  62127. if (impostor.physicsBody) {
  62128. this.removePhysicsBody(impostor);
  62129. //TODO is that needed?
  62130. impostor.forceUpdate();
  62131. }
  62132. return;
  62133. }
  62134. //should a new body be created for this impostor?
  62135. if (impostor.isBodyInitRequired()) {
  62136. var shape = this._createShape(impostor);
  62137. //unregister events, if body is being changed
  62138. var oldBody = impostor.physicsBody;
  62139. if (oldBody) {
  62140. this.removePhysicsBody(impostor);
  62141. }
  62142. //create the body and material
  62143. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  62144. var bodyCreationObject = {
  62145. mass: impostor.getParam("mass"),
  62146. material: material
  62147. };
  62148. // A simple extend, in case native options were used.
  62149. var nativeOptions = impostor.getParam("nativeOptions");
  62150. for (var key in nativeOptions) {
  62151. if (nativeOptions.hasOwnProperty(key)) {
  62152. bodyCreationObject[key] = nativeOptions[key];
  62153. }
  62154. }
  62155. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  62156. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  62157. this.world.addEventListener("preStep", impostor.beforeStep);
  62158. this.world.addEventListener("postStep", impostor.afterStep);
  62159. impostor.physicsBody.addShape(shape);
  62160. this.world.add(impostor.physicsBody);
  62161. //try to keep the body moving in the right direction by taking old properties.
  62162. //Should be tested!
  62163. if (oldBody) {
  62164. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  62165. impostor.physicsBody[param].copy(oldBody[param]);
  62166. });
  62167. }
  62168. this._processChildMeshes(impostor);
  62169. }
  62170. //now update the body's transformation
  62171. this._updatePhysicsBodyTransformation(impostor);
  62172. };
  62173. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  62174. var _this = this;
  62175. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  62176. if (meshChildren.length) {
  62177. var processMesh = function (localPosition, mesh) {
  62178. var childImpostor = mesh.getPhysicsImpostor();
  62179. if (childImpostor) {
  62180. var parent = childImpostor.parent;
  62181. if (parent !== mainImpostor) {
  62182. var localPosition = mesh.position;
  62183. if (childImpostor.physicsBody) {
  62184. _this.removePhysicsBody(childImpostor);
  62185. childImpostor.physicsBody = null;
  62186. }
  62187. childImpostor.parent = mainImpostor;
  62188. childImpostor.resetUpdateFlags();
  62189. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  62190. //Add the mass of the children.
  62191. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  62192. }
  62193. }
  62194. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  62195. };
  62196. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  62197. }
  62198. };
  62199. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  62200. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  62201. this.world.removeEventListener("preStep", impostor.beforeStep);
  62202. this.world.removeEventListener("postStep", impostor.afterStep);
  62203. this.world.remove(impostor.physicsBody);
  62204. };
  62205. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  62206. var mainBody = impostorJoint.mainImpostor.physicsBody;
  62207. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  62208. if (!mainBody || !connectedBody) {
  62209. return;
  62210. }
  62211. var constraint;
  62212. var jointData = impostorJoint.joint.jointData;
  62213. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  62214. var constraintData = {
  62215. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  62216. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  62217. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  62218. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  62219. maxForce: jointData.nativeParams.maxForce,
  62220. collideConnected: !!jointData.collision
  62221. };
  62222. switch (impostorJoint.joint.type) {
  62223. case BABYLON.PhysicsJoint.HingeJoint:
  62224. case BABYLON.PhysicsJoint.Hinge2Joint:
  62225. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  62226. break;
  62227. case BABYLON.PhysicsJoint.DistanceJoint:
  62228. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  62229. break;
  62230. case BABYLON.PhysicsJoint.SpringJoint:
  62231. var springData = jointData;
  62232. constraint = new CANNON.Spring(mainBody, connectedBody, {
  62233. restLength: springData.length,
  62234. stiffness: springData.stiffness,
  62235. damping: springData.damping,
  62236. localAnchorA: constraintData.pivotA,
  62237. localAnchorB: constraintData.pivotB
  62238. });
  62239. break;
  62240. case BABYLON.PhysicsJoint.LockJoint:
  62241. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  62242. break;
  62243. case BABYLON.PhysicsJoint.PointToPointJoint:
  62244. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  62245. default:
  62246. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  62247. break;
  62248. }
  62249. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  62250. constraint.collideConnected = !!jointData.collision;
  62251. impostorJoint.joint.physicsJoint = constraint;
  62252. //don't add spring as constraint, as it is not one.
  62253. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  62254. this.world.addConstraint(constraint);
  62255. }
  62256. else {
  62257. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  62258. constraint.applyForce();
  62259. });
  62260. }
  62261. };
  62262. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  62263. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  62264. };
  62265. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  62266. var index;
  62267. var mat;
  62268. for (index = 0; index < this._physicsMaterials.length; index++) {
  62269. mat = this._physicsMaterials[index];
  62270. if (mat.friction === friction && mat.restitution === restitution) {
  62271. return mat;
  62272. }
  62273. }
  62274. var currentMat = new CANNON.Material(name);
  62275. currentMat.friction = friction;
  62276. currentMat.restitution = restitution;
  62277. this._physicsMaterials.push(currentMat);
  62278. return currentMat;
  62279. };
  62280. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  62281. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  62282. };
  62283. CannonJSPlugin.prototype._createShape = function (impostor) {
  62284. var object = impostor.object;
  62285. var returnValue;
  62286. var extendSize = impostor.getObjectExtendSize();
  62287. switch (impostor.type) {
  62288. case BABYLON.PhysicsImpostor.SphereImpostor:
  62289. var radiusX = extendSize.x;
  62290. var radiusY = extendSize.y;
  62291. var radiusZ = extendSize.z;
  62292. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  62293. break;
  62294. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  62295. case BABYLON.PhysicsImpostor.CylinderImpostor:
  62296. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  62297. break;
  62298. case BABYLON.PhysicsImpostor.BoxImpostor:
  62299. var box = extendSize.scale(0.5);
  62300. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  62301. break;
  62302. case BABYLON.PhysicsImpostor.PlaneImpostor:
  62303. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  62304. returnValue = new CANNON.Plane();
  62305. break;
  62306. case BABYLON.PhysicsImpostor.MeshImpostor:
  62307. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  62308. var rawFaces = object.getIndices ? object.getIndices() : [];
  62309. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  62310. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  62311. break;
  62312. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  62313. returnValue = this._createHeightmap(object);
  62314. break;
  62315. case BABYLON.PhysicsImpostor.ParticleImpostor:
  62316. returnValue = new CANNON.Particle();
  62317. break;
  62318. }
  62319. return returnValue;
  62320. };
  62321. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  62322. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62323. var matrix = [];
  62324. //For now pointDepth will not be used and will be automatically calculated.
  62325. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  62326. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  62327. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  62328. var elementSize = dim * 2 / arraySize;
  62329. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  62330. for (var i = 0; i < pos.length; i = i + 3) {
  62331. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  62332. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  62333. var y = pos[i + 1] + minY;
  62334. if (!matrix[x]) {
  62335. matrix[x] = [];
  62336. }
  62337. if (!matrix[x][z]) {
  62338. matrix[x][z] = y;
  62339. }
  62340. matrix[x][z] = Math.max(y, matrix[x][z]);
  62341. }
  62342. for (var x = 0; x <= arraySize; ++x) {
  62343. if (!matrix[x]) {
  62344. var loc = 1;
  62345. while (!matrix[(x + loc) % arraySize]) {
  62346. loc++;
  62347. }
  62348. matrix[x] = matrix[(x + loc) % arraySize].slice();
  62349. //console.log("missing x", x);
  62350. }
  62351. for (var z = 0; z <= arraySize; ++z) {
  62352. if (!matrix[x][z]) {
  62353. var loc = 1;
  62354. var newValue;
  62355. while (newValue === undefined) {
  62356. newValue = matrix[x][(z + loc++) % arraySize];
  62357. }
  62358. matrix[x][z] = newValue;
  62359. }
  62360. }
  62361. }
  62362. var shape = new CANNON.Heightfield(matrix, {
  62363. elementSize: elementSize
  62364. });
  62365. //For future reference, needed for body transformation
  62366. shape.minY = minY;
  62367. return shape;
  62368. };
  62369. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  62370. var object = impostor.object;
  62371. //make sure it is updated...
  62372. object.computeWorldMatrix && object.computeWorldMatrix(true);
  62373. // The delta between the mesh position and the mesh bounding box center
  62374. var center = impostor.getObjectCenter();
  62375. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  62376. this._tmpPosition.copyFrom(center);
  62377. var quaternion = object.rotationQuaternion;
  62378. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  62379. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  62380. //-90 DEG in X, precalculated
  62381. quaternion = quaternion.multiply(this._minus90X);
  62382. //Invert! (Precalculated, 90 deg in X)
  62383. //No need to clone. this will never change.
  62384. impostor.setDeltaRotation(this._plus90X);
  62385. }
  62386. //If it is a heightfield, if should be centered.
  62387. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  62388. var mesh = object;
  62389. //calculate the correct body position:
  62390. var rotationQuaternion = mesh.rotationQuaternion;
  62391. mesh.rotationQuaternion = this._tmpUnityRotation;
  62392. mesh.computeWorldMatrix(true);
  62393. //get original center with no rotation
  62394. var c = center.clone();
  62395. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  62396. //rotation is back
  62397. mesh.rotationQuaternion = rotationQuaternion;
  62398. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  62399. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  62400. mesh.setPivotMatrix(p);
  62401. mesh.computeWorldMatrix(true);
  62402. //calculate the translation
  62403. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  62404. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  62405. //add it inverted to the delta
  62406. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  62407. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  62408. mesh.setPivotMatrix(oldPivot);
  62409. mesh.computeWorldMatrix(true);
  62410. }
  62411. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  62412. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  62413. this._tmpPosition.copyFrom(object.position);
  62414. }
  62415. impostor.setDeltaPosition(this._tmpDeltaPosition);
  62416. //Now update the impostor object
  62417. impostor.physicsBody.position.copy(this._tmpPosition);
  62418. impostor.physicsBody.quaternion.copy(quaternion);
  62419. };
  62420. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  62421. impostor.object.position.copyFrom(impostor.physicsBody.position);
  62422. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  62423. };
  62424. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  62425. impostor.physicsBody.position.copy(newPosition);
  62426. impostor.physicsBody.quaternion.copy(newRotation);
  62427. };
  62428. CannonJSPlugin.prototype.isSupported = function () {
  62429. return window.CANNON !== undefined;
  62430. };
  62431. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  62432. impostor.physicsBody.velocity.copy(velocity);
  62433. };
  62434. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  62435. impostor.physicsBody.angularVelocity.copy(velocity);
  62436. };
  62437. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  62438. var v = impostor.physicsBody.velocity;
  62439. if (!v)
  62440. return null;
  62441. return new BABYLON.Vector3(v.x, v.y, v.z);
  62442. };
  62443. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  62444. var v = impostor.physicsBody.angularVelocity;
  62445. if (!v)
  62446. return null;
  62447. return new BABYLON.Vector3(v.x, v.y, v.z);
  62448. };
  62449. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  62450. impostor.physicsBody.mass = mass;
  62451. impostor.physicsBody.updateMassProperties();
  62452. };
  62453. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  62454. return impostor.physicsBody.mass;
  62455. };
  62456. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  62457. return impostor.physicsBody.material.friction;
  62458. };
  62459. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  62460. impostor.physicsBody.material.friction = friction;
  62461. };
  62462. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  62463. return impostor.physicsBody.material.restitution;
  62464. };
  62465. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  62466. impostor.physicsBody.material.restitution = restitution;
  62467. };
  62468. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  62469. impostor.physicsBody.sleep();
  62470. };
  62471. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  62472. impostor.physicsBody.wakeUp();
  62473. };
  62474. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  62475. joint.physicsJoint.distance = maxDistance;
  62476. };
  62477. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  62478. if (!motorIndex) {
  62479. joint.physicsJoint.enableMotor();
  62480. }
  62481. };
  62482. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  62483. if (!motorIndex) {
  62484. joint.physicsJoint.disableMotor();
  62485. }
  62486. };
  62487. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  62488. if (!motorIndex) {
  62489. joint.physicsJoint.enableMotor();
  62490. joint.physicsJoint.setMotorSpeed(speed);
  62491. if (maxForce) {
  62492. this.setLimit(joint, maxForce);
  62493. }
  62494. }
  62495. };
  62496. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  62497. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  62498. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  62499. };
  62500. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  62501. var body = impostor.physicsBody;
  62502. mesh.position.x = body.position.x;
  62503. mesh.position.y = body.position.y;
  62504. mesh.position.z = body.position.z;
  62505. mesh.rotationQuaternion.x = body.quaternion.x;
  62506. mesh.rotationQuaternion.y = body.quaternion.y;
  62507. mesh.rotationQuaternion.z = body.quaternion.z;
  62508. mesh.rotationQuaternion.w = body.quaternion.w;
  62509. };
  62510. CannonJSPlugin.prototype.getRadius = function (impostor) {
  62511. var shape = impostor.physicsBody.shapes[0];
  62512. return shape.boundingSphereRadius;
  62513. };
  62514. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  62515. var shape = impostor.physicsBody.shapes[0];
  62516. result.x = shape.halfExtents.x * 2;
  62517. result.y = shape.halfExtents.y * 2;
  62518. result.z = shape.halfExtents.z * 2;
  62519. };
  62520. CannonJSPlugin.prototype.dispose = function () {
  62521. };
  62522. return CannonJSPlugin;
  62523. }());
  62524. BABYLON.CannonJSPlugin = CannonJSPlugin;
  62525. })(BABYLON || (BABYLON = {}));
  62526. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  62527. var BABYLON;
  62528. (function (BABYLON) {
  62529. var OimoJSPlugin = (function () {
  62530. function OimoJSPlugin(iterations) {
  62531. this.name = "OimoJSPlugin";
  62532. this._tmpImpostorsArray = [];
  62533. this._tmpPositionVector = BABYLON.Vector3.Zero();
  62534. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  62535. this.world.worldscale(1);
  62536. this.world.clear();
  62537. //making sure no stats are calculated
  62538. this.world.isNoStat = true;
  62539. }
  62540. OimoJSPlugin.prototype.setGravity = function (gravity) {
  62541. this.world.gravity.copy(gravity);
  62542. };
  62543. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  62544. this.world.timeStep = timeStep;
  62545. };
  62546. OimoJSPlugin.prototype.getTimeStep = function () {
  62547. return this.world.timeStep;
  62548. };
  62549. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  62550. var _this = this;
  62551. impostors.forEach(function (impostor) {
  62552. impostor.beforeStep();
  62553. });
  62554. this.world.step();
  62555. impostors.forEach(function (impostor) {
  62556. impostor.afterStep();
  62557. //update the ordered impostors array
  62558. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  62559. });
  62560. //check for collisions
  62561. var contact = this.world.contacts;
  62562. while (contact !== null) {
  62563. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  62564. contact = contact.next;
  62565. continue;
  62566. }
  62567. //is this body colliding with any other? get the impostor
  62568. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  62569. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  62570. if (!mainImpostor || !collidingImpostor) {
  62571. contact = contact.next;
  62572. continue;
  62573. }
  62574. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  62575. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  62576. contact = contact.next;
  62577. }
  62578. };
  62579. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  62580. var mass = impostor.physicsBody.massInfo.mass;
  62581. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  62582. };
  62583. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  62584. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  62585. this.applyImpulse(impostor, force, contactPoint);
  62586. };
  62587. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  62588. var _this = this;
  62589. //parent-child relationship. Does this impostor has a parent impostor?
  62590. if (impostor.parent) {
  62591. if (impostor.physicsBody) {
  62592. this.removePhysicsBody(impostor);
  62593. //TODO is that needed?
  62594. impostor.forceUpdate();
  62595. }
  62596. return;
  62597. }
  62598. if (impostor.isBodyInitRequired()) {
  62599. var bodyConfig = {
  62600. name: impostor.uniqueId,
  62601. //Oimo must have mass, also for static objects.
  62602. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  62603. size: [],
  62604. type: [],
  62605. pos: [],
  62606. rot: [],
  62607. move: impostor.getParam("mass") !== 0,
  62608. //Supporting older versions of Oimo
  62609. world: this.world
  62610. };
  62611. var impostors = [impostor];
  62612. var addToArray = function (parent) {
  62613. if (!parent.getChildMeshes)
  62614. return;
  62615. parent.getChildMeshes().forEach(function (m) {
  62616. if (m.physicsImpostor) {
  62617. impostors.push(m.physicsImpostor);
  62618. m.physicsImpostor._init();
  62619. }
  62620. });
  62621. };
  62622. addToArray(impostor.object);
  62623. var checkWithEpsilon_1 = function (value) {
  62624. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  62625. };
  62626. impostors.forEach(function (i) {
  62627. //get the correct bounding box
  62628. var oldQuaternion = i.object.rotationQuaternion;
  62629. var rot = new OIMO.Euler().setFromQuaternion({
  62630. x: impostor.object.rotationQuaternion.x,
  62631. y: impostor.object.rotationQuaternion.y,
  62632. z: impostor.object.rotationQuaternion.z,
  62633. s: impostor.object.rotationQuaternion.w
  62634. });
  62635. var extendSize = i.getObjectExtendSize();
  62636. if (i === impostor) {
  62637. var center = impostor.getObjectCenter();
  62638. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  62639. //Can also use Array.prototype.push.apply
  62640. bodyConfig.pos.push(center.x);
  62641. bodyConfig.pos.push(center.y);
  62642. bodyConfig.pos.push(center.z);
  62643. //tmp solution
  62644. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  62645. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  62646. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  62647. }
  62648. else {
  62649. bodyConfig.pos.push(i.object.position.x);
  62650. bodyConfig.pos.push(i.object.position.y);
  62651. bodyConfig.pos.push(i.object.position.z);
  62652. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  62653. bodyConfig.rot.push(0);
  62654. bodyConfig.rot.push(0);
  62655. bodyConfig.rot.push(0);
  62656. }
  62657. // register mesh
  62658. switch (i.type) {
  62659. case BABYLON.PhysicsImpostor.ParticleImpostor:
  62660. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  62661. case BABYLON.PhysicsImpostor.SphereImpostor:
  62662. var radiusX = extendSize.x;
  62663. var radiusY = extendSize.y;
  62664. var radiusZ = extendSize.z;
  62665. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  62666. bodyConfig.type.push('sphere');
  62667. //due to the way oimo works with compounds, add 3 times
  62668. bodyConfig.size.push(size);
  62669. bodyConfig.size.push(size);
  62670. bodyConfig.size.push(size);
  62671. break;
  62672. case BABYLON.PhysicsImpostor.CylinderImpostor:
  62673. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  62674. var sizeY = checkWithEpsilon_1(extendSize.y);
  62675. bodyConfig.type.push('cylinder');
  62676. bodyConfig.size.push(sizeX);
  62677. bodyConfig.size.push(sizeY);
  62678. //due to the way oimo works with compounds, add one more value.
  62679. bodyConfig.size.push(sizeY);
  62680. break;
  62681. case BABYLON.PhysicsImpostor.PlaneImpostor:
  62682. case BABYLON.PhysicsImpostor.BoxImpostor:
  62683. default:
  62684. var sizeX = checkWithEpsilon_1(extendSize.x);
  62685. var sizeY = checkWithEpsilon_1(extendSize.y);
  62686. var sizeZ = checkWithEpsilon_1(extendSize.z);
  62687. bodyConfig.type.push('box');
  62688. bodyConfig.size.push(sizeX);
  62689. bodyConfig.size.push(sizeY);
  62690. bodyConfig.size.push(sizeZ);
  62691. break;
  62692. }
  62693. //actually not needed, but hey...
  62694. i.object.rotationQuaternion = oldQuaternion;
  62695. });
  62696. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  62697. }
  62698. else {
  62699. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  62700. }
  62701. impostor.setDeltaPosition(this._tmpPositionVector);
  62702. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  62703. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  62704. };
  62705. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  62706. //impostor.physicsBody.dispose();
  62707. //Same as : (older oimo versions)
  62708. this.world.removeRigidBody(impostor.physicsBody);
  62709. };
  62710. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  62711. var mainBody = impostorJoint.mainImpostor.physicsBody;
  62712. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  62713. if (!mainBody || !connectedBody) {
  62714. return;
  62715. }
  62716. var jointData = impostorJoint.joint.jointData;
  62717. var options = jointData.nativeParams || {};
  62718. var type;
  62719. var nativeJointData = {
  62720. body1: mainBody,
  62721. body2: connectedBody,
  62722. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  62723. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  62724. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  62725. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  62726. min: options.min,
  62727. max: options.max,
  62728. collision: options.collision || jointData.collision,
  62729. spring: options.spring,
  62730. //supporting older version of Oimo
  62731. world: this.world
  62732. };
  62733. switch (impostorJoint.joint.type) {
  62734. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  62735. type = "jointBall";
  62736. break;
  62737. case BABYLON.PhysicsJoint.SpringJoint:
  62738. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  62739. var springData = jointData;
  62740. nativeJointData.min = springData.length || nativeJointData.min;
  62741. //Max should also be set, just make sure it is at least min
  62742. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  62743. case BABYLON.PhysicsJoint.DistanceJoint:
  62744. type = "jointDistance";
  62745. nativeJointData.max = jointData.maxDistance;
  62746. break;
  62747. case BABYLON.PhysicsJoint.PrismaticJoint:
  62748. type = "jointPrisme";
  62749. break;
  62750. case BABYLON.PhysicsJoint.SliderJoint:
  62751. type = "jointSlide";
  62752. break;
  62753. case BABYLON.PhysicsJoint.WheelJoint:
  62754. type = "jointWheel";
  62755. break;
  62756. case BABYLON.PhysicsJoint.HingeJoint:
  62757. default:
  62758. type = "jointHinge";
  62759. break;
  62760. }
  62761. nativeJointData.type = type;
  62762. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  62763. };
  62764. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  62765. //Bug in Oimo prevents us from disposing a joint in the playground
  62766. //joint.joint.physicsJoint.dispose();
  62767. //So we will bruteforce it!
  62768. try {
  62769. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  62770. }
  62771. catch (e) {
  62772. BABYLON.Tools.Warn(e);
  62773. }
  62774. };
  62775. OimoJSPlugin.prototype.isSupported = function () {
  62776. return OIMO !== undefined;
  62777. };
  62778. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  62779. if (!impostor.physicsBody.sleeping) {
  62780. //TODO check that
  62781. if (impostor.physicsBody.shapes.next) {
  62782. var parentShape = this._getLastShape(impostor.physicsBody);
  62783. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  62784. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  62785. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  62786. }
  62787. else {
  62788. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  62789. }
  62790. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  62791. impostor.object.rotationQuaternion.normalize();
  62792. }
  62793. };
  62794. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  62795. var body = impostor.physicsBody;
  62796. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  62797. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  62798. body.syncShapes();
  62799. body.awake();
  62800. };
  62801. OimoJSPlugin.prototype._getLastShape = function (body) {
  62802. var lastShape = body.shapes;
  62803. while (lastShape.next) {
  62804. lastShape = lastShape.next;
  62805. }
  62806. return lastShape;
  62807. };
  62808. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  62809. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  62810. };
  62811. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  62812. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  62813. };
  62814. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  62815. var v = impostor.physicsBody.linearVelocity;
  62816. if (!v)
  62817. return null;
  62818. return new BABYLON.Vector3(v.x, v.y, v.z);
  62819. };
  62820. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  62821. var v = impostor.physicsBody.angularVelocity;
  62822. if (!v)
  62823. return null;
  62824. return new BABYLON.Vector3(v.x, v.y, v.z);
  62825. };
  62826. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  62827. var staticBody = mass === 0;
  62828. //this will actually set the body's density and not its mass.
  62829. //But this is how oimo treats the mass variable.
  62830. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  62831. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  62832. };
  62833. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  62834. return impostor.physicsBody.shapes.density;
  62835. };
  62836. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  62837. return impostor.physicsBody.shapes.friction;
  62838. };
  62839. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  62840. impostor.physicsBody.shapes.friction = friction;
  62841. };
  62842. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  62843. return impostor.physicsBody.shapes.restitution;
  62844. };
  62845. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  62846. impostor.physicsBody.shapes.restitution = restitution;
  62847. };
  62848. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  62849. impostor.physicsBody.sleep();
  62850. };
  62851. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  62852. impostor.physicsBody.awake();
  62853. };
  62854. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  62855. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  62856. if (minDistance !== void 0) {
  62857. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  62858. }
  62859. };
  62860. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  62861. //TODO separate rotational and transational motors.
  62862. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  62863. if (motor) {
  62864. motor.setMotor(speed, maxForce);
  62865. }
  62866. };
  62867. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  62868. //TODO separate rotational and transational motors.
  62869. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  62870. if (motor) {
  62871. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  62872. }
  62873. };
  62874. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  62875. var body = impostor.physicsBody;
  62876. mesh.position.x = body.position.x;
  62877. mesh.position.y = body.position.y;
  62878. mesh.position.z = body.position.z;
  62879. mesh.rotationQuaternion.x = body.orientation.x;
  62880. mesh.rotationQuaternion.y = body.orientation.y;
  62881. mesh.rotationQuaternion.z = body.orientation.z;
  62882. mesh.rotationQuaternion.w = body.orientation.s;
  62883. };
  62884. OimoJSPlugin.prototype.getRadius = function (impostor) {
  62885. return impostor.physicsBody.shapes.radius;
  62886. };
  62887. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  62888. var shape = impostor.physicsBody.shapes;
  62889. result.x = shape.halfWidth * 2;
  62890. result.y = shape.halfHeight * 2;
  62891. result.z = shape.halfDepth * 2;
  62892. };
  62893. OimoJSPlugin.prototype.dispose = function () {
  62894. this.world.clear();
  62895. };
  62896. return OimoJSPlugin;
  62897. }());
  62898. BABYLON.OimoJSPlugin = OimoJSPlugin;
  62899. })(BABYLON || (BABYLON = {}));
  62900. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  62901. var BABYLON;
  62902. (function (BABYLON) {
  62903. var Internals;
  62904. (function (Internals) {
  62905. /*
  62906. * Based on jsTGALoader - Javascript loader for TGA file
  62907. * By Vincent Thibault
  62908. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  62909. */
  62910. var TGATools = (function () {
  62911. function TGATools() {
  62912. }
  62913. TGATools.GetTGAHeader = function (data) {
  62914. var offset = 0;
  62915. var header = {
  62916. id_length: data[offset++],
  62917. colormap_type: data[offset++],
  62918. image_type: data[offset++],
  62919. colormap_index: data[offset++] | data[offset++] << 8,
  62920. colormap_length: data[offset++] | data[offset++] << 8,
  62921. colormap_size: data[offset++],
  62922. origin: [
  62923. data[offset++] | data[offset++] << 8,
  62924. data[offset++] | data[offset++] << 8
  62925. ],
  62926. width: data[offset++] | data[offset++] << 8,
  62927. height: data[offset++] | data[offset++] << 8,
  62928. pixel_size: data[offset++],
  62929. flags: data[offset++]
  62930. };
  62931. return header;
  62932. };
  62933. TGATools.UploadContent = function (gl, data) {
  62934. // Not enough data to contain header ?
  62935. if (data.length < 19) {
  62936. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  62937. return;
  62938. }
  62939. // Read Header
  62940. var offset = 18;
  62941. var header = TGATools.GetTGAHeader(data);
  62942. // Assume it's a valid Targa file.
  62943. if (header.id_length + offset > data.length) {
  62944. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  62945. return;
  62946. }
  62947. // Skip not needed data
  62948. offset += header.id_length;
  62949. var use_rle = false;
  62950. var use_pal = false;
  62951. var use_rgb = false;
  62952. var use_grey = false;
  62953. // Get some informations.
  62954. switch (header.image_type) {
  62955. case TGATools._TYPE_RLE_INDEXED:
  62956. use_rle = true;
  62957. case TGATools._TYPE_INDEXED:
  62958. use_pal = true;
  62959. break;
  62960. case TGATools._TYPE_RLE_RGB:
  62961. use_rle = true;
  62962. case TGATools._TYPE_RGB:
  62963. use_rgb = true;
  62964. break;
  62965. case TGATools._TYPE_RLE_GREY:
  62966. use_rle = true;
  62967. case TGATools._TYPE_GREY:
  62968. use_grey = true;
  62969. break;
  62970. }
  62971. var pixel_data;
  62972. var numAlphaBits = header.flags & 0xf;
  62973. var pixel_size = header.pixel_size >> 3;
  62974. var pixel_total = header.width * header.height * pixel_size;
  62975. // Read palettes
  62976. var palettes;
  62977. if (use_pal) {
  62978. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  62979. }
  62980. // Read LRE
  62981. if (use_rle) {
  62982. pixel_data = new Uint8Array(pixel_total);
  62983. var c, count, i;
  62984. var localOffset = 0;
  62985. var pixels = new Uint8Array(pixel_size);
  62986. while (offset < pixel_total && localOffset < pixel_total) {
  62987. c = data[offset++];
  62988. count = (c & 0x7f) + 1;
  62989. // RLE pixels
  62990. if (c & 0x80) {
  62991. // Bind pixel tmp array
  62992. for (i = 0; i < pixel_size; ++i) {
  62993. pixels[i] = data[offset++];
  62994. }
  62995. // Copy pixel array
  62996. for (i = 0; i < count; ++i) {
  62997. pixel_data.set(pixels, localOffset + i * pixel_size);
  62998. }
  62999. localOffset += pixel_size * count;
  63000. }
  63001. else {
  63002. count *= pixel_size;
  63003. for (i = 0; i < count; ++i) {
  63004. pixel_data[localOffset + i] = data[offset++];
  63005. }
  63006. localOffset += count;
  63007. }
  63008. }
  63009. }
  63010. else {
  63011. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  63012. }
  63013. // Load to texture
  63014. var x_start, y_start, x_step, y_step, y_end, x_end;
  63015. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  63016. default:
  63017. case TGATools._ORIGIN_UL:
  63018. x_start = 0;
  63019. x_step = 1;
  63020. x_end = header.width;
  63021. y_start = 0;
  63022. y_step = 1;
  63023. y_end = header.height;
  63024. break;
  63025. case TGATools._ORIGIN_BL:
  63026. x_start = 0;
  63027. x_step = 1;
  63028. x_end = header.width;
  63029. y_start = header.height - 1;
  63030. y_step = -1;
  63031. y_end = -1;
  63032. break;
  63033. case TGATools._ORIGIN_UR:
  63034. x_start = header.width - 1;
  63035. x_step = -1;
  63036. x_end = -1;
  63037. y_start = 0;
  63038. y_step = 1;
  63039. y_end = header.height;
  63040. break;
  63041. case TGATools._ORIGIN_BR:
  63042. x_start = header.width - 1;
  63043. x_step = -1;
  63044. x_end = -1;
  63045. y_start = header.height - 1;
  63046. y_step = -1;
  63047. y_end = -1;
  63048. break;
  63049. }
  63050. // Load the specify method
  63051. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  63052. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  63053. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  63054. };
  63055. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63056. var image = pixel_data, colormap = palettes;
  63057. var width = header.width, height = header.height;
  63058. var color, i = 0, x, y;
  63059. var imageData = new Uint8Array(width * height * 4);
  63060. for (y = y_start; y !== y_end; y += y_step) {
  63061. for (x = x_start; x !== x_end; x += x_step, i++) {
  63062. color = image[i];
  63063. imageData[(x + width * y) * 4 + 3] = 255;
  63064. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  63065. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  63066. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  63067. }
  63068. }
  63069. return imageData;
  63070. };
  63071. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63072. var image = pixel_data;
  63073. var width = header.width, height = header.height;
  63074. var color, i = 0, x, y;
  63075. var imageData = new Uint8Array(width * height * 4);
  63076. for (y = y_start; y !== y_end; y += y_step) {
  63077. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  63078. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  63079. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  63080. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  63081. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  63082. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  63083. }
  63084. }
  63085. return imageData;
  63086. };
  63087. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63088. var image = pixel_data;
  63089. var width = header.width, height = header.height;
  63090. var i = 0, x, y;
  63091. var imageData = new Uint8Array(width * height * 4);
  63092. for (y = y_start; y !== y_end; y += y_step) {
  63093. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  63094. imageData[(x + width * y) * 4 + 3] = 255;
  63095. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  63096. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  63097. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  63098. }
  63099. }
  63100. return imageData;
  63101. };
  63102. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63103. var image = pixel_data;
  63104. var width = header.width, height = header.height;
  63105. var i = 0, x, y;
  63106. var imageData = new Uint8Array(width * height * 4);
  63107. for (y = y_start; y !== y_end; y += y_step) {
  63108. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  63109. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  63110. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  63111. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  63112. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  63113. }
  63114. }
  63115. return imageData;
  63116. };
  63117. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63118. var image = pixel_data;
  63119. var width = header.width, height = header.height;
  63120. var color, i = 0, x, y;
  63121. var imageData = new Uint8Array(width * height * 4);
  63122. for (y = y_start; y !== y_end; y += y_step) {
  63123. for (x = x_start; x !== x_end; x += x_step, i++) {
  63124. color = image[i];
  63125. imageData[(x + width * y) * 4 + 0] = color;
  63126. imageData[(x + width * y) * 4 + 1] = color;
  63127. imageData[(x + width * y) * 4 + 2] = color;
  63128. imageData[(x + width * y) * 4 + 3] = 255;
  63129. }
  63130. }
  63131. return imageData;
  63132. };
  63133. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63134. var image = pixel_data;
  63135. var width = header.width, height = header.height;
  63136. var i = 0, x, y;
  63137. var imageData = new Uint8Array(width * height * 4);
  63138. for (y = y_start; y !== y_end; y += y_step) {
  63139. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  63140. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  63141. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  63142. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  63143. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  63144. }
  63145. }
  63146. return imageData;
  63147. };
  63148. TGATools._TYPE_NO_DATA = 0;
  63149. TGATools._TYPE_INDEXED = 1;
  63150. TGATools._TYPE_RGB = 2;
  63151. TGATools._TYPE_GREY = 3;
  63152. TGATools._TYPE_RLE_INDEXED = 9;
  63153. TGATools._TYPE_RLE_RGB = 10;
  63154. TGATools._TYPE_RLE_GREY = 11;
  63155. TGATools._ORIGIN_MASK = 0x30;
  63156. TGATools._ORIGIN_SHIFT = 0x04;
  63157. TGATools._ORIGIN_BL = 0x00;
  63158. TGATools._ORIGIN_BR = 0x01;
  63159. TGATools._ORIGIN_UL = 0x02;
  63160. TGATools._ORIGIN_UR = 0x03;
  63161. return TGATools;
  63162. }());
  63163. Internals.TGATools = TGATools;
  63164. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63165. })(BABYLON || (BABYLON = {}));
  63166. //# sourceMappingURL=babylon.tga.js.map
  63167. var BABYLON;
  63168. (function (BABYLON) {
  63169. var Internals;
  63170. (function (Internals) {
  63171. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  63172. // All values and structures referenced from:
  63173. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  63174. var DDS_MAGIC = 0x20534444;
  63175. 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;
  63176. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  63177. 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;
  63178. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  63179. function FourCCToInt32(value) {
  63180. return value.charCodeAt(0) +
  63181. (value.charCodeAt(1) << 8) +
  63182. (value.charCodeAt(2) << 16) +
  63183. (value.charCodeAt(3) << 24);
  63184. }
  63185. function Int32ToFourCC(value) {
  63186. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  63187. }
  63188. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  63189. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  63190. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  63191. var FOURCC_DX10 = FourCCToInt32("DX10");
  63192. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  63193. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  63194. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  63195. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  63196. var headerLengthInt = 31; // The header length in 32 bit ints
  63197. // Offsets into the header array
  63198. var off_magic = 0;
  63199. var off_size = 1;
  63200. var off_flags = 2;
  63201. var off_height = 3;
  63202. var off_width = 4;
  63203. var off_mipmapCount = 7;
  63204. var off_pfFlags = 20;
  63205. var off_pfFourCC = 21;
  63206. var off_RGBbpp = 22;
  63207. var off_RMask = 23;
  63208. var off_GMask = 24;
  63209. var off_BMask = 25;
  63210. var off_AMask = 26;
  63211. var off_caps1 = 27;
  63212. var off_caps2 = 28;
  63213. var off_caps3 = 29;
  63214. var off_caps4 = 30;
  63215. var off_dxgiFormat = 32;
  63216. ;
  63217. var DDSTools = (function () {
  63218. function DDSTools() {
  63219. }
  63220. DDSTools.GetDDSInfo = function (arrayBuffer) {
  63221. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  63222. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  63223. var mipmapCount = 1;
  63224. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  63225. mipmapCount = Math.max(1, header[off_mipmapCount]);
  63226. }
  63227. var fourCC = header[off_pfFourCC];
  63228. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  63229. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63230. switch (fourCC) {
  63231. case FOURCC_D3DFMT_R16G16B16A16F:
  63232. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63233. break;
  63234. case FOURCC_D3DFMT_R32G32B32A32F:
  63235. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63236. break;
  63237. case FOURCC_DX10:
  63238. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  63239. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63240. break;
  63241. }
  63242. }
  63243. return {
  63244. width: header[off_width],
  63245. height: header[off_height],
  63246. mipmapCount: mipmapCount,
  63247. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  63248. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  63249. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  63250. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  63251. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  63252. dxgiFormat: dxgiFormat,
  63253. textureType: textureType
  63254. };
  63255. };
  63256. DDSTools._ToHalfFloat = function (value) {
  63257. if (!DDSTools._FloatView) {
  63258. DDSTools._FloatView = new Float32Array(1);
  63259. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  63260. }
  63261. DDSTools._FloatView[0] = value;
  63262. var x = DDSTools._Int32View[0];
  63263. var bits = (x >> 16) & 0x8000; /* Get the sign */
  63264. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  63265. var e = (x >> 23) & 0xff; /* Using int is faster here */
  63266. /* If zero, or denormal, or exponent underflows too much for a denormal
  63267. * half, return signed zero. */
  63268. if (e < 103) {
  63269. return bits;
  63270. }
  63271. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  63272. if (e > 142) {
  63273. bits |= 0x7c00;
  63274. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  63275. * not Inf, so make sure we set one mantissa bit too. */
  63276. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  63277. return bits;
  63278. }
  63279. /* If exponent underflows but not too much, return a denormal */
  63280. if (e < 113) {
  63281. m |= 0x0800;
  63282. /* Extra rounding may overflow and set mantissa to 0 and exponent
  63283. * to 1, which is OK. */
  63284. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  63285. return bits;
  63286. }
  63287. bits |= ((e - 112) << 10) | (m >> 1);
  63288. bits += m & 1;
  63289. return bits;
  63290. };
  63291. DDSTools._FromHalfFloat = function (value) {
  63292. var s = (value & 0x8000) >> 15;
  63293. var e = (value & 0x7C00) >> 10;
  63294. var f = value & 0x03FF;
  63295. if (e === 0) {
  63296. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  63297. }
  63298. else if (e == 0x1F) {
  63299. return f ? NaN : ((s ? -1 : 1) * Infinity);
  63300. }
  63301. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  63302. };
  63303. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63304. var destArray = new Float32Array(dataLength);
  63305. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63306. var index = 0;
  63307. for (var y = 0; y < height; y++) {
  63308. for (var x = 0; x < width; x++) {
  63309. var srcPos = (x + y * width) * 4;
  63310. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  63311. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  63312. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  63313. if (DDSTools.StoreLODInAlphaChannel) {
  63314. destArray[index + 3] = lod;
  63315. }
  63316. else {
  63317. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  63318. }
  63319. index += 4;
  63320. }
  63321. }
  63322. return destArray;
  63323. };
  63324. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63325. if (DDSTools.StoreLODInAlphaChannel) {
  63326. var destArray = new Uint16Array(dataLength);
  63327. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63328. var index = 0;
  63329. for (var y = 0; y < height; y++) {
  63330. for (var x = 0; x < width; x++) {
  63331. var srcPos = (x + y * width) * 4;
  63332. destArray[index] = srcData[srcPos];
  63333. destArray[index + 1] = srcData[srcPos + 1];
  63334. destArray[index + 2] = srcData[srcPos + 2];
  63335. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  63336. index += 4;
  63337. }
  63338. }
  63339. return destArray;
  63340. }
  63341. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  63342. };
  63343. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63344. if (DDSTools.StoreLODInAlphaChannel) {
  63345. var destArray = new Float32Array(dataLength);
  63346. var srcData = new Float32Array(arrayBuffer, dataOffset);
  63347. var index = 0;
  63348. for (var y = 0; y < height; y++) {
  63349. for (var x = 0; x < width; x++) {
  63350. var srcPos = (x + y * width) * 4;
  63351. destArray[index] = srcData[srcPos];
  63352. destArray[index + 1] = srcData[srcPos + 1];
  63353. destArray[index + 2] = srcData[srcPos + 2];
  63354. destArray[index + 3] = lod;
  63355. index += 4;
  63356. }
  63357. }
  63358. return destArray;
  63359. }
  63360. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  63361. };
  63362. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63363. var destArray = new Uint8Array(dataLength);
  63364. var srcData = new Float32Array(arrayBuffer, dataOffset);
  63365. var index = 0;
  63366. for (var y = 0; y < height; y++) {
  63367. for (var x = 0; x < width; x++) {
  63368. var srcPos = (x + y * width) * 4;
  63369. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  63370. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  63371. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  63372. if (DDSTools.StoreLODInAlphaChannel) {
  63373. destArray[index + 3] = lod;
  63374. }
  63375. else {
  63376. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  63377. }
  63378. index += 4;
  63379. }
  63380. }
  63381. return destArray;
  63382. };
  63383. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63384. var destArray = new Uint8Array(dataLength);
  63385. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63386. var index = 0;
  63387. for (var y = 0; y < height; y++) {
  63388. for (var x = 0; x < width; x++) {
  63389. var srcPos = (x + y * width) * 4;
  63390. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  63391. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  63392. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  63393. if (DDSTools.StoreLODInAlphaChannel) {
  63394. destArray[index + 3] = lod;
  63395. }
  63396. else {
  63397. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  63398. }
  63399. index += 4;
  63400. }
  63401. }
  63402. return destArray;
  63403. };
  63404. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63405. var byteArray = new Uint8Array(dataLength);
  63406. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63407. var index = 0;
  63408. for (var y = 0; y < height; y++) {
  63409. for (var x = 0; x < width; x++) {
  63410. var srcPos = (x + y * width) * 4;
  63411. byteArray[index] = srcData[srcPos + 2];
  63412. byteArray[index + 1] = srcData[srcPos + 1];
  63413. byteArray[index + 2] = srcData[srcPos];
  63414. byteArray[index + 3] = srcData[srcPos + 3];
  63415. index += 4;
  63416. }
  63417. }
  63418. return byteArray;
  63419. };
  63420. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63421. var byteArray = new Uint8Array(dataLength);
  63422. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63423. var index = 0;
  63424. for (var y = 0; y < height; y++) {
  63425. for (var x = 0; x < width; x++) {
  63426. var srcPos = (x + y * width) * 3;
  63427. byteArray[index] = srcData[srcPos + 2];
  63428. byteArray[index + 1] = srcData[srcPos + 1];
  63429. byteArray[index + 2] = srcData[srcPos];
  63430. index += 3;
  63431. }
  63432. }
  63433. return byteArray;
  63434. };
  63435. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63436. var byteArray = new Uint8Array(dataLength);
  63437. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63438. var index = 0;
  63439. for (var y = 0; y < height; y++) {
  63440. for (var x = 0; x < width; x++) {
  63441. var srcPos = (x + y * width);
  63442. byteArray[index] = srcData[srcPos];
  63443. index++;
  63444. }
  63445. }
  63446. return byteArray;
  63447. };
  63448. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  63449. if (lodIndex === void 0) { lodIndex = -1; }
  63450. var ext = engine.getCaps().s3tc;
  63451. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  63452. if (header[off_magic] != DDS_MAGIC) {
  63453. BABYLON.Tools.Error("Invalid magic number in DDS header");
  63454. return;
  63455. }
  63456. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  63457. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  63458. return;
  63459. }
  63460. if (info.isCompressed && !ext) {
  63461. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  63462. return;
  63463. }
  63464. var bpp = header[off_RGBbpp];
  63465. dataOffset = header[off_size] + 4;
  63466. var computeFormats = false;
  63467. if (info.isFourCC) {
  63468. fourCC = header[off_pfFourCC];
  63469. switch (fourCC) {
  63470. case FOURCC_DXT1:
  63471. blockBytes = 8;
  63472. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  63473. break;
  63474. case FOURCC_DXT3:
  63475. blockBytes = 16;
  63476. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  63477. break;
  63478. case FOURCC_DXT5:
  63479. blockBytes = 16;
  63480. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  63481. break;
  63482. case FOURCC_D3DFMT_R16G16B16A16F:
  63483. computeFormats = true;
  63484. break;
  63485. case FOURCC_D3DFMT_R32G32B32A32F:
  63486. computeFormats = true;
  63487. break;
  63488. case FOURCC_DX10:
  63489. // There is an additionnal header so dataOffset need to be changed
  63490. dataOffset += 5 * 4; // 5 uints
  63491. var supported = false;
  63492. switch (info.dxgiFormat) {
  63493. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  63494. computeFormats = true;
  63495. supported = true;
  63496. break;
  63497. case DXGI_FORMAT_B8G8R8X8_UNORM:
  63498. info.isRGB = true;
  63499. info.isFourCC = false;
  63500. bpp = 32;
  63501. supported = true;
  63502. break;
  63503. }
  63504. if (supported) {
  63505. break;
  63506. }
  63507. default:
  63508. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  63509. return;
  63510. }
  63511. }
  63512. if (computeFormats) {
  63513. format = engine._getWebGLTextureType(info.textureType);
  63514. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63515. }
  63516. mipmapCount = 1;
  63517. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  63518. mipmapCount = Math.max(1, header[off_mipmapCount]);
  63519. }
  63520. for (var face = 0; face < faces; face++) {
  63521. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  63522. width = header[off_width];
  63523. height = header[off_height];
  63524. for (mip = 0; mip < mipmapCount; ++mip) {
  63525. if (lodIndex === -1 || lodIndex === mip) {
  63526. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  63527. var i = (lodIndex === -1) ? mip : 0;
  63528. if (!info.isCompressed && info.isFourCC) {
  63529. dataLength = width * height * 4;
  63530. var floatArray;
  63531. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  63532. if (bpp === 128) {
  63533. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63534. }
  63535. else if (bpp === 64) {
  63536. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63537. }
  63538. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63539. format = engine._getWebGLTextureType(info.textureType);
  63540. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63541. }
  63542. else {
  63543. if (bpp === 128) {
  63544. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63545. }
  63546. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  63547. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63548. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63549. format = engine._getWebGLTextureType(info.textureType);
  63550. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63551. }
  63552. else {
  63553. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63554. }
  63555. }
  63556. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  63557. }
  63558. else if (info.isRGB) {
  63559. if (bpp === 24) {
  63560. dataLength = width * height * 3;
  63561. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63562. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  63563. }
  63564. else {
  63565. dataLength = width * height * 4;
  63566. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63567. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  63568. }
  63569. }
  63570. else if (info.isLuminance) {
  63571. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  63572. var unpaddedRowSize = width;
  63573. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  63574. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  63575. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63576. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  63577. }
  63578. else {
  63579. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  63580. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  63581. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  63582. }
  63583. }
  63584. dataOffset += width * height * (bpp / 8);
  63585. width *= 0.5;
  63586. height *= 0.5;
  63587. width = Math.max(1.0, width);
  63588. height = Math.max(1.0, height);
  63589. }
  63590. }
  63591. };
  63592. DDSTools.StoreLODInAlphaChannel = false;
  63593. return DDSTools;
  63594. }());
  63595. Internals.DDSTools = DDSTools;
  63596. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63597. })(BABYLON || (BABYLON = {}));
  63598. //# sourceMappingURL=babylon.dds.js.map
  63599. var BABYLON;
  63600. (function (BABYLON) {
  63601. var Internals;
  63602. (function (Internals) {
  63603. /**
  63604. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  63605. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  63606. */
  63607. var KhronosTextureContainer = (function () {
  63608. /**
  63609. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  63610. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  63611. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  63612. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  63613. */
  63614. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  63615. this.arrayBuffer = arrayBuffer;
  63616. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  63617. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  63618. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  63619. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  63620. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  63621. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  63622. BABYLON.Tools.Error("texture missing KTX identifier");
  63623. return;
  63624. }
  63625. // load the reset of the header in native 32 bit int
  63626. var header = new Int32Array(this.arrayBuffer, 12, 13);
  63627. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  63628. var oppositeEndianess = header[0] === 0x01020304;
  63629. // read all the header elements in order they exist in the file, without modification (sans endainness)
  63630. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  63631. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  63632. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  63633. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  63634. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  63635. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  63636. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  63637. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  63638. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  63639. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  63640. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  63641. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  63642. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  63643. if (this.glType !== 0) {
  63644. BABYLON.Tools.Error("only compressed formats currently supported");
  63645. return;
  63646. }
  63647. else {
  63648. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  63649. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  63650. }
  63651. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  63652. BABYLON.Tools.Error("only 2D textures currently supported");
  63653. return;
  63654. }
  63655. if (this.numberOfArrayElements !== 0) {
  63656. BABYLON.Tools.Error("texture arrays not currently supported");
  63657. return;
  63658. }
  63659. if (this.numberOfFaces !== facesExpected) {
  63660. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  63661. return;
  63662. }
  63663. // we now have a completely validated file, so could use existence of loadType as success
  63664. // would need to make this more elaborate & adjust checks above to support more than one load type
  63665. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  63666. }
  63667. // not as fast hardware based, but will probably never need to use
  63668. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  63669. return ((val & 0xFF) << 24)
  63670. | ((val & 0xFF00) << 8)
  63671. | ((val >> 8) & 0xFF00)
  63672. | ((val >> 24) & 0xFF);
  63673. };
  63674. /**
  63675. * It is assumed that the texture has already been created & is currently bound
  63676. */
  63677. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  63678. switch (this.loadType) {
  63679. case KhronosTextureContainer.COMPRESSED_2D:
  63680. this._upload2DCompressedLevels(gl, loadMipmaps);
  63681. break;
  63682. case KhronosTextureContainer.TEX_2D:
  63683. case KhronosTextureContainer.COMPRESSED_3D:
  63684. case KhronosTextureContainer.TEX_3D:
  63685. }
  63686. };
  63687. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  63688. // initialize width & height for level 1
  63689. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  63690. var width = this.pixelWidth;
  63691. var height = this.pixelHeight;
  63692. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  63693. for (var level = 0; level < mipmapCount; level++) {
  63694. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  63695. for (var face = 0; face < this.numberOfFaces; face++) {
  63696. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  63697. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  63698. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  63699. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  63700. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  63701. }
  63702. width = Math.max(1.0, width * 0.5);
  63703. height = Math.max(1.0, height * 0.5);
  63704. }
  63705. };
  63706. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  63707. // load types
  63708. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  63709. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  63710. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  63711. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  63712. return KhronosTextureContainer;
  63713. }());
  63714. Internals.KhronosTextureContainer = KhronosTextureContainer;
  63715. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63716. })(BABYLON || (BABYLON = {}));
  63717. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  63718. var BABYLON;
  63719. (function (BABYLON) {
  63720. var DynamicFloatArrayElementInfo = (function () {
  63721. function DynamicFloatArrayElementInfo() {
  63722. }
  63723. return DynamicFloatArrayElementInfo;
  63724. }());
  63725. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  63726. /**
  63727. * 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.
  63728. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  63729. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  63730. * 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.
  63731. * 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.
  63732. * 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".
  63733. */
  63734. var DynamicFloatArray = (function () {
  63735. /**
  63736. * Construct an instance of the dynamic float array
  63737. * @param stride size of one element in float (i.e. not bytes!)
  63738. * @param initialElementCount the number of available entries at construction
  63739. */
  63740. function DynamicFloatArray(stride, initialElementCount) {
  63741. this.compareValueOffset = null;
  63742. this.sortingAscending = true;
  63743. this._stride = stride;
  63744. this.buffer = new Float32Array(stride * initialElementCount);
  63745. this._lastUsed = 0;
  63746. this._firstFree = 0;
  63747. this._allEntries = new Array(initialElementCount);
  63748. this._freeEntries = new Array(initialElementCount);
  63749. for (var i = 0; i < initialElementCount; i++) {
  63750. var element = new DynamicFloatArrayElementInfo();
  63751. element.offset = i * stride;
  63752. this._allEntries[i] = element;
  63753. this._freeEntries[initialElementCount - i - 1] = element;
  63754. }
  63755. }
  63756. /**
  63757. * Allocate an element in the array.
  63758. * @return the element info instance that contains the offset into the main buffer of the element's location.
  63759. * Beware, this offset may change when you call pack()
  63760. */
  63761. DynamicFloatArray.prototype.allocElement = function () {
  63762. if (this._freeEntries.length === 0) {
  63763. this._growBuffer();
  63764. }
  63765. var el = this._freeEntries.pop();
  63766. this._lastUsed = Math.max(el.offset, this._lastUsed);
  63767. if (el.offset === this._firstFree) {
  63768. if (this._freeEntries.length > 0) {
  63769. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  63770. }
  63771. else {
  63772. this._firstFree += this._stride;
  63773. }
  63774. }
  63775. return el;
  63776. };
  63777. /**
  63778. * Free the element corresponding to the given element info
  63779. * @param elInfo the element that describe the allocated element
  63780. */
  63781. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  63782. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  63783. this._freeEntries.push(elInfo);
  63784. };
  63785. /**
  63786. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  63787. * 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().
  63788. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  63789. */
  63790. DynamicFloatArray.prototype.pack = function () {
  63791. // no free slot? no need to pack
  63792. if (this._freeEntries.length === 0) {
  63793. return this.buffer;
  63794. }
  63795. // If the buffer is already packed the last used will always be lower than the first free
  63796. // 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.
  63797. if (this._lastUsed < this._firstFree) {
  63798. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  63799. return elementsBuffer_1;
  63800. }
  63801. var s = this._stride;
  63802. // 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
  63803. var lastFree = new DynamicFloatArrayElementInfo();
  63804. lastFree.offset = this.totalElementCount * s;
  63805. this._freeEntries.push(lastFree);
  63806. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  63807. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  63808. var firstFreeSlotOffset = sortedFree[0].offset;
  63809. var freeZoneSize = 1;
  63810. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  63811. var prevOffset = sortedFree[0].offset;
  63812. for (var i = 1; i < sortedFree.length; i++) {
  63813. // 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
  63814. if (firstFreeSlotOffset >= occupiedZoneSize) {
  63815. break;
  63816. }
  63817. var curFree = sortedFree[i];
  63818. var curOffset = curFree.offset;
  63819. // Compute the distance between this offset and the previous
  63820. var distance = curOffset - prevOffset;
  63821. // If the distance is the stride size, they are adjacent, it good, move to the next
  63822. if (distance === s) {
  63823. // Free zone is one element bigger
  63824. ++freeZoneSize;
  63825. // as we're about to iterate to the next, the cur becomes the previous...
  63826. prevOffset = curOffset;
  63827. continue;
  63828. }
  63829. // Distance is bigger, which means there's x element between the previous free and this one
  63830. var usedRange = (distance / s) - 1;
  63831. // Two cases the free zone is smaller than the data to move or bigger
  63832. // Copy what can fit in the free zone
  63833. var curMoveOffset = curOffset - s;
  63834. var copyCount = Math.min(freeZoneSize, usedRange);
  63835. for (var j = 0; j < copyCount; j++) {
  63836. var freeI = firstFreeSlotOffset / s;
  63837. var curI = curMoveOffset / s;
  63838. var moveEl = sortedAll[curI];
  63839. this._moveElement(moveEl, firstFreeSlotOffset);
  63840. var replacedEl = sortedAll[freeI];
  63841. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  63842. replacedEl.offset = curMoveOffset;
  63843. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  63844. sortedAll[freeI] = moveEl;
  63845. sortedAll[curI] = replacedEl;
  63846. curMoveOffset -= s;
  63847. firstFreeSlotOffset += s;
  63848. }
  63849. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  63850. if (freeZoneSize <= usedRange) {
  63851. firstFreeSlotOffset = curMoveOffset + s;
  63852. freeZoneSize = 1 + copyCount;
  63853. }
  63854. else {
  63855. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  63856. }
  63857. // as we're about to iterate to the next, the cur becomes the previous...
  63858. prevOffset = curOffset;
  63859. }
  63860. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  63861. this._lastUsed = firstFreeSlotOffset - s;
  63862. this._firstFree = firstFreeSlotOffset;
  63863. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  63864. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  63865. this._allEntries = sortedAll;
  63866. return elementsBuffer;
  63867. };
  63868. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  63869. for (var i = 0; i < this._stride; i++) {
  63870. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  63871. }
  63872. element.offset = destOffset;
  63873. };
  63874. DynamicFloatArray.prototype._growBuffer = function () {
  63875. // Allocate the new buffer with 50% more entries, copy the content of the current one
  63876. var newElCount = Math.floor(this.totalElementCount * 1.5);
  63877. var newBuffer = new Float32Array(newElCount * this._stride);
  63878. newBuffer.set(this.buffer);
  63879. var curCount = this.totalElementCount;
  63880. var addedCount = newElCount - this.totalElementCount;
  63881. for (var i = 0; i < addedCount; i++) {
  63882. var element = new DynamicFloatArrayElementInfo();
  63883. element.offset = (curCount + i) * this.stride;
  63884. this._allEntries.push(element);
  63885. this._freeEntries[addedCount - i - 1] = element;
  63886. }
  63887. this._firstFree = curCount * this.stride;
  63888. this.buffer = newBuffer;
  63889. };
  63890. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  63891. /**
  63892. * Get the total count of entries that can fit in the current buffer
  63893. * @returns the elements count
  63894. */
  63895. get: function () {
  63896. return this._allEntries.length;
  63897. },
  63898. enumerable: true,
  63899. configurable: true
  63900. });
  63901. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  63902. /**
  63903. * Get the count of free entries that can still be allocated without resizing the buffer
  63904. * @returns the free elements count
  63905. */
  63906. get: function () {
  63907. return this._freeEntries.length;
  63908. },
  63909. enumerable: true,
  63910. configurable: true
  63911. });
  63912. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  63913. /**
  63914. * Get the count of allocated elements
  63915. * @returns the allocated elements count
  63916. */
  63917. get: function () {
  63918. return this._allEntries.length - this._freeEntries.length;
  63919. },
  63920. enumerable: true,
  63921. configurable: true
  63922. });
  63923. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  63924. /**
  63925. * Return the size of one element in float
  63926. * @returns the size in float
  63927. */
  63928. get: function () {
  63929. return this._stride;
  63930. },
  63931. enumerable: true,
  63932. configurable: true
  63933. });
  63934. DynamicFloatArray.prototype.sort = function () {
  63935. var _this = this;
  63936. if (!this.compareValueOffset) {
  63937. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  63938. }
  63939. var count = this.usedElementCount;
  63940. // Do we have to (re)create the sort table?
  63941. if (!this._sortTable || this._sortTable.length < count) {
  63942. // 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...
  63943. var newCount = Math.min(this.totalElementCount, count * 2);
  63944. this._sortTable = new Array(newCount);
  63945. }
  63946. if (!this._sortedTable || this._sortedTable.length !== count) {
  63947. this._sortedTable = new Array(count);
  63948. }
  63949. // Because, you know...
  63950. this.pack();
  63951. //let stride = this.stride;
  63952. //for (let i = 0; i < count; i++) {
  63953. // let si = this._sortTable[i];
  63954. // if (!si) {
  63955. // si = new SortInfo();
  63956. // this._sortTable[i] = si;
  63957. // }
  63958. // si.entry = this._allEntries[i];
  63959. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  63960. // si.swapedOffset = null;
  63961. // this._sortedTable[i] = si;
  63962. //}
  63963. var curOffset = 0;
  63964. var stride = this.stride;
  63965. for (var i = 0; i < count; i++, curOffset += stride) {
  63966. var si = this._sortTable[i];
  63967. if (!si) {
  63968. si = new SortInfo();
  63969. this._sortTable[i] = si;
  63970. }
  63971. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  63972. si.offset = curOffset;
  63973. si.swapedOffset = null;
  63974. this._sortedTable[i] = si;
  63975. }
  63976. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  63977. if (this.sortingAscending) {
  63978. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  63979. }
  63980. else {
  63981. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  63982. }
  63983. var swapElements = function (src, dst) {
  63984. for (var i = 0; i < stride; i++) {
  63985. var tps = _this.buffer[dst + i];
  63986. _this.buffer[dst + i] = _this.buffer[src + i];
  63987. _this.buffer[src + i] = tps;
  63988. }
  63989. };
  63990. // 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:
  63991. // 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),
  63992. // and I still want something with a good algorithm complexity.
  63993. // 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,
  63994. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  63995. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  63996. // 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
  63997. // until we find a SortInfo object without a swapedOffset which means we got the right location
  63998. // 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
  63999. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  64000. for (var i = 0; i < count; i++) {
  64001. // Get the element to move
  64002. var sourceSI = this._sortedTable[i];
  64003. var destSI = this._sortTable[i];
  64004. var sourceOff = sourceSI.offset;
  64005. // If the source changed location, find the new one
  64006. if (sourceSI.swapedOffset) {
  64007. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  64008. var curSI = sourceSI;
  64009. while (curSI.swapedOffset) {
  64010. curSI = this._sortTable[curSI.swapedOffset / stride];
  64011. }
  64012. // Finally get the right location
  64013. sourceOff = curSI.offset;
  64014. }
  64015. // Tag the element being replaced with its new location
  64016. destSI.swapedOffset = sourceOff;
  64017. // Swap elements (only if needed)
  64018. if (sourceOff !== destSI.offset) {
  64019. swapElements(sourceOff, destSI.offset);
  64020. }
  64021. // Update the offset in the corresponding DFAE
  64022. //sourceSI.entry.offset = destSI.entry.offset;
  64023. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  64024. }
  64025. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  64026. return true;
  64027. };
  64028. return DynamicFloatArray;
  64029. }());
  64030. BABYLON.DynamicFloatArray = DynamicFloatArray;
  64031. var SortInfo = (function () {
  64032. function SortInfo() {
  64033. this.compareData = this.offset = this.swapedOffset = null;
  64034. }
  64035. return SortInfo;
  64036. }());
  64037. })(BABYLON || (BABYLON = {}));
  64038. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  64039. var BABYLON;
  64040. (function (BABYLON) {
  64041. var Debug;
  64042. (function (Debug) {
  64043. /**
  64044. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  64045. */
  64046. var SkeletonViewer = (function () {
  64047. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  64048. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  64049. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  64050. this.skeleton = skeleton;
  64051. this.mesh = mesh;
  64052. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  64053. this.renderingGroupId = renderingGroupId;
  64054. this.color = BABYLON.Color3.White();
  64055. this._debugLines = [];
  64056. this._isEnabled = false;
  64057. this._scene = scene;
  64058. this.update();
  64059. this._renderFunction = this.update.bind(this);
  64060. }
  64061. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  64062. get: function () {
  64063. return this._isEnabled;
  64064. },
  64065. set: function (value) {
  64066. if (this._isEnabled === value) {
  64067. return;
  64068. }
  64069. this._isEnabled = value;
  64070. if (value) {
  64071. this._scene.registerBeforeRender(this._renderFunction);
  64072. }
  64073. else {
  64074. this._scene.unregisterBeforeRender(this._renderFunction);
  64075. }
  64076. },
  64077. enumerable: true,
  64078. configurable: true
  64079. });
  64080. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  64081. if (x === void 0) { x = 0; }
  64082. if (y === void 0) { y = 0; }
  64083. if (z === void 0) { z = 0; }
  64084. var tmat = BABYLON.Tmp.Matrix[0];
  64085. var parentBone = bone.getParent();
  64086. tmat.copyFrom(bone.getLocalMatrix());
  64087. if (x !== 0 || y !== 0 || z !== 0) {
  64088. var tmat2 = BABYLON.Tmp.Matrix[1];
  64089. BABYLON.Matrix.IdentityToRef(tmat2);
  64090. tmat2.m[12] = x;
  64091. tmat2.m[13] = y;
  64092. tmat2.m[14] = z;
  64093. tmat2.multiplyToRef(tmat, tmat);
  64094. }
  64095. if (parentBone) {
  64096. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  64097. }
  64098. tmat.multiplyToRef(meshMat, tmat);
  64099. position.x = tmat.m[12];
  64100. position.y = tmat.m[13];
  64101. position.z = tmat.m[14];
  64102. };
  64103. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  64104. var len = bones.length;
  64105. var meshPos = this.mesh.position;
  64106. for (var i = 0; i < len; i++) {
  64107. var bone = bones[i];
  64108. var points = this._debugLines[i];
  64109. if (!points) {
  64110. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64111. this._debugLines[i] = points;
  64112. }
  64113. this._getBonePosition(points[0], bone, meshMat);
  64114. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  64115. points[0].subtractInPlace(meshPos);
  64116. points[1].subtractInPlace(meshPos);
  64117. }
  64118. };
  64119. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  64120. var len = bones.length;
  64121. var boneNum = 0;
  64122. var meshPos = this.mesh.position;
  64123. for (var i = len - 1; i >= 0; i--) {
  64124. var childBone = bones[i];
  64125. var parentBone = childBone.getParent();
  64126. if (!parentBone) {
  64127. continue;
  64128. }
  64129. var points = this._debugLines[boneNum];
  64130. if (!points) {
  64131. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64132. this._debugLines[boneNum] = points;
  64133. }
  64134. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  64135. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  64136. points[0].subtractInPlace(meshPos);
  64137. points[1].subtractInPlace(meshPos);
  64138. boneNum++;
  64139. }
  64140. };
  64141. SkeletonViewer.prototype.update = function () {
  64142. if (this.autoUpdateBonesMatrices) {
  64143. this.skeleton.computeAbsoluteTransforms();
  64144. }
  64145. if (this.skeleton.bones[0].length === undefined) {
  64146. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64147. }
  64148. else {
  64149. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64150. }
  64151. if (!this._debugMesh) {
  64152. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  64153. this._debugMesh.renderingGroupId = this.renderingGroupId;
  64154. }
  64155. else {
  64156. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  64157. }
  64158. this._debugMesh.position.copyFrom(this.mesh.position);
  64159. this._debugMesh.color = this.color;
  64160. };
  64161. SkeletonViewer.prototype.dispose = function () {
  64162. if (this._debugMesh) {
  64163. this.isEnabled = false;
  64164. this._debugMesh.dispose();
  64165. this._debugMesh = null;
  64166. }
  64167. };
  64168. return SkeletonViewer;
  64169. }());
  64170. Debug.SkeletonViewer = SkeletonViewer;
  64171. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64172. })(BABYLON || (BABYLON = {}));
  64173. //# sourceMappingURL=babylon.skeletonViewer.js.map
  64174. var BABYLON;
  64175. (function (BABYLON) {
  64176. var Debug;
  64177. (function (Debug) {
  64178. var AxesViewer = (function () {
  64179. function AxesViewer(scene, scaleLines) {
  64180. if (scaleLines === void 0) { scaleLines = 1; }
  64181. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64182. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64183. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64184. this.scaleLines = 1;
  64185. this.scaleLines = scaleLines;
  64186. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  64187. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  64188. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  64189. this._xmesh.renderingGroupId = 2;
  64190. this._ymesh.renderingGroupId = 2;
  64191. this._zmesh.renderingGroupId = 2;
  64192. this._xmesh.material.checkReadyOnlyOnce = true;
  64193. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  64194. this._ymesh.material.checkReadyOnlyOnce = true;
  64195. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  64196. this._zmesh.material.checkReadyOnlyOnce = true;
  64197. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  64198. this.scene = scene;
  64199. }
  64200. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  64201. var scaleLines = this.scaleLines;
  64202. this._xmesh.position.copyFrom(position);
  64203. this._ymesh.position.copyFrom(position);
  64204. this._zmesh.position.copyFrom(position);
  64205. var point2 = this._xline[1];
  64206. point2.x = xaxis.x * scaleLines;
  64207. point2.y = xaxis.y * scaleLines;
  64208. point2.z = xaxis.z * scaleLines;
  64209. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  64210. point2 = this._yline[1];
  64211. point2.x = yaxis.x * scaleLines;
  64212. point2.y = yaxis.y * scaleLines;
  64213. point2.z = yaxis.z * scaleLines;
  64214. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  64215. point2 = this._zline[1];
  64216. point2.x = zaxis.x * scaleLines;
  64217. point2.y = zaxis.y * scaleLines;
  64218. point2.z = zaxis.z * scaleLines;
  64219. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  64220. };
  64221. AxesViewer.prototype.dispose = function () {
  64222. if (this._xmesh) {
  64223. this._xmesh.dispose();
  64224. this._ymesh.dispose();
  64225. this._zmesh.dispose();
  64226. this._xmesh = null;
  64227. this._ymesh = null;
  64228. this._zmesh = null;
  64229. this._xline = null;
  64230. this._yline = null;
  64231. this._zline = null;
  64232. this.scene = null;
  64233. }
  64234. };
  64235. return AxesViewer;
  64236. }());
  64237. Debug.AxesViewer = AxesViewer;
  64238. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64239. })(BABYLON || (BABYLON = {}));
  64240. //# sourceMappingURL=babylon.axesViewer.js.map
  64241. var BABYLON;
  64242. (function (BABYLON) {
  64243. var Debug;
  64244. (function (Debug) {
  64245. var BoneAxesViewer = (function (_super) {
  64246. __extends(BoneAxesViewer, _super);
  64247. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  64248. if (scaleLines === void 0) { scaleLines = 1; }
  64249. var _this = _super.call(this, scene, scaleLines) || this;
  64250. _this.pos = BABYLON.Vector3.Zero();
  64251. _this.xaxis = BABYLON.Vector3.Zero();
  64252. _this.yaxis = BABYLON.Vector3.Zero();
  64253. _this.zaxis = BABYLON.Vector3.Zero();
  64254. _this.mesh = mesh;
  64255. _this.bone = bone;
  64256. return _this;
  64257. }
  64258. BoneAxesViewer.prototype.update = function () {
  64259. var bone = this.bone;
  64260. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  64261. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  64262. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  64263. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  64264. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  64265. };
  64266. BoneAxesViewer.prototype.dispose = function () {
  64267. if (this.pos) {
  64268. this.pos = null;
  64269. this.xaxis = null;
  64270. this.yaxis = null;
  64271. this.zaxis = null;
  64272. this.mesh = null;
  64273. this.bone = null;
  64274. _super.prototype.dispose.call(this);
  64275. }
  64276. };
  64277. return BoneAxesViewer;
  64278. }(Debug.AxesViewer));
  64279. Debug.BoneAxesViewer = BoneAxesViewer;
  64280. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64281. })(BABYLON || (BABYLON = {}));
  64282. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  64283. var BABYLON;
  64284. (function (BABYLON) {
  64285. var RayHelper = (function () {
  64286. function RayHelper(ray) {
  64287. this.ray = ray;
  64288. }
  64289. RayHelper.CreateAndShow = function (ray, scene, color) {
  64290. var helper = new RayHelper(ray);
  64291. helper.show(scene, color);
  64292. return helper;
  64293. };
  64294. RayHelper.prototype.show = function (scene, color) {
  64295. if (!this._renderFunction) {
  64296. var ray = this.ray;
  64297. this._renderFunction = this._render.bind(this);
  64298. this._scene = scene;
  64299. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  64300. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  64301. this._scene.registerBeforeRender(this._renderFunction);
  64302. }
  64303. if (color) {
  64304. this._renderLine.color.copyFrom(color);
  64305. }
  64306. };
  64307. RayHelper.prototype.hide = function () {
  64308. if (this._renderFunction) {
  64309. this._scene.unregisterBeforeRender(this._renderFunction);
  64310. this._scene = null;
  64311. this._renderFunction = null;
  64312. this._renderLine.dispose();
  64313. this._renderLine = null;
  64314. this._renderPoints = null;
  64315. }
  64316. };
  64317. RayHelper.prototype._render = function () {
  64318. var ray = this.ray;
  64319. var point = this._renderPoints[1];
  64320. var len = Math.min(ray.length, 1000000);
  64321. point.copyFrom(ray.direction);
  64322. point.scaleInPlace(len);
  64323. point.addInPlace(ray.origin);
  64324. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  64325. };
  64326. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  64327. this._attachedToMesh = mesh;
  64328. var ray = this.ray;
  64329. if (!ray.direction) {
  64330. ray.direction = BABYLON.Vector3.Zero();
  64331. }
  64332. if (!ray.origin) {
  64333. ray.origin = BABYLON.Vector3.Zero();
  64334. }
  64335. if (length) {
  64336. ray.length = length;
  64337. }
  64338. if (!meshSpaceOrigin) {
  64339. meshSpaceOrigin = BABYLON.Vector3.Zero();
  64340. }
  64341. if (!meshSpaceDirection) {
  64342. // -1 so that this will work with Mesh.lookAt
  64343. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  64344. }
  64345. if (!this._meshSpaceDirection) {
  64346. this._meshSpaceDirection = meshSpaceDirection.clone();
  64347. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  64348. }
  64349. else {
  64350. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  64351. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  64352. }
  64353. if (!this._updateToMeshFunction) {
  64354. this._updateToMeshFunction = this._updateToMesh.bind(this);
  64355. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  64356. }
  64357. this._updateToMesh();
  64358. };
  64359. RayHelper.prototype.detachFromMesh = function () {
  64360. if (this._attachedToMesh) {
  64361. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  64362. this._attachedToMesh = null;
  64363. this._updateToMeshFunction = null;
  64364. }
  64365. };
  64366. RayHelper.prototype._updateToMesh = function () {
  64367. var ray = this.ray;
  64368. if (this._attachedToMesh._isDisposed) {
  64369. this.detachFromMesh();
  64370. return;
  64371. }
  64372. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  64373. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  64374. };
  64375. RayHelper.prototype.dispose = function () {
  64376. this.hide();
  64377. this.detachFromMesh();
  64378. this.ray = null;
  64379. };
  64380. return RayHelper;
  64381. }());
  64382. BABYLON.RayHelper = RayHelper;
  64383. })(BABYLON || (BABYLON = {}));
  64384. //# sourceMappingURL=babylon.rayHelper.js.map
  64385. var BABYLON;
  64386. (function (BABYLON) {
  64387. var DebugLayer = (function () {
  64388. function DebugLayer(scene) {
  64389. this._scene = scene;
  64390. }
  64391. /** Creates the inspector window. */
  64392. DebugLayer.prototype._createInspector = function (config) {
  64393. if (config === void 0) { config = {}; }
  64394. var popup = config.popup || false;
  64395. var initialTab = config.initialTab || 0;
  64396. var parentElement = config.parentElement || null;
  64397. if (!this._inspector) {
  64398. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  64399. } // else nothing to do,; instance is already existing
  64400. };
  64401. DebugLayer.prototype.isVisible = function () {
  64402. if (!this._inspector) {
  64403. return false;
  64404. }
  64405. return true;
  64406. };
  64407. DebugLayer.prototype.hide = function () {
  64408. if (this._inspector) {
  64409. try {
  64410. this._inspector.dispose();
  64411. }
  64412. catch (e) {
  64413. // If the inspector has been removed directly from the inspector tool
  64414. }
  64415. this._inspector = null;
  64416. }
  64417. };
  64418. DebugLayer.prototype.show = function (config) {
  64419. if (config === void 0) { config = {}; }
  64420. if (typeof INSPECTOR == 'undefined') {
  64421. // Load inspector and add it to the DOM
  64422. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  64423. }
  64424. else {
  64425. // Otherwise creates the inspector
  64426. this._createInspector(config);
  64427. }
  64428. };
  64429. // Get protocol used - http or https
  64430. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  64431. return DebugLayer;
  64432. }());
  64433. BABYLON.DebugLayer = DebugLayer;
  64434. })(BABYLON || (BABYLON = {}));
  64435. //# sourceMappingURL=babylon.debugLayer.js.map
  64436. var BABYLON;
  64437. (function (BABYLON) {
  64438. var Debug;
  64439. (function (Debug) {
  64440. var PhysicsViewer = (function () {
  64441. function PhysicsViewer(scene) {
  64442. this._impostors = [];
  64443. this._meshes = [];
  64444. this._numMeshes = 0;
  64445. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64446. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  64447. }
  64448. PhysicsViewer.prototype._updateDebugMeshes = function () {
  64449. var plugin = this._physicsEnginePlugin;
  64450. for (var i = 0; i < this._numMeshes; i++) {
  64451. if (this._impostors[i].isDisposed) {
  64452. this.hideImpostor(this._impostors[i--]);
  64453. }
  64454. else {
  64455. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  64456. }
  64457. }
  64458. };
  64459. PhysicsViewer.prototype.showImpostor = function (impostor) {
  64460. for (var i = 0; i < this._numMeshes; i++) {
  64461. if (this._impostors[i] == impostor) {
  64462. return;
  64463. }
  64464. }
  64465. var debugMesh = this._getDebugMesh(impostor, this._scene);
  64466. if (debugMesh) {
  64467. this._impostors[this._numMeshes] = impostor;
  64468. this._meshes[this._numMeshes] = debugMesh;
  64469. if (this._numMeshes === 0) {
  64470. this._renderFunction = this._updateDebugMeshes.bind(this);
  64471. this._scene.registerBeforeRender(this._renderFunction);
  64472. }
  64473. this._numMeshes++;
  64474. }
  64475. };
  64476. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  64477. var removed = false;
  64478. for (var i = 0; i < this._numMeshes; i++) {
  64479. if (this._impostors[i] == impostor) {
  64480. this._scene.removeMesh(this._meshes[i]);
  64481. this._meshes[i].dispose();
  64482. this._numMeshes--;
  64483. if (this._numMeshes > 0) {
  64484. this._meshes[i] = this._meshes[this._numMeshes];
  64485. this._impostors[i] = this._impostors[this._numMeshes];
  64486. this._meshes[this._numMeshes] = null;
  64487. this._impostors[this._numMeshes] = null;
  64488. }
  64489. else {
  64490. this._meshes[0] = null;
  64491. this._impostors[0] = null;
  64492. }
  64493. removed = true;
  64494. break;
  64495. }
  64496. }
  64497. if (removed && this._numMeshes === 0) {
  64498. this._scene.unregisterBeforeRender(this._renderFunction);
  64499. }
  64500. };
  64501. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  64502. if (!this._debugMaterial) {
  64503. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  64504. this._debugMaterial.wireframe = true;
  64505. }
  64506. return this._debugMaterial;
  64507. };
  64508. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  64509. if (!this._debugBoxMesh) {
  64510. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  64511. this._debugBoxMesh.renderingGroupId = 1;
  64512. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64513. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  64514. scene.removeMesh(this._debugBoxMesh);
  64515. }
  64516. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  64517. };
  64518. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  64519. if (!this._debugSphereMesh) {
  64520. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  64521. this._debugSphereMesh.renderingGroupId = 1;
  64522. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64523. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  64524. scene.removeMesh(this._debugSphereMesh);
  64525. }
  64526. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  64527. };
  64528. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  64529. var body = impostor.physicsBody;
  64530. var shape = body.shapes[0];
  64531. var mesh;
  64532. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  64533. mesh = this._getDebugBoxMesh(scene);
  64534. impostor.getBoxSizeToRef(mesh.scaling);
  64535. }
  64536. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  64537. mesh = this._getDebugSphereMesh(scene);
  64538. var radius = impostor.getRadius();
  64539. mesh.scaling.x = radius * 2;
  64540. mesh.scaling.y = radius * 2;
  64541. mesh.scaling.z = radius * 2;
  64542. }
  64543. return mesh;
  64544. };
  64545. PhysicsViewer.prototype.dispose = function () {
  64546. for (var i = 0; i < this._numMeshes; i++) {
  64547. this.hideImpostor(this._impostors[i]);
  64548. }
  64549. if (this._debugBoxMesh) {
  64550. this._debugBoxMesh.dispose();
  64551. }
  64552. if (this._debugSphereMesh) {
  64553. this._debugSphereMesh.dispose();
  64554. }
  64555. if (this._debugMaterial) {
  64556. this._debugMaterial.dispose();
  64557. }
  64558. this._impostors.length = 0;
  64559. this._scene = null;
  64560. this._physicsEnginePlugin = null;
  64561. };
  64562. return PhysicsViewer;
  64563. }());
  64564. Debug.PhysicsViewer = PhysicsViewer;
  64565. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64566. })(BABYLON || (BABYLON = {}));
  64567. //# sourceMappingURL=babylon.physicsViewer.js.map
  64568. var BABYLON;
  64569. (function (BABYLON) {
  64570. var BoundingBoxRenderer = (function () {
  64571. function BoundingBoxRenderer(scene) {
  64572. this.frontColor = new BABYLON.Color3(1, 1, 1);
  64573. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  64574. this.showBackLines = true;
  64575. this.renderList = new BABYLON.SmartArray(32);
  64576. this._vertexBuffers = {};
  64577. this._scene = scene;
  64578. }
  64579. BoundingBoxRenderer.prototype._prepareRessources = function () {
  64580. if (this._colorShader) {
  64581. return;
  64582. }
  64583. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  64584. attributes: [BABYLON.VertexBuffer.PositionKind],
  64585. uniforms: ["world", "viewProjection", "color"]
  64586. });
  64587. var engine = this._scene.getEngine();
  64588. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  64589. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  64590. this._createIndexBuffer();
  64591. };
  64592. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  64593. var engine = this._scene.getEngine();
  64594. 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]);
  64595. };
  64596. BoundingBoxRenderer.prototype._rebuild = function () {
  64597. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  64598. this._createIndexBuffer();
  64599. };
  64600. BoundingBoxRenderer.prototype.reset = function () {
  64601. this.renderList.reset();
  64602. };
  64603. BoundingBoxRenderer.prototype.render = function () {
  64604. if (this.renderList.length === 0) {
  64605. return;
  64606. }
  64607. this._prepareRessources();
  64608. if (!this._colorShader.isReady()) {
  64609. return;
  64610. }
  64611. var engine = this._scene.getEngine();
  64612. engine.setDepthWrite(false);
  64613. this._colorShader._preBind();
  64614. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  64615. var boundingBox = this.renderList.data[boundingBoxIndex];
  64616. var min = boundingBox.minimum;
  64617. var max = boundingBox.maximum;
  64618. var diff = max.subtract(min);
  64619. var median = min.add(diff.scale(0.5));
  64620. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64621. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64622. .multiply(boundingBox.getWorldMatrix());
  64623. // VBOs
  64624. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64625. if (this.showBackLines) {
  64626. // Back
  64627. engine.setDepthFunctionToGreaterOrEqual();
  64628. this._scene.resetCachedMaterial();
  64629. this._colorShader.setColor4("color", this.backColor.toColor4());
  64630. this._colorShader.bind(worldMatrix);
  64631. // Draw order
  64632. engine.draw(false, 0, 24);
  64633. }
  64634. // Front
  64635. engine.setDepthFunctionToLess();
  64636. this._scene.resetCachedMaterial();
  64637. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64638. this._colorShader.bind(worldMatrix);
  64639. // Draw order
  64640. engine.draw(false, 0, 24);
  64641. }
  64642. this._colorShader.unbind();
  64643. engine.setDepthFunctionToLessOrEqual();
  64644. engine.setDepthWrite(true);
  64645. };
  64646. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64647. this._prepareRessources();
  64648. if (!this._colorShader.isReady()) {
  64649. return;
  64650. }
  64651. var engine = this._scene.getEngine();
  64652. engine.setDepthWrite(false);
  64653. engine.setColorWrite(false);
  64654. this._colorShader._preBind();
  64655. var boundingBox = mesh._boundingInfo.boundingBox;
  64656. var min = boundingBox.minimum;
  64657. var max = boundingBox.maximum;
  64658. var diff = max.subtract(min);
  64659. var median = min.add(diff.scale(0.5));
  64660. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64661. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64662. .multiply(boundingBox.getWorldMatrix());
  64663. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64664. engine.setDepthFunctionToLess();
  64665. this._scene.resetCachedMaterial();
  64666. this._colorShader.bind(worldMatrix);
  64667. engine.draw(false, 0, 24);
  64668. this._colorShader.unbind();
  64669. engine.setDepthFunctionToLessOrEqual();
  64670. engine.setDepthWrite(true);
  64671. engine.setColorWrite(true);
  64672. };
  64673. BoundingBoxRenderer.prototype.dispose = function () {
  64674. if (!this._colorShader) {
  64675. return;
  64676. }
  64677. this.renderList.dispose();
  64678. this._colorShader.dispose();
  64679. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64680. if (buffer) {
  64681. buffer.dispose();
  64682. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64683. }
  64684. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64685. };
  64686. return BoundingBoxRenderer;
  64687. }());
  64688. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  64689. })(BABYLON || (BABYLON = {}));
  64690. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  64691. var BABYLON;
  64692. (function (BABYLON) {
  64693. var MorphTarget = (function () {
  64694. function MorphTarget(name, influence) {
  64695. if (influence === void 0) { influence = 0; }
  64696. this.name = name;
  64697. this.animations = new Array();
  64698. this.onInfluenceChanged = new BABYLON.Observable();
  64699. this.influence = influence;
  64700. }
  64701. Object.defineProperty(MorphTarget.prototype, "influence", {
  64702. get: function () {
  64703. return this._influence;
  64704. },
  64705. set: function (influence) {
  64706. if (this._influence === influence) {
  64707. return;
  64708. }
  64709. var previous = this._influence;
  64710. this._influence = influence;
  64711. if (this.onInfluenceChanged.hasObservers) {
  64712. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  64713. }
  64714. },
  64715. enumerable: true,
  64716. configurable: true
  64717. });
  64718. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  64719. get: function () {
  64720. return this._normals !== undefined;
  64721. },
  64722. enumerable: true,
  64723. configurable: true
  64724. });
  64725. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  64726. get: function () {
  64727. return this._tangents !== undefined;
  64728. },
  64729. enumerable: true,
  64730. configurable: true
  64731. });
  64732. MorphTarget.prototype.setPositions = function (data) {
  64733. this._positions = new Float32Array(data);
  64734. };
  64735. MorphTarget.prototype.getPositions = function () {
  64736. return this._positions;
  64737. };
  64738. MorphTarget.prototype.setNormals = function (data) {
  64739. this._normals = new Float32Array(data);
  64740. };
  64741. MorphTarget.prototype.getNormals = function () {
  64742. return this._normals;
  64743. };
  64744. MorphTarget.prototype.setTangents = function (data) {
  64745. this._tangents = new Float32Array(data);
  64746. };
  64747. MorphTarget.prototype.getTangents = function () {
  64748. return this._tangents;
  64749. };
  64750. /**
  64751. * Serializes the current target into a Serialization object.
  64752. * Returns the serialized object.
  64753. */
  64754. MorphTarget.prototype.serialize = function () {
  64755. var serializationObject = {};
  64756. serializationObject.name = this.name;
  64757. serializationObject.influence = this.influence;
  64758. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  64759. if (this.hasNormals) {
  64760. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  64761. }
  64762. if (this.hasTangents) {
  64763. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  64764. }
  64765. return serializationObject;
  64766. };
  64767. // Statics
  64768. MorphTarget.Parse = function (serializationObject) {
  64769. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  64770. result.setPositions(serializationObject.positions);
  64771. if (serializationObject.normals) {
  64772. result.setNormals(serializationObject.normals);
  64773. }
  64774. if (serializationObject.tangents) {
  64775. result.setTangents(serializationObject.tangents);
  64776. }
  64777. return result;
  64778. };
  64779. MorphTarget.FromMesh = function (mesh, name, influence) {
  64780. if (!name) {
  64781. name = mesh.name;
  64782. }
  64783. var result = new MorphTarget(name, influence);
  64784. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  64785. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  64786. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  64787. }
  64788. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  64789. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  64790. }
  64791. return result;
  64792. };
  64793. return MorphTarget;
  64794. }());
  64795. BABYLON.MorphTarget = MorphTarget;
  64796. })(BABYLON || (BABYLON = {}));
  64797. //# sourceMappingURL=babylon.morphTarget.js.map
  64798. var BABYLON;
  64799. (function (BABYLON) {
  64800. var MorphTargetManager = (function () {
  64801. function MorphTargetManager(scene) {
  64802. this._targets = new Array();
  64803. this._targetObservable = new Array();
  64804. this._activeTargets = new BABYLON.SmartArray(16);
  64805. this._supportsNormals = false;
  64806. this._supportsTangents = false;
  64807. this._vertexCount = 0;
  64808. this._uniqueId = 0;
  64809. this._tempInfluences = new Array();
  64810. if (!scene) {
  64811. scene = BABYLON.Engine.LastCreatedScene;
  64812. }
  64813. this._scene = scene;
  64814. this._scene.morphTargetManagers.push(this);
  64815. this._uniqueId = scene.getUniqueId();
  64816. }
  64817. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  64818. get: function () {
  64819. return this._uniqueId;
  64820. },
  64821. enumerable: true,
  64822. configurable: true
  64823. });
  64824. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  64825. get: function () {
  64826. return this._vertexCount;
  64827. },
  64828. enumerable: true,
  64829. configurable: true
  64830. });
  64831. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  64832. get: function () {
  64833. return this._supportsNormals;
  64834. },
  64835. enumerable: true,
  64836. configurable: true
  64837. });
  64838. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  64839. get: function () {
  64840. return this._supportsTangents;
  64841. },
  64842. enumerable: true,
  64843. configurable: true
  64844. });
  64845. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  64846. get: function () {
  64847. return this._targets.length;
  64848. },
  64849. enumerable: true,
  64850. configurable: true
  64851. });
  64852. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  64853. get: function () {
  64854. return this._activeTargets.length;
  64855. },
  64856. enumerable: true,
  64857. configurable: true
  64858. });
  64859. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  64860. get: function () {
  64861. return this._influences;
  64862. },
  64863. enumerable: true,
  64864. configurable: true
  64865. });
  64866. MorphTargetManager.prototype.getActiveTarget = function (index) {
  64867. return this._activeTargets.data[index];
  64868. };
  64869. MorphTargetManager.prototype.getTarget = function (index) {
  64870. return this._targets[index];
  64871. };
  64872. MorphTargetManager.prototype.addTarget = function (target) {
  64873. var _this = this;
  64874. if (this._vertexCount) {
  64875. if (this._vertexCount !== target.getPositions().length / 3) {
  64876. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  64877. return;
  64878. }
  64879. }
  64880. this._targets.push(target);
  64881. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  64882. _this._syncActiveTargets(needUpdate);
  64883. }));
  64884. this._syncActiveTargets(true);
  64885. };
  64886. MorphTargetManager.prototype.removeTarget = function (target) {
  64887. var index = this._targets.indexOf(target);
  64888. if (index >= 0) {
  64889. this._targets.splice(index, 1);
  64890. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  64891. this._vertexCount = 0;
  64892. this._syncActiveTargets(true);
  64893. }
  64894. };
  64895. /**
  64896. * Serializes the current manager into a Serialization object.
  64897. * Returns the serialized object.
  64898. */
  64899. MorphTargetManager.prototype.serialize = function () {
  64900. var serializationObject = {};
  64901. serializationObject.id = this.uniqueId;
  64902. serializationObject.targets = [];
  64903. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  64904. var target = _a[_i];
  64905. serializationObject.targets.push(target.serialize());
  64906. }
  64907. return serializationObject;
  64908. };
  64909. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  64910. this._syncActiveTargets(needUpdate);
  64911. };
  64912. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  64913. var influenceCount = 0;
  64914. this._activeTargets.reset();
  64915. this._supportsNormals = true;
  64916. this._supportsTangents = true;
  64917. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  64918. var target = _a[_i];
  64919. if (target.influence > 0) {
  64920. this._activeTargets.push(target);
  64921. this._tempInfluences[influenceCount++] = target.influence;
  64922. this._supportsNormals = this._supportsNormals && target.hasNormals;
  64923. this._supportsTangents = this._supportsTangents && target.hasTangents;
  64924. if (this._vertexCount === 0) {
  64925. this._vertexCount = target.getPositions().length / 3;
  64926. }
  64927. }
  64928. }
  64929. if (!this._influences || this._influences.length !== influenceCount) {
  64930. this._influences = new Float32Array(influenceCount);
  64931. }
  64932. for (var index = 0; index < influenceCount; index++) {
  64933. this._influences[index] = this._tempInfluences[index];
  64934. }
  64935. if (needUpdate) {
  64936. // Flag meshes as dirty to resync with the active targets
  64937. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  64938. var mesh = _c[_b];
  64939. if (mesh.morphTargetManager === this) {
  64940. mesh._syncGeometryWithMorphTargetManager();
  64941. }
  64942. }
  64943. }
  64944. };
  64945. // Statics
  64946. MorphTargetManager.Parse = function (serializationObject, scene) {
  64947. var result = new MorphTargetManager(scene);
  64948. result._uniqueId = serializationObject.id;
  64949. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  64950. var targetData = _a[_i];
  64951. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  64952. }
  64953. return result;
  64954. };
  64955. return MorphTargetManager;
  64956. }());
  64957. BABYLON.MorphTargetManager = MorphTargetManager;
  64958. })(BABYLON || (BABYLON = {}));
  64959. //# sourceMappingURL=babylon.morphTargetManager.js.map
  64960. var BABYLON;
  64961. (function (BABYLON) {
  64962. /**
  64963. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  64964. * It can help converting any input color in a desired output one. This can then be used to create effects
  64965. * from sepia, black and white to sixties or futuristic rendering...
  64966. *
  64967. * The only supported format is currently 3dl.
  64968. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  64969. */
  64970. var ColorGradingTexture = (function (_super) {
  64971. __extends(ColorGradingTexture, _super);
  64972. /**
  64973. * Instantiates a ColorGradingTexture from the following parameters.
  64974. *
  64975. * @param url The location of the color gradind data (currently only supporting 3dl)
  64976. * @param scene The scene the texture will be used in
  64977. */
  64978. function ColorGradingTexture(url, scene) {
  64979. var _this = _super.call(this, scene) || this;
  64980. if (!url) {
  64981. return _this;
  64982. }
  64983. _this._textureMatrix = BABYLON.Matrix.Identity();
  64984. _this.name = url;
  64985. _this.url = url;
  64986. _this.hasAlpha = false;
  64987. _this.isCube = false;
  64988. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64989. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64990. _this.anisotropicFilteringLevel = 1;
  64991. _this._texture = _this._getFromCache(url, true);
  64992. if (!_this._texture) {
  64993. if (!scene.useDelayedTextureLoading) {
  64994. _this.loadTexture();
  64995. }
  64996. else {
  64997. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64998. }
  64999. }
  65000. return _this;
  65001. }
  65002. /**
  65003. * Returns the texture matrix used in most of the material.
  65004. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  65005. */
  65006. ColorGradingTexture.prototype.getTextureMatrix = function () {
  65007. return this._textureMatrix;
  65008. };
  65009. /**
  65010. * Occurs when the file being loaded is a .3dl LUT file.
  65011. */
  65012. ColorGradingTexture.prototype.load3dlTexture = function () {
  65013. var _this = this;
  65014. var mipLevels = 0;
  65015. var floatArrayView = null;
  65016. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65017. this._texture = texture;
  65018. var callback = function (text) {
  65019. var data;
  65020. var tempData;
  65021. var line;
  65022. var lines = text.split('\n');
  65023. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  65024. var maxColor = 0;
  65025. for (var i = 0; i < lines.length; i++) {
  65026. line = lines[i];
  65027. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  65028. continue;
  65029. if (line.indexOf('#') === 0)
  65030. continue;
  65031. var words = line.split(" ");
  65032. if (size === 0) {
  65033. // Number of space + one
  65034. size = words.length;
  65035. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  65036. tempData = new Float32Array(size * size * size * 4);
  65037. continue;
  65038. }
  65039. if (size != 0) {
  65040. var r = Math.max(parseInt(words[0]), 0);
  65041. var g = Math.max(parseInt(words[1]), 0);
  65042. var b = Math.max(parseInt(words[2]), 0);
  65043. maxColor = Math.max(r, maxColor);
  65044. maxColor = Math.max(g, maxColor);
  65045. maxColor = Math.max(b, maxColor);
  65046. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  65047. tempData[pixelStorageIndex + 0] = r;
  65048. tempData[pixelStorageIndex + 1] = g;
  65049. tempData[pixelStorageIndex + 2] = b;
  65050. pixelIndexSlice++;
  65051. if (pixelIndexSlice % size == 0) {
  65052. pixelIndexH++;
  65053. pixelIndexSlice = 0;
  65054. if (pixelIndexH % size == 0) {
  65055. pixelIndexW++;
  65056. pixelIndexH = 0;
  65057. }
  65058. }
  65059. }
  65060. }
  65061. for (var i = 0; i < tempData.length; i++) {
  65062. if (i > 0 && (i + 1) % 4 === 0) {
  65063. data[i] = 255;
  65064. }
  65065. else {
  65066. var value = tempData[i];
  65067. data[i] = (value / maxColor * 255);
  65068. }
  65069. }
  65070. texture.updateSize(size * size, size);
  65071. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  65072. };
  65073. BABYLON.Tools.LoadFile(this.url, callback);
  65074. return this._texture;
  65075. };
  65076. /**
  65077. * Starts the loading process of the texture.
  65078. */
  65079. ColorGradingTexture.prototype.loadTexture = function () {
  65080. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  65081. this.load3dlTexture();
  65082. }
  65083. };
  65084. /**
  65085. * Clones the color gradind texture.
  65086. */
  65087. ColorGradingTexture.prototype.clone = function () {
  65088. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  65089. // Base texture
  65090. newTexture.level = this.level;
  65091. return newTexture;
  65092. };
  65093. /**
  65094. * Called during delayed load for textures.
  65095. */
  65096. ColorGradingTexture.prototype.delayLoad = function () {
  65097. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65098. return;
  65099. }
  65100. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  65101. this._texture = this._getFromCache(this.url, true);
  65102. if (!this._texture) {
  65103. this.loadTexture();
  65104. }
  65105. };
  65106. /**
  65107. * Parses a color grading texture serialized by Babylon.
  65108. * @param parsedTexture The texture information being parsedTexture
  65109. * @param scene The scene to load the texture in
  65110. * @param rootUrl The root url of the data assets to load
  65111. * @return A color gradind texture
  65112. */
  65113. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  65114. var texture = null;
  65115. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  65116. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  65117. texture.name = parsedTexture.name;
  65118. texture.level = parsedTexture.level;
  65119. }
  65120. return texture;
  65121. };
  65122. /**
  65123. * Serializes the LUT texture to json format.
  65124. */
  65125. ColorGradingTexture.prototype.serialize = function () {
  65126. if (!this.name) {
  65127. return null;
  65128. }
  65129. var serializationObject = {};
  65130. serializationObject.name = this.name;
  65131. serializationObject.level = this.level;
  65132. serializationObject.customType = "BABYLON.ColorGradingTexture";
  65133. return serializationObject;
  65134. };
  65135. /**
  65136. * Empty line regex stored for GC.
  65137. */
  65138. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  65139. return ColorGradingTexture;
  65140. }(BABYLON.BaseTexture));
  65141. BABYLON.ColorGradingTexture = ColorGradingTexture;
  65142. })(BABYLON || (BABYLON = {}));
  65143. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  65144. var BABYLON;
  65145. (function (BABYLON) {
  65146. /**
  65147. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  65148. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  65149. * 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;
  65150. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  65151. */
  65152. var ColorCurves = (function () {
  65153. function ColorCurves() {
  65154. this._dirty = true;
  65155. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  65156. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  65157. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  65158. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  65159. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  65160. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  65161. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  65162. this._globalHue = 30;
  65163. this._globalDensity = 0;
  65164. this._globalSaturation = 0;
  65165. this._globalExposure = 0;
  65166. this._highlightsHue = 30;
  65167. this._highlightsDensity = 0;
  65168. this._highlightsSaturation = 0;
  65169. this._highlightsExposure = 0;
  65170. this._midtonesHue = 30;
  65171. this._midtonesDensity = 0;
  65172. this._midtonesSaturation = 0;
  65173. this._midtonesExposure = 0;
  65174. this._shadowsHue = 30;
  65175. this._shadowsDensity = 0;
  65176. this._shadowsSaturation = 0;
  65177. this._shadowsExposure = 0;
  65178. }
  65179. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  65180. /**
  65181. * Gets the global Hue value.
  65182. * 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).
  65183. */
  65184. get: function () {
  65185. return this._globalHue;
  65186. },
  65187. /**
  65188. * Sets the global Hue value.
  65189. * 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).
  65190. */
  65191. set: function (value) {
  65192. this._globalHue = value;
  65193. this._dirty = true;
  65194. },
  65195. enumerable: true,
  65196. configurable: true
  65197. });
  65198. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  65199. /**
  65200. * Gets the global Density value.
  65201. * 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.
  65202. * Values less than zero provide a filter of opposite hue.
  65203. */
  65204. get: function () {
  65205. return this._globalDensity;
  65206. },
  65207. /**
  65208. * Sets the global Density value.
  65209. * 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.
  65210. * Values less than zero provide a filter of opposite hue.
  65211. */
  65212. set: function (value) {
  65213. this._globalDensity = value;
  65214. this._dirty = true;
  65215. },
  65216. enumerable: true,
  65217. configurable: true
  65218. });
  65219. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  65220. /**
  65221. * Gets the global Saturation value.
  65222. * 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.
  65223. */
  65224. get: function () {
  65225. return this._globalSaturation;
  65226. },
  65227. /**
  65228. * Sets the global Saturation value.
  65229. * 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.
  65230. */
  65231. set: function (value) {
  65232. this._globalSaturation = value;
  65233. this._dirty = true;
  65234. },
  65235. enumerable: true,
  65236. configurable: true
  65237. });
  65238. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  65239. /**
  65240. * Gets the highlights Hue value.
  65241. * 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).
  65242. */
  65243. get: function () {
  65244. return this._highlightsHue;
  65245. },
  65246. /**
  65247. * Sets the highlights Hue value.
  65248. * 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).
  65249. */
  65250. set: function (value) {
  65251. this._highlightsHue = value;
  65252. this._dirty = true;
  65253. },
  65254. enumerable: true,
  65255. configurable: true
  65256. });
  65257. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  65258. /**
  65259. * Gets the highlights Density value.
  65260. * 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.
  65261. * Values less than zero provide a filter of opposite hue.
  65262. */
  65263. get: function () {
  65264. return this._highlightsDensity;
  65265. },
  65266. /**
  65267. * Sets the highlights Density value.
  65268. * 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.
  65269. * Values less than zero provide a filter of opposite hue.
  65270. */
  65271. set: function (value) {
  65272. this._highlightsDensity = value;
  65273. this._dirty = true;
  65274. },
  65275. enumerable: true,
  65276. configurable: true
  65277. });
  65278. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  65279. /**
  65280. * Gets the highlights Saturation value.
  65281. * 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.
  65282. */
  65283. get: function () {
  65284. return this._highlightsSaturation;
  65285. },
  65286. /**
  65287. * Sets the highlights Saturation value.
  65288. * 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.
  65289. */
  65290. set: function (value) {
  65291. this._highlightsSaturation = value;
  65292. this._dirty = true;
  65293. },
  65294. enumerable: true,
  65295. configurable: true
  65296. });
  65297. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  65298. /**
  65299. * Gets the highlights Exposure value.
  65300. * 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.
  65301. */
  65302. get: function () {
  65303. return this._highlightsExposure;
  65304. },
  65305. /**
  65306. * Sets the highlights Exposure value.
  65307. * 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.
  65308. */
  65309. set: function (value) {
  65310. this._highlightsExposure = value;
  65311. this._dirty = true;
  65312. },
  65313. enumerable: true,
  65314. configurable: true
  65315. });
  65316. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  65317. /**
  65318. * Gets the midtones Hue value.
  65319. * 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).
  65320. */
  65321. get: function () {
  65322. return this._midtonesHue;
  65323. },
  65324. /**
  65325. * Sets the midtones Hue value.
  65326. * 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).
  65327. */
  65328. set: function (value) {
  65329. this._midtonesHue = value;
  65330. this._dirty = true;
  65331. },
  65332. enumerable: true,
  65333. configurable: true
  65334. });
  65335. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  65336. /**
  65337. * Gets the midtones Density value.
  65338. * 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.
  65339. * Values less than zero provide a filter of opposite hue.
  65340. */
  65341. get: function () {
  65342. return this._midtonesDensity;
  65343. },
  65344. /**
  65345. * Sets the midtones Density value.
  65346. * 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.
  65347. * Values less than zero provide a filter of opposite hue.
  65348. */
  65349. set: function (value) {
  65350. this._midtonesDensity = value;
  65351. this._dirty = true;
  65352. },
  65353. enumerable: true,
  65354. configurable: true
  65355. });
  65356. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  65357. /**
  65358. * Gets the midtones Saturation value.
  65359. * 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.
  65360. */
  65361. get: function () {
  65362. return this._midtonesSaturation;
  65363. },
  65364. /**
  65365. * Sets the midtones Saturation value.
  65366. * 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.
  65367. */
  65368. set: function (value) {
  65369. this._midtonesSaturation = value;
  65370. this._dirty = true;
  65371. },
  65372. enumerable: true,
  65373. configurable: true
  65374. });
  65375. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  65376. /**
  65377. * Gets the midtones Exposure value.
  65378. * 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.
  65379. */
  65380. get: function () {
  65381. return this._midtonesExposure;
  65382. },
  65383. /**
  65384. * Sets the midtones Exposure value.
  65385. * 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.
  65386. */
  65387. set: function (value) {
  65388. this._midtonesExposure = value;
  65389. this._dirty = true;
  65390. },
  65391. enumerable: true,
  65392. configurable: true
  65393. });
  65394. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  65395. /**
  65396. * Gets the shadows Hue value.
  65397. * 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).
  65398. */
  65399. get: function () {
  65400. return this._shadowsHue;
  65401. },
  65402. /**
  65403. * Sets the shadows Hue value.
  65404. * 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).
  65405. */
  65406. set: function (value) {
  65407. this._shadowsHue = value;
  65408. this._dirty = true;
  65409. },
  65410. enumerable: true,
  65411. configurable: true
  65412. });
  65413. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  65414. /**
  65415. * Gets the shadows Density value.
  65416. * 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.
  65417. * Values less than zero provide a filter of opposite hue.
  65418. */
  65419. get: function () {
  65420. return this._shadowsDensity;
  65421. },
  65422. /**
  65423. * Sets the shadows Density value.
  65424. * 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.
  65425. * Values less than zero provide a filter of opposite hue.
  65426. */
  65427. set: function (value) {
  65428. this._shadowsDensity = value;
  65429. this._dirty = true;
  65430. },
  65431. enumerable: true,
  65432. configurable: true
  65433. });
  65434. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  65435. /**
  65436. * Gets the shadows Saturation value.
  65437. * 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.
  65438. */
  65439. get: function () {
  65440. return this._shadowsSaturation;
  65441. },
  65442. /**
  65443. * Sets the shadows Saturation value.
  65444. * 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.
  65445. */
  65446. set: function (value) {
  65447. this._shadowsSaturation = value;
  65448. this._dirty = true;
  65449. },
  65450. enumerable: true,
  65451. configurable: true
  65452. });
  65453. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  65454. /**
  65455. * Gets the shadows Exposure value.
  65456. * 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.
  65457. */
  65458. get: function () {
  65459. return this._shadowsExposure;
  65460. },
  65461. /**
  65462. * Sets the shadows Exposure value.
  65463. * 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.
  65464. */
  65465. set: function (value) {
  65466. this._shadowsExposure = value;
  65467. this._dirty = true;
  65468. },
  65469. enumerable: true,
  65470. configurable: true
  65471. });
  65472. ColorCurves.prototype.getClassName = function () {
  65473. return "ColorCurves";
  65474. };
  65475. /**
  65476. * Binds the color curves to the shader.
  65477. * @param colorCurves The color curve to bind
  65478. * @param effect The effect to bind to
  65479. */
  65480. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  65481. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  65482. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  65483. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  65484. if (colorCurves._dirty) {
  65485. colorCurves._dirty = false;
  65486. // Fill in global info.
  65487. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  65488. // Compute highlights info.
  65489. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  65490. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  65491. // Compute midtones info.
  65492. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  65493. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  65494. // Compute shadows info.
  65495. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  65496. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  65497. // Compute deltas (neutral is midtones).
  65498. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  65499. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  65500. }
  65501. if (effect) {
  65502. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  65503. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  65504. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  65505. }
  65506. };
  65507. /**
  65508. * Prepare the list of uniforms associated with the ColorCurves effects.
  65509. * @param uniformsList The list of uniforms used in the effect
  65510. */
  65511. ColorCurves.PrepareUniforms = function (uniformsList) {
  65512. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  65513. };
  65514. /**
  65515. * Returns color grading data based on a hue, density, saturation and exposure value.
  65516. * @param filterHue The hue of the color filter.
  65517. * @param filterDensity The density of the color filter.
  65518. * @param saturation The saturation.
  65519. * @param exposure The exposure.
  65520. * @param result The result data container.
  65521. */
  65522. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  65523. if (hue == null) {
  65524. return;
  65525. }
  65526. hue = ColorCurves.clamp(hue, 0, 360);
  65527. density = ColorCurves.clamp(density, -100, 100);
  65528. saturation = ColorCurves.clamp(saturation, -100, 100);
  65529. exposure = ColorCurves.clamp(exposure, -100, 100);
  65530. // Remap the slider/config filter density with non-linear mapping and also scale by half
  65531. // so that the maximum filter density is only 50% control. This provides fine control
  65532. // for small values and reasonable range.
  65533. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  65534. density *= 0.5;
  65535. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  65536. if (density < 0) {
  65537. density *= -1;
  65538. hue = (hue + 180) % 360;
  65539. }
  65540. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  65541. result.scaleToRef(2, result);
  65542. result.a = 1 + 0.01 * saturation;
  65543. };
  65544. /**
  65545. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  65546. * @param value The input slider value in range [-100,100].
  65547. * @returns Adjusted value.
  65548. */
  65549. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  65550. value /= 100;
  65551. var x = Math.abs(value);
  65552. x = Math.pow(x, 2);
  65553. if (value < 0) {
  65554. x *= -1;
  65555. }
  65556. x *= 100;
  65557. return x;
  65558. };
  65559. /**
  65560. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  65561. * @param hue The hue (H) input.
  65562. * @param saturation The saturation (S) input.
  65563. * @param brightness The brightness (B) input.
  65564. * @result An RGBA color represented as Vector4.
  65565. */
  65566. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  65567. var h = ColorCurves.clamp(hue, 0, 360);
  65568. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  65569. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  65570. if (s === 0) {
  65571. result.r = v;
  65572. result.g = v;
  65573. result.b = v;
  65574. }
  65575. else {
  65576. // sector 0 to 5
  65577. h /= 60;
  65578. var i = Math.floor(h);
  65579. // fractional part of h
  65580. var f = h - i;
  65581. var p = v * (1 - s);
  65582. var q = v * (1 - s * f);
  65583. var t = v * (1 - s * (1 - f));
  65584. switch (i) {
  65585. case 0:
  65586. result.r = v;
  65587. result.g = t;
  65588. result.b = p;
  65589. break;
  65590. case 1:
  65591. result.r = q;
  65592. result.g = v;
  65593. result.b = p;
  65594. break;
  65595. case 2:
  65596. result.r = p;
  65597. result.g = v;
  65598. result.b = t;
  65599. break;
  65600. case 3:
  65601. result.r = p;
  65602. result.g = q;
  65603. result.b = v;
  65604. break;
  65605. case 4:
  65606. result.r = t;
  65607. result.g = p;
  65608. result.b = v;
  65609. break;
  65610. default:// case 5:
  65611. result.r = v;
  65612. result.g = p;
  65613. result.b = q;
  65614. break;
  65615. }
  65616. }
  65617. result.a = 1;
  65618. };
  65619. /**
  65620. * Returns a value clamped between min and max
  65621. * @param value The value to clamp
  65622. * @param min The minimum of value
  65623. * @param max The maximum of value
  65624. * @returns The clamped value.
  65625. */
  65626. ColorCurves.clamp = function (value, min, max) {
  65627. return Math.min(Math.max(value, min), max);
  65628. };
  65629. /**
  65630. * Clones the current color curve instance.
  65631. * @return The cloned curves
  65632. */
  65633. ColorCurves.prototype.clone = function () {
  65634. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  65635. };
  65636. /**
  65637. * Serializes the current color curve instance to a json representation.
  65638. * @return a JSON representation
  65639. */
  65640. ColorCurves.prototype.serialize = function () {
  65641. return BABYLON.SerializationHelper.Serialize(this);
  65642. };
  65643. /**
  65644. * Parses the color curve from a json representation.
  65645. * @param source the JSON source to parse
  65646. * @return The parsed curves
  65647. */
  65648. ColorCurves.Parse = function (source) {
  65649. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  65650. };
  65651. __decorate([
  65652. BABYLON.serialize()
  65653. ], ColorCurves.prototype, "_globalHue", void 0);
  65654. __decorate([
  65655. BABYLON.serialize()
  65656. ], ColorCurves.prototype, "_globalDensity", void 0);
  65657. __decorate([
  65658. BABYLON.serialize()
  65659. ], ColorCurves.prototype, "_globalSaturation", void 0);
  65660. __decorate([
  65661. BABYLON.serialize()
  65662. ], ColorCurves.prototype, "_globalExposure", void 0);
  65663. __decorate([
  65664. BABYLON.serialize()
  65665. ], ColorCurves.prototype, "_highlightsHue", void 0);
  65666. __decorate([
  65667. BABYLON.serialize()
  65668. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  65669. __decorate([
  65670. BABYLON.serialize()
  65671. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  65672. __decorate([
  65673. BABYLON.serialize()
  65674. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  65675. __decorate([
  65676. BABYLON.serialize()
  65677. ], ColorCurves.prototype, "_midtonesHue", void 0);
  65678. __decorate([
  65679. BABYLON.serialize()
  65680. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  65681. __decorate([
  65682. BABYLON.serialize()
  65683. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  65684. __decorate([
  65685. BABYLON.serialize()
  65686. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  65687. return ColorCurves;
  65688. }());
  65689. BABYLON.ColorCurves = ColorCurves;
  65690. })(BABYLON || (BABYLON = {}));
  65691. //# sourceMappingURL=babylon.colorCurves.js.map
  65692. var BABYLON;
  65693. (function (BABYLON) {
  65694. var Octree = (function () {
  65695. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  65696. if (maxDepth === void 0) { maxDepth = 2; }
  65697. this.maxDepth = maxDepth;
  65698. this.dynamicContent = new Array();
  65699. this._maxBlockCapacity = maxBlockCapacity || 64;
  65700. this._selectionContent = new BABYLON.SmartArray(1024);
  65701. this._creationFunc = creationFunc;
  65702. }
  65703. // Methods
  65704. Octree.prototype.update = function (worldMin, worldMax, entries) {
  65705. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  65706. };
  65707. Octree.prototype.addMesh = function (entry) {
  65708. for (var index = 0; index < this.blocks.length; index++) {
  65709. var block = this.blocks[index];
  65710. block.addEntry(entry);
  65711. }
  65712. };
  65713. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  65714. this._selectionContent.reset();
  65715. for (var index = 0; index < this.blocks.length; index++) {
  65716. var block = this.blocks[index];
  65717. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  65718. }
  65719. if (allowDuplicate) {
  65720. this._selectionContent.concat(this.dynamicContent);
  65721. }
  65722. else {
  65723. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65724. }
  65725. return this._selectionContent;
  65726. };
  65727. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  65728. this._selectionContent.reset();
  65729. for (var index = 0; index < this.blocks.length; index++) {
  65730. var block = this.blocks[index];
  65731. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  65732. }
  65733. if (allowDuplicate) {
  65734. this._selectionContent.concat(this.dynamicContent);
  65735. }
  65736. else {
  65737. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65738. }
  65739. return this._selectionContent;
  65740. };
  65741. Octree.prototype.intersectsRay = function (ray) {
  65742. this._selectionContent.reset();
  65743. for (var index = 0; index < this.blocks.length; index++) {
  65744. var block = this.blocks[index];
  65745. block.intersectsRay(ray, this._selectionContent);
  65746. }
  65747. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65748. return this._selectionContent;
  65749. };
  65750. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  65751. target.blocks = new Array();
  65752. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  65753. // Segmenting space
  65754. for (var x = 0; x < 2; x++) {
  65755. for (var y = 0; y < 2; y++) {
  65756. for (var z = 0; z < 2; z++) {
  65757. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  65758. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  65759. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  65760. block.addEntries(entries);
  65761. target.blocks.push(block);
  65762. }
  65763. }
  65764. }
  65765. };
  65766. Octree.CreationFuncForMeshes = function (entry, block) {
  65767. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  65768. block.entries.push(entry);
  65769. }
  65770. };
  65771. Octree.CreationFuncForSubMeshes = function (entry, block) {
  65772. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  65773. block.entries.push(entry);
  65774. }
  65775. };
  65776. return Octree;
  65777. }());
  65778. BABYLON.Octree = Octree;
  65779. })(BABYLON || (BABYLON = {}));
  65780. //# sourceMappingURL=babylon.octree.js.map
  65781. var BABYLON;
  65782. (function (BABYLON) {
  65783. var OctreeBlock = (function () {
  65784. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  65785. this.entries = new Array();
  65786. this._boundingVectors = new Array();
  65787. this._capacity = capacity;
  65788. this._depth = depth;
  65789. this._maxDepth = maxDepth;
  65790. this._creationFunc = creationFunc;
  65791. this._minPoint = minPoint;
  65792. this._maxPoint = maxPoint;
  65793. this._boundingVectors.push(minPoint.clone());
  65794. this._boundingVectors.push(maxPoint.clone());
  65795. this._boundingVectors.push(minPoint.clone());
  65796. this._boundingVectors[2].x = maxPoint.x;
  65797. this._boundingVectors.push(minPoint.clone());
  65798. this._boundingVectors[3].y = maxPoint.y;
  65799. this._boundingVectors.push(minPoint.clone());
  65800. this._boundingVectors[4].z = maxPoint.z;
  65801. this._boundingVectors.push(maxPoint.clone());
  65802. this._boundingVectors[5].z = minPoint.z;
  65803. this._boundingVectors.push(maxPoint.clone());
  65804. this._boundingVectors[6].x = minPoint.x;
  65805. this._boundingVectors.push(maxPoint.clone());
  65806. this._boundingVectors[7].y = minPoint.y;
  65807. }
  65808. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  65809. // Property
  65810. get: function () {
  65811. return this._capacity;
  65812. },
  65813. enumerable: true,
  65814. configurable: true
  65815. });
  65816. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  65817. get: function () {
  65818. return this._minPoint;
  65819. },
  65820. enumerable: true,
  65821. configurable: true
  65822. });
  65823. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  65824. get: function () {
  65825. return this._maxPoint;
  65826. },
  65827. enumerable: true,
  65828. configurable: true
  65829. });
  65830. // Methods
  65831. OctreeBlock.prototype.addEntry = function (entry) {
  65832. if (this.blocks) {
  65833. for (var index = 0; index < this.blocks.length; index++) {
  65834. var block = this.blocks[index];
  65835. block.addEntry(entry);
  65836. }
  65837. return;
  65838. }
  65839. this._creationFunc(entry, this);
  65840. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  65841. this.createInnerBlocks();
  65842. }
  65843. };
  65844. OctreeBlock.prototype.addEntries = function (entries) {
  65845. for (var index = 0; index < entries.length; index++) {
  65846. var mesh = entries[index];
  65847. this.addEntry(mesh);
  65848. }
  65849. };
  65850. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  65851. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  65852. if (this.blocks) {
  65853. for (var index = 0; index < this.blocks.length; index++) {
  65854. var block = this.blocks[index];
  65855. block.select(frustumPlanes, selection, allowDuplicate);
  65856. }
  65857. return;
  65858. }
  65859. if (allowDuplicate) {
  65860. selection.concat(this.entries);
  65861. }
  65862. else {
  65863. selection.concatWithNoDuplicate(this.entries);
  65864. }
  65865. }
  65866. };
  65867. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  65868. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  65869. if (this.blocks) {
  65870. for (var index = 0; index < this.blocks.length; index++) {
  65871. var block = this.blocks[index];
  65872. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  65873. }
  65874. return;
  65875. }
  65876. if (allowDuplicate) {
  65877. selection.concat(this.entries);
  65878. }
  65879. else {
  65880. selection.concatWithNoDuplicate(this.entries);
  65881. }
  65882. }
  65883. };
  65884. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  65885. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  65886. if (this.blocks) {
  65887. for (var index = 0; index < this.blocks.length; index++) {
  65888. var block = this.blocks[index];
  65889. block.intersectsRay(ray, selection);
  65890. }
  65891. return;
  65892. }
  65893. selection.concatWithNoDuplicate(this.entries);
  65894. }
  65895. };
  65896. OctreeBlock.prototype.createInnerBlocks = function () {
  65897. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  65898. };
  65899. return OctreeBlock;
  65900. }());
  65901. BABYLON.OctreeBlock = OctreeBlock;
  65902. })(BABYLON || (BABYLON = {}));
  65903. //# sourceMappingURL=babylon.octreeBlock.js.map
  65904. var BABYLON;
  65905. (function (BABYLON) {
  65906. var SIMDVector3 = (function () {
  65907. function SIMDVector3() {
  65908. }
  65909. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  65910. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  65911. };
  65912. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  65913. var m = transformation.m;
  65914. var m0 = SIMD.Float32x4.load(m, 0);
  65915. var m1 = SIMD.Float32x4.load(m, 4);
  65916. var m2 = SIMD.Float32x4.load(m, 8);
  65917. var m3 = SIMD.Float32x4.load(m, 12);
  65918. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  65919. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  65920. result.x = SIMD.Float32x4.extractLane(r, 0);
  65921. result.y = SIMD.Float32x4.extractLane(r, 1);
  65922. result.z = SIMD.Float32x4.extractLane(r, 2);
  65923. };
  65924. return SIMDVector3;
  65925. }());
  65926. var SIMDMatrix = (function () {
  65927. function SIMDMatrix() {
  65928. }
  65929. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  65930. var tm = this.m;
  65931. var om = other.m;
  65932. var m0 = SIMD.Float32x4.load(om, 0);
  65933. var m1 = SIMD.Float32x4.load(om, 4);
  65934. var m2 = SIMD.Float32x4.load(om, 8);
  65935. var m3 = SIMD.Float32x4.load(om, 12);
  65936. for (var i = 0; i < 16; i += 4) {
  65937. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  65938. }
  65939. return this;
  65940. };
  65941. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  65942. var src = this.m;
  65943. var dest = other.m;
  65944. // Load the 4 rows
  65945. var src0 = SIMD.Float32x4.load(src, 0);
  65946. var src1 = SIMD.Float32x4.load(src, 4);
  65947. var src2 = SIMD.Float32x4.load(src, 8);
  65948. var src3 = SIMD.Float32x4.load(src, 12);
  65949. // Transpose the source matrix. Sort of. Not a true transpose operation
  65950. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  65951. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  65952. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  65953. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  65954. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  65955. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  65956. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  65957. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  65958. // This is a true transposition, but it will lead to an incorrect result
  65959. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  65960. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  65961. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  65962. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  65963. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  65964. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  65965. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  65966. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  65967. // ----
  65968. tmp1 = SIMD.Float32x4.mul(row2, row3);
  65969. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65970. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  65971. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  65972. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65973. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  65974. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  65975. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  65976. // ----
  65977. tmp1 = SIMD.Float32x4.mul(row1, row2);
  65978. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65979. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  65980. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  65981. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65982. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  65983. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  65984. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  65985. // ----
  65986. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  65987. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65988. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  65989. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  65990. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  65991. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65992. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  65993. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  65994. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  65995. // ----
  65996. tmp1 = SIMD.Float32x4.mul(row0, row1);
  65997. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65998. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  65999. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  66000. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66001. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  66002. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  66003. // ----
  66004. tmp1 = SIMD.Float32x4.mul(row0, row3);
  66005. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66006. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  66007. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  66008. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66009. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  66010. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  66011. // ----
  66012. tmp1 = SIMD.Float32x4.mul(row0, row2);
  66013. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66014. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  66015. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  66016. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66017. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  66018. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  66019. // Compute determinant
  66020. var det = SIMD.Float32x4.mul(row0, minor0);
  66021. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  66022. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  66023. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  66024. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  66025. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  66026. // These shuffles aren't necessary if the faulty transposition is done
  66027. // up at the top of this function.
  66028. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  66029. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  66030. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  66031. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  66032. // Compute final values by multiplying with 1/det
  66033. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  66034. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  66035. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  66036. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  66037. return this;
  66038. };
  66039. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  66040. var out = result.m;
  66041. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  66042. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  66043. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  66044. // cc.kmVec3Subtract(f, pCenter, pEye);
  66045. var f = SIMD.Float32x4.sub(center, eye);
  66046. // cc.kmVec3Normalize(f, f);
  66047. var tmp = SIMD.Float32x4.mul(f, f);
  66048. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  66049. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  66050. // cc.kmVec3Assign(up, pUp);
  66051. // cc.kmVec3Normalize(up, up);
  66052. tmp = SIMD.Float32x4.mul(up, up);
  66053. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  66054. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  66055. // cc.kmVec3Cross(s, f, up);
  66056. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  66057. // cc.kmVec3Normalize(s, s);
  66058. tmp = SIMD.Float32x4.mul(s, s);
  66059. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  66060. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  66061. // cc.kmVec3Cross(u, s, f);
  66062. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  66063. // cc.kmVec3Normalize(s, s);
  66064. tmp = SIMD.Float32x4.mul(s, s);
  66065. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  66066. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  66067. var zero = SIMD.Float32x4.splat(0.0);
  66068. s = SIMD.Float32x4.neg(s);
  66069. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  66070. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  66071. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  66072. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  66073. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  66074. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  66075. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  66076. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  66077. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  66078. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  66079. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  66080. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  66081. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  66082. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  66083. };
  66084. return SIMDMatrix;
  66085. }());
  66086. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  66087. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  66088. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  66089. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  66090. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  66091. var SIMDHelper = (function () {
  66092. function SIMDHelper() {
  66093. }
  66094. Object.defineProperty(SIMDHelper, "IsEnabled", {
  66095. get: function () {
  66096. return SIMDHelper._isEnabled;
  66097. },
  66098. enumerable: true,
  66099. configurable: true
  66100. });
  66101. SIMDHelper.DisableSIMD = function () {
  66102. // Replace functions
  66103. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  66104. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  66105. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  66106. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  66107. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  66108. SIMDHelper._isEnabled = false;
  66109. };
  66110. SIMDHelper.EnableSIMD = function () {
  66111. if (self.SIMD === undefined) {
  66112. return;
  66113. }
  66114. // check if polyfills needed
  66115. if (!self.Math.fround) {
  66116. self.Math.fround = (function (array) { return function (x) {
  66117. return array[0] = x, array[0];
  66118. }; })(new Float32Array(1));
  66119. }
  66120. if (!self.Math.imul) {
  66121. self.Math.imul = function (a, b) {
  66122. var ah = (a >>> 16) & 0xffff;
  66123. var al = a & 0xffff;
  66124. var bh = (b >>> 16) & 0xffff;
  66125. var bl = b & 0xffff;
  66126. // the shift by 0 fixes the sign on the high part
  66127. // the final |0 converts the unsigned value into a signed value
  66128. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  66129. };
  66130. }
  66131. // Replace functions
  66132. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  66133. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  66134. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  66135. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  66136. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  66137. SIMDHelper._isEnabled = true;
  66138. };
  66139. SIMDHelper._isEnabled = false;
  66140. return SIMDHelper;
  66141. }());
  66142. BABYLON.SIMDHelper = SIMDHelper;
  66143. })(BABYLON || (BABYLON = {}));
  66144. //# sourceMappingURL=babylon.math.SIMD.js.map
  66145. var BABYLON;
  66146. (function (BABYLON) {
  66147. var VRDistortionCorrectionPostProcess = (function (_super) {
  66148. __extends(VRDistortionCorrectionPostProcess, _super);
  66149. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  66150. var _this = _super.call(this, name, "vrDistortionCorrection", [
  66151. 'LensCenter',
  66152. 'Scale',
  66153. 'ScaleIn',
  66154. 'HmdWarpParam'
  66155. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  66156. _this._isRightEye = isRightEye;
  66157. _this._distortionFactors = vrMetrics.distortionK;
  66158. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  66159. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  66160. _this.adaptScaleToCurrentViewport = true;
  66161. _this.onSizeChangedObservable.add(function () {
  66162. _this.aspectRatio = _this.width * .5 / _this.height;
  66163. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  66164. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  66165. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  66166. });
  66167. _this.onApplyObservable.add(function (effect) {
  66168. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  66169. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  66170. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  66171. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  66172. });
  66173. return _this;
  66174. }
  66175. return VRDistortionCorrectionPostProcess;
  66176. }(BABYLON.PostProcess));
  66177. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  66178. })(BABYLON || (BABYLON = {}));
  66179. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  66180. var BABYLON;
  66181. (function (BABYLON) {
  66182. var AnaglyphPostProcess = (function (_super) {
  66183. __extends(AnaglyphPostProcess, _super);
  66184. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  66185. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  66186. _this._passedProcess = rigCameras[0]._rigPostProcess;
  66187. _this.onApplyObservable.add(function (effect) {
  66188. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  66189. });
  66190. return _this;
  66191. }
  66192. return AnaglyphPostProcess;
  66193. }(BABYLON.PostProcess));
  66194. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  66195. })(BABYLON || (BABYLON = {}));
  66196. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  66197. var BABYLON;
  66198. (function (BABYLON) {
  66199. var StereoscopicInterlacePostProcess = (function (_super) {
  66200. __extends(StereoscopicInterlacePostProcess, _super);
  66201. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  66202. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  66203. _this._passedProcess = rigCameras[0]._rigPostProcess;
  66204. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  66205. _this.onSizeChangedObservable.add(function () {
  66206. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  66207. });
  66208. _this.onApplyObservable.add(function (effect) {
  66209. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  66210. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  66211. });
  66212. return _this;
  66213. }
  66214. return StereoscopicInterlacePostProcess;
  66215. }(BABYLON.PostProcess));
  66216. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  66217. })(BABYLON || (BABYLON = {}));
  66218. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  66219. var BABYLON;
  66220. (function (BABYLON) {
  66221. var FreeCameraDeviceOrientationInput = (function () {
  66222. function FreeCameraDeviceOrientationInput() {
  66223. var _this = this;
  66224. this._screenOrientationAngle = 0;
  66225. this._screenQuaternion = new BABYLON.Quaternion();
  66226. this._alpha = 0;
  66227. this._beta = 0;
  66228. this._gamma = 0;
  66229. this._orientationChanged = function () {
  66230. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  66231. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  66232. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  66233. };
  66234. this._deviceOrientation = function (evt) {
  66235. _this._alpha = evt.alpha;
  66236. _this._beta = evt.beta;
  66237. _this._gamma = evt.gamma;
  66238. };
  66239. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  66240. this._orientationChanged();
  66241. }
  66242. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  66243. get: function () {
  66244. return this._camera;
  66245. },
  66246. set: function (camera) {
  66247. this._camera = camera;
  66248. if (this._camera != null && !this._camera.rotationQuaternion) {
  66249. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  66250. }
  66251. },
  66252. enumerable: true,
  66253. configurable: true
  66254. });
  66255. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  66256. window.addEventListener("orientationchange", this._orientationChanged);
  66257. window.addEventListener("deviceorientation", this._deviceOrientation);
  66258. //In certain cases, the attach control is called AFTER orientation was changed,
  66259. //So this is needed.
  66260. this._orientationChanged();
  66261. };
  66262. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  66263. window.removeEventListener("orientationchange", this._orientationChanged);
  66264. window.removeEventListener("deviceorientation", this._deviceOrientation);
  66265. };
  66266. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  66267. //if no device orientation provided, don't update the rotation.
  66268. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  66269. if (!this._alpha)
  66270. return;
  66271. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  66272. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  66273. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  66274. //Mirror on XY Plane
  66275. this._camera.rotationQuaternion.z *= -1;
  66276. this._camera.rotationQuaternion.w *= -1;
  66277. };
  66278. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  66279. return "FreeCameraDeviceOrientationInput";
  66280. };
  66281. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  66282. return "deviceOrientation";
  66283. };
  66284. return FreeCameraDeviceOrientationInput;
  66285. }());
  66286. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  66287. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  66288. })(BABYLON || (BABYLON = {}));
  66289. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  66290. var BABYLON;
  66291. (function (BABYLON) {
  66292. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  66293. function ArcRotateCameraVRDeviceOrientationInput() {
  66294. this.alphaCorrection = 1;
  66295. this.betaCorrection = 1;
  66296. this.gammaCorrection = 1;
  66297. this._alpha = 0;
  66298. this._beta = 0;
  66299. this._gamma = 0;
  66300. this._dirty = false;
  66301. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  66302. }
  66303. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  66304. this.camera.attachControl(element, noPreventDefault);
  66305. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  66306. };
  66307. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  66308. var camera = this.camera;
  66309. this._alpha = +evt.alpha | 0;
  66310. this._beta = +evt.beta | 0;
  66311. this._gamma = +evt.gamma | 0;
  66312. this._dirty = true;
  66313. };
  66314. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  66315. if (this._dirty) {
  66316. this._dirty = false;
  66317. if (this._gamma < 0) {
  66318. this._gamma = 180 + this._gamma;
  66319. }
  66320. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  66321. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  66322. }
  66323. };
  66324. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  66325. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  66326. };
  66327. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  66328. return "ArcRotateCameraVRDeviceOrientationInput";
  66329. };
  66330. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  66331. return "VRDeviceOrientation";
  66332. };
  66333. return ArcRotateCameraVRDeviceOrientationInput;
  66334. }());
  66335. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  66336. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  66337. })(BABYLON || (BABYLON = {}));
  66338. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  66339. var BABYLON;
  66340. (function (BABYLON) {
  66341. var VRCameraMetrics = (function () {
  66342. function VRCameraMetrics() {
  66343. this.compensateDistortion = true;
  66344. }
  66345. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  66346. get: function () {
  66347. return this.hResolution / (2 * this.vResolution);
  66348. },
  66349. enumerable: true,
  66350. configurable: true
  66351. });
  66352. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  66353. get: function () {
  66354. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  66355. },
  66356. enumerable: true,
  66357. configurable: true
  66358. });
  66359. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  66360. get: function () {
  66361. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  66362. var h = (4 * meters) / this.hScreenSize;
  66363. return BABYLON.Matrix.Translation(h, 0, 0);
  66364. },
  66365. enumerable: true,
  66366. configurable: true
  66367. });
  66368. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  66369. get: function () {
  66370. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  66371. var h = (4 * meters) / this.hScreenSize;
  66372. return BABYLON.Matrix.Translation(-h, 0, 0);
  66373. },
  66374. enumerable: true,
  66375. configurable: true
  66376. });
  66377. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  66378. get: function () {
  66379. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  66380. },
  66381. enumerable: true,
  66382. configurable: true
  66383. });
  66384. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  66385. get: function () {
  66386. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  66387. },
  66388. enumerable: true,
  66389. configurable: true
  66390. });
  66391. VRCameraMetrics.GetDefault = function () {
  66392. var result = new VRCameraMetrics();
  66393. result.hResolution = 1280;
  66394. result.vResolution = 800;
  66395. result.hScreenSize = 0.149759993;
  66396. result.vScreenSize = 0.0935999975;
  66397. result.vScreenCenter = 0.0467999987;
  66398. result.eyeToScreenDistance = 0.0410000011;
  66399. result.lensSeparationDistance = 0.0635000020;
  66400. result.interpupillaryDistance = 0.0640000030;
  66401. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  66402. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  66403. result.postProcessScaleFactor = 1.714605507808412;
  66404. result.lensCenterOffset = 0.151976421;
  66405. return result;
  66406. };
  66407. return VRCameraMetrics;
  66408. }());
  66409. BABYLON.VRCameraMetrics = VRCameraMetrics;
  66410. })(BABYLON || (BABYLON = {}));
  66411. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  66412. var BABYLON;
  66413. (function (BABYLON) {
  66414. var WebVRFreeCamera = (function (_super) {
  66415. __extends(WebVRFreeCamera, _super);
  66416. function WebVRFreeCamera(name, position, scene, webVROptions) {
  66417. if (webVROptions === void 0) { webVROptions = {}; }
  66418. var _this = _super.call(this, name, position, scene) || this;
  66419. _this.webVROptions = webVROptions;
  66420. _this._vrDevice = null;
  66421. _this.rawPose = null;
  66422. _this._vrEnabled = false;
  66423. _this._specsVersion = 1.1;
  66424. _this._attached = false;
  66425. _this._positionOffset = BABYLON.Vector3.Zero();
  66426. _this._descendants = [];
  66427. _this.devicePosition = BABYLON.Vector3.Zero();
  66428. _this.deviceScaleFactor = 1;
  66429. _this.controllers = [];
  66430. _this.onControllersAttachedObservable = new BABYLON.Observable();
  66431. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  66432. _this.minZ = 0.1;
  66433. //legacy support - the compensation boolean was removed.
  66434. if (arguments.length === 5) {
  66435. _this.webVROptions = arguments[4];
  66436. }
  66437. // default webVR options
  66438. if (_this.webVROptions.trackPosition == undefined) {
  66439. _this.webVROptions.trackPosition = true;
  66440. }
  66441. if (_this.webVROptions.controllerMeshes == undefined) {
  66442. _this.webVROptions.controllerMeshes = true;
  66443. }
  66444. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  66445. _this.webVROptions.defaultLightingOnControllers = true;
  66446. }
  66447. _this.rotationQuaternion = new BABYLON.Quaternion();
  66448. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66449. if (_this.webVROptions && _this.webVROptions.positionScale) {
  66450. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  66451. }
  66452. //enable VR
  66453. _this.getEngine().initWebVR();
  66454. //check specs version
  66455. if (!window.VRFrameData) {
  66456. _this._specsVersion = 1.0;
  66457. _this._frameData = {};
  66458. }
  66459. else {
  66460. _this._frameData = new VRFrameData();
  66461. }
  66462. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  66463. if (!device) {
  66464. return;
  66465. }
  66466. _this._vrEnabled = true;
  66467. _this._vrDevice = device;
  66468. //reset the rig parameters.
  66469. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  66470. if (_this._attached) {
  66471. _this.getEngine().enableVR(_this._vrDevice);
  66472. }
  66473. });
  66474. /**
  66475. * The idea behind the following lines:
  66476. * objects that have the camera as parent should actually have the rig cameras as a parent.
  66477. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  66478. * the second will not show it correctly.
  66479. *
  66480. * To solve this - each object that has the camera as parent will be added to a protected array.
  66481. * When the rig camera renders, it will take this array and set all of those to be its children.
  66482. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  66483. * Amazing!
  66484. */
  66485. scene.onBeforeCameraRenderObservable.add(function (camera) {
  66486. if (camera.parent === _this && _this.rigParenting) {
  66487. _this._descendants = _this.getDescendants(true, function (n) {
  66488. // don't take the cameras or the controllers!
  66489. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  66490. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  66491. return !isController && !isRigCamera;
  66492. });
  66493. _this._descendants.forEach(function (node) {
  66494. node.parent = camera;
  66495. });
  66496. }
  66497. });
  66498. scene.onAfterCameraRenderObservable.add(function (camera) {
  66499. if (camera.parent === _this && _this.rigParenting) {
  66500. _this._descendants.forEach(function (node) {
  66501. node.parent = _this;
  66502. });
  66503. }
  66504. });
  66505. return _this;
  66506. }
  66507. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  66508. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  66509. var gp = _a[_i];
  66510. if (gp.hand === name) {
  66511. return gp;
  66512. }
  66513. }
  66514. return undefined;
  66515. };
  66516. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  66517. get: function () {
  66518. if (!this._leftController) {
  66519. this._leftController = this.getControllerByName("left");
  66520. }
  66521. return this._leftController;
  66522. },
  66523. enumerable: true,
  66524. configurable: true
  66525. });
  66526. ;
  66527. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  66528. get: function () {
  66529. if (!this._rightController) {
  66530. this._rightController = this.getControllerByName("right");
  66531. }
  66532. return this._rightController;
  66533. },
  66534. enumerable: true,
  66535. configurable: true
  66536. });
  66537. ;
  66538. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  66539. if (length === void 0) { length = 100; }
  66540. if (this.leftCamera) {
  66541. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  66542. }
  66543. else {
  66544. return _super.prototype.getForwardRay.call(this, length);
  66545. }
  66546. };
  66547. WebVRFreeCamera.prototype._checkInputs = function () {
  66548. if (this._vrEnabled) {
  66549. if (this._specsVersion === 1.1) {
  66550. this._vrDevice.getFrameData(this._frameData);
  66551. }
  66552. else {
  66553. //backwards comp
  66554. var pose = this._vrDevice.getPose();
  66555. this._frameData.pose = pose;
  66556. }
  66557. this.updateFromDevice(this._frameData.pose);
  66558. }
  66559. _super.prototype._checkInputs.call(this);
  66560. };
  66561. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  66562. if (poseData && poseData.orientation) {
  66563. this.rawPose = poseData;
  66564. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  66565. if (this.getScene().useRightHandedSystem) {
  66566. this.deviceRotationQuaternion.z *= -1;
  66567. this.deviceRotationQuaternion.w *= -1;
  66568. }
  66569. if (this.webVROptions.trackPosition && this.rawPose.position) {
  66570. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  66571. if (this.getScene().useRightHandedSystem) {
  66572. this.devicePosition.z *= -1;
  66573. }
  66574. }
  66575. }
  66576. };
  66577. /**
  66578. * WebVR's attach control will start broadcasting frames to the device.
  66579. * Note that in certain browsers (chrome for example) this function must be called
  66580. * within a user-interaction callback. Example:
  66581. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  66582. *
  66583. * @param {HTMLElement} element
  66584. * @param {boolean} [noPreventDefault]
  66585. *
  66586. * @memberOf WebVRFreeCamera
  66587. */
  66588. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  66589. _super.prototype.attachControl.call(this, element, noPreventDefault);
  66590. this._attached = true;
  66591. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  66592. if (this._vrEnabled) {
  66593. this.getEngine().enableVR(this._vrDevice);
  66594. }
  66595. // try to attach the controllers, if found.
  66596. this.initControllers();
  66597. };
  66598. WebVRFreeCamera.prototype.detachControl = function (element) {
  66599. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  66600. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  66601. _super.prototype.detachControl.call(this, element);
  66602. this._vrEnabled = false;
  66603. this._attached = false;
  66604. this.getEngine().disableVR();
  66605. };
  66606. WebVRFreeCamera.prototype.getClassName = function () {
  66607. return "WebVRFreeCamera";
  66608. };
  66609. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  66610. //uses the vrDisplay's "resetPose()".
  66611. //pitch and roll won't be affected.
  66612. this._vrDevice.resetPose();
  66613. };
  66614. WebVRFreeCamera.prototype._updateRigCameras = function () {
  66615. var camLeft = this._rigCameras[0];
  66616. var camRight = this._rigCameras[1];
  66617. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66618. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66619. camLeft.position.copyFrom(this.devicePosition);
  66620. camRight.position.copyFrom(this.devicePosition);
  66621. };
  66622. /**
  66623. * This function is called by the two RIG cameras.
  66624. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  66625. */
  66626. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  66627. var _this = this;
  66628. //WebVR 1.0
  66629. if (this._cameraRigParams["specs"] === 1.0) {
  66630. this._updateCameraRotationMatrix();
  66631. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  66632. // Computing target and final matrix
  66633. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  66634. if (this.getScene().useRightHandedSystem) {
  66635. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  66636. }
  66637. else {
  66638. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  66639. }
  66640. //now move the eye in the right direction
  66641. var eyeParams = this._cameraRigParams["eyeParameters"];
  66642. var offset = eyeParams.offset;
  66643. // it will actually always be 0, but just in case
  66644. if (this.getScene().useRightHandedSystem) {
  66645. offset[2] *= -1;
  66646. }
  66647. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  66648. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  66649. }
  66650. else {
  66651. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  66652. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  66653. if (!this.getScene().useRightHandedSystem) {
  66654. [2, 6, 8, 9, 14].forEach(function (num) {
  66655. _this._webvrViewMatrix.m[num] *= -1;
  66656. });
  66657. }
  66658. // update the camera rotation matrix
  66659. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  66660. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  66661. // Computing target and final matrix
  66662. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  66663. }
  66664. var parentCamera = this._cameraRigParams["parentCamera"];
  66665. // should the view matrix be updated with scale and position offset?
  66666. if (parentCamera.deviceScaleFactor !== 1) {
  66667. this._webvrViewMatrix.invert();
  66668. // scale the position, if set
  66669. if (parentCamera.deviceScaleFactor) {
  66670. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  66671. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  66672. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  66673. }
  66674. this._webvrViewMatrix.invert();
  66675. }
  66676. return this._webvrViewMatrix;
  66677. };
  66678. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  66679. var _this = this;
  66680. if (this._cameraRigParams["specs"] === 1.0) {
  66681. var eyeParams = this._cameraRigParams["eyeParameters"];
  66682. // deprecated!!
  66683. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, this.minZ, this.maxZ, this._projectionMatrix, this.getScene().useRightHandedSystem);
  66684. }
  66685. else {
  66686. var parentCamera = this.parent;
  66687. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  66688. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  66689. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  66690. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  66691. //babylon compatible matrix
  66692. if (!this.getScene().useRightHandedSystem) {
  66693. [8, 9, 10, 11].forEach(function (num) {
  66694. _this._projectionMatrix.m[num] *= -1;
  66695. });
  66696. }
  66697. }
  66698. return this._projectionMatrix;
  66699. };
  66700. WebVRFreeCamera.prototype.initControllers = function () {
  66701. var _this = this;
  66702. this.controllers = [];
  66703. var manager = this.getScene().gamepadManager;
  66704. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  66705. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  66706. var webVrController = gamepad;
  66707. if (webVrController.defaultModel) {
  66708. webVrController.defaultModel.setEnabled(false);
  66709. }
  66710. }
  66711. });
  66712. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  66713. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  66714. var webVrController = gamepad;
  66715. if (_this.webVROptions.controllerMeshes) {
  66716. if (webVrController.defaultModel) {
  66717. webVrController.defaultModel.setEnabled(true);
  66718. }
  66719. else {
  66720. // Load the meshes
  66721. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  66722. if (_this.webVROptions.defaultLightingOnControllers) {
  66723. if (!_this._lightOnControllers) {
  66724. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  66725. }
  66726. var activateLightOnSubMeshes_1 = function (mesh, light) {
  66727. var children = mesh.getChildren();
  66728. if (children.length !== 0) {
  66729. children.forEach(function (mesh) {
  66730. light.includedOnlyMeshes.push(mesh);
  66731. activateLightOnSubMeshes_1(mesh, light);
  66732. });
  66733. }
  66734. };
  66735. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  66736. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  66737. }
  66738. });
  66739. }
  66740. }
  66741. webVrController.attachToPoseControlledCamera(_this);
  66742. // since this is async - sanity check. Is the controller already stored?
  66743. if (_this.controllers.indexOf(webVrController) === -1) {
  66744. //add to the controllers array
  66745. _this.controllers.push(webVrController);
  66746. //did we find enough controllers? Great! let the developer know.
  66747. if (_this.controllers.length >= 2) {
  66748. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  66749. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  66750. // So we're overriding setting left & right manually to be sure
  66751. var firstViveWandDetected = false;
  66752. for (var i = 0; i < _this.controllers.length; i++) {
  66753. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  66754. if (!firstViveWandDetected) {
  66755. firstViveWandDetected = true;
  66756. _this.controllers[i].hand = "left";
  66757. }
  66758. else {
  66759. _this.controllers[i].hand = "right";
  66760. }
  66761. }
  66762. }
  66763. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  66764. }
  66765. }
  66766. }
  66767. });
  66768. };
  66769. return WebVRFreeCamera;
  66770. }(BABYLON.FreeCamera));
  66771. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  66772. })(BABYLON || (BABYLON = {}));
  66773. //# sourceMappingURL=babylon.webVRCamera.js.map
  66774. /// <reference path="babylon.freeCamera.ts" />
  66775. var BABYLON;
  66776. (function (BABYLON) {
  66777. // We're mainly based on the logic defined into the FreeCamera code
  66778. var DeviceOrientationCamera = (function (_super) {
  66779. __extends(DeviceOrientationCamera, _super);
  66780. function DeviceOrientationCamera(name, position, scene) {
  66781. var _this = _super.call(this, name, position, scene) || this;
  66782. _this._quaternionCache = new BABYLON.Quaternion();
  66783. _this.inputs.addDeviceOrientation();
  66784. return _this;
  66785. }
  66786. DeviceOrientationCamera.prototype.getClassName = function () {
  66787. return "DeviceOrientationCamera";
  66788. };
  66789. DeviceOrientationCamera.prototype._checkInputs = function () {
  66790. _super.prototype._checkInputs.call(this);
  66791. this._quaternionCache.copyFrom(this.rotationQuaternion);
  66792. if (this._initialQuaternion) {
  66793. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  66794. }
  66795. };
  66796. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  66797. var _this = this;
  66798. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  66799. //can only work if this camera has a rotation quaternion already.
  66800. if (!this.rotationQuaternion)
  66801. return;
  66802. if (!this._initialQuaternion) {
  66803. this._initialQuaternion = new BABYLON.Quaternion();
  66804. }
  66805. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  66806. ['x', 'y', 'z'].forEach(function (axisName) {
  66807. if (!axis[axisName]) {
  66808. _this._initialQuaternion[axisName] = 0;
  66809. }
  66810. else {
  66811. _this._initialQuaternion[axisName] *= -1;
  66812. }
  66813. });
  66814. this._initialQuaternion.normalize();
  66815. //force rotation update
  66816. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  66817. };
  66818. return DeviceOrientationCamera;
  66819. }(BABYLON.FreeCamera));
  66820. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  66821. })(BABYLON || (BABYLON = {}));
  66822. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  66823. var BABYLON;
  66824. (function (BABYLON) {
  66825. var VRDeviceOrientationFreeCamera = (function (_super) {
  66826. __extends(VRDeviceOrientationFreeCamera, _super);
  66827. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  66828. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66829. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66830. var _this = _super.call(this, name, position, scene) || this;
  66831. vrCameraMetrics.compensateDistortion = compensateDistortion;
  66832. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  66833. return _this;
  66834. }
  66835. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  66836. return "VRDeviceOrientationFreeCamera";
  66837. };
  66838. return VRDeviceOrientationFreeCamera;
  66839. }(BABYLON.DeviceOrientationCamera));
  66840. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  66841. var VRDeviceOrientationGamepadCamera = (function (_super) {
  66842. __extends(VRDeviceOrientationGamepadCamera, _super);
  66843. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  66844. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66845. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66846. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  66847. _this.inputs.addGamepad();
  66848. return _this;
  66849. }
  66850. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  66851. return "VRDeviceOrientationGamepadCamera";
  66852. };
  66853. return VRDeviceOrientationGamepadCamera;
  66854. }(VRDeviceOrientationFreeCamera));
  66855. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  66856. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  66857. __extends(VRDeviceOrientationArcRotateCamera, _super);
  66858. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  66859. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66860. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66861. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66862. vrCameraMetrics.compensateDistortion = compensateDistortion;
  66863. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  66864. _this.inputs.addVRDeviceOrientation();
  66865. return _this;
  66866. }
  66867. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  66868. return "VRDeviceOrientationArcRotateCamera";
  66869. };
  66870. return VRDeviceOrientationArcRotateCamera;
  66871. }(BABYLON.ArcRotateCamera));
  66872. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  66873. })(BABYLON || (BABYLON = {}));
  66874. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  66875. /// <reference path="babylon.freeCamera.ts" />
  66876. /// <reference path="babylon.arcRotateCamera.ts" />
  66877. /// <reference path="babylon.gamepadCamera.ts" />
  66878. /// <reference path="babylon.universalCamera.ts" />
  66879. var BABYLON;
  66880. (function (BABYLON) {
  66881. var AnaglyphFreeCamera = (function (_super) {
  66882. __extends(AnaglyphFreeCamera, _super);
  66883. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  66884. var _this = _super.call(this, name, position, scene) || this;
  66885. _this.interaxialDistance = interaxialDistance;
  66886. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66887. return _this;
  66888. }
  66889. AnaglyphFreeCamera.prototype.getClassName = function () {
  66890. return "AnaglyphFreeCamera";
  66891. };
  66892. return AnaglyphFreeCamera;
  66893. }(BABYLON.FreeCamera));
  66894. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  66895. var AnaglyphArcRotateCamera = (function (_super) {
  66896. __extends(AnaglyphArcRotateCamera, _super);
  66897. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  66898. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66899. _this.interaxialDistance = interaxialDistance;
  66900. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66901. return _this;
  66902. }
  66903. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  66904. return "AnaglyphArcRotateCamera";
  66905. };
  66906. return AnaglyphArcRotateCamera;
  66907. }(BABYLON.ArcRotateCamera));
  66908. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  66909. var AnaglyphGamepadCamera = (function (_super) {
  66910. __extends(AnaglyphGamepadCamera, _super);
  66911. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  66912. var _this = _super.call(this, name, position, scene) || this;
  66913. _this.interaxialDistance = interaxialDistance;
  66914. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66915. return _this;
  66916. }
  66917. AnaglyphGamepadCamera.prototype.getClassName = function () {
  66918. return "AnaglyphGamepadCamera";
  66919. };
  66920. return AnaglyphGamepadCamera;
  66921. }(BABYLON.GamepadCamera));
  66922. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  66923. var AnaglyphUniversalCamera = (function (_super) {
  66924. __extends(AnaglyphUniversalCamera, _super);
  66925. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  66926. var _this = _super.call(this, name, position, scene) || this;
  66927. _this.interaxialDistance = interaxialDistance;
  66928. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66929. return _this;
  66930. }
  66931. AnaglyphUniversalCamera.prototype.getClassName = function () {
  66932. return "AnaglyphUniversalCamera";
  66933. };
  66934. return AnaglyphUniversalCamera;
  66935. }(BABYLON.UniversalCamera));
  66936. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  66937. var StereoscopicFreeCamera = (function (_super) {
  66938. __extends(StereoscopicFreeCamera, _super);
  66939. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66940. var _this = _super.call(this, name, position, scene) || this;
  66941. _this.interaxialDistance = interaxialDistance;
  66942. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66943. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66944. return _this;
  66945. }
  66946. StereoscopicFreeCamera.prototype.getClassName = function () {
  66947. return "StereoscopicFreeCamera";
  66948. };
  66949. return StereoscopicFreeCamera;
  66950. }(BABYLON.FreeCamera));
  66951. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  66952. var StereoscopicArcRotateCamera = (function (_super) {
  66953. __extends(StereoscopicArcRotateCamera, _super);
  66954. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  66955. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66956. _this.interaxialDistance = interaxialDistance;
  66957. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66958. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66959. return _this;
  66960. }
  66961. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  66962. return "StereoscopicArcRotateCamera";
  66963. };
  66964. return StereoscopicArcRotateCamera;
  66965. }(BABYLON.ArcRotateCamera));
  66966. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  66967. var StereoscopicGamepadCamera = (function (_super) {
  66968. __extends(StereoscopicGamepadCamera, _super);
  66969. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66970. var _this = _super.call(this, name, position, scene) || this;
  66971. _this.interaxialDistance = interaxialDistance;
  66972. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66973. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66974. return _this;
  66975. }
  66976. StereoscopicGamepadCamera.prototype.getClassName = function () {
  66977. return "StereoscopicGamepadCamera";
  66978. };
  66979. return StereoscopicGamepadCamera;
  66980. }(BABYLON.GamepadCamera));
  66981. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  66982. var StereoscopicUniversalCamera = (function (_super) {
  66983. __extends(StereoscopicUniversalCamera, _super);
  66984. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66985. var _this = _super.call(this, name, position, scene) || this;
  66986. _this.interaxialDistance = interaxialDistance;
  66987. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66988. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66989. return _this;
  66990. }
  66991. StereoscopicUniversalCamera.prototype.getClassName = function () {
  66992. return "StereoscopicUniversalCamera";
  66993. };
  66994. return StereoscopicUniversalCamera;
  66995. }(BABYLON.UniversalCamera));
  66996. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  66997. })(BABYLON || (BABYLON = {}));
  66998. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  66999. var BABYLON;
  67000. (function (BABYLON) {
  67001. var VRExperienceHelper = (function () {
  67002. function VRExperienceHelper(scene, webVROptions) {
  67003. if (webVROptions === void 0) { webVROptions = {}; }
  67004. var _this = this;
  67005. this.webVROptions = webVROptions;
  67006. this._webVRsupportedAndReady = false;
  67007. this._isInVRMode = false;
  67008. this._scene = scene;
  67009. if (!this._scene.activeCamera) {
  67010. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  67011. }
  67012. else {
  67013. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  67014. if (scene.activeCamera.rotation) {
  67015. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  67016. }
  67017. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  67018. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  67019. }
  67020. this._scene.activeCamera = this._deviceOrientationCamera;
  67021. this._position = this._scene.activeCamera.position;
  67022. this._canvas = scene.getEngine().getRenderingCanvas();
  67023. this._scene.activeCamera.attachControl(this._canvas);
  67024. this._btnVR = document.createElement("BUTTON");
  67025. this._btnVR.className = "babylonVRicon";
  67026. this._btnVR.id = "babylonVRiconbtn";
  67027. this._btnVR.title = "Click to switch to VR";
  67028. var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";
  67029. var style = document.createElement('style');
  67030. style.appendChild(document.createTextNode(css));
  67031. document.getElementsByTagName('head')[0].appendChild(style);
  67032. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  67033. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  67034. window.addEventListener("resize", function () {
  67035. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  67036. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  67037. });
  67038. // Exiting VR mode using 'ESC' key on desktop
  67039. document.addEventListener("keydown", function (event) {
  67040. if (event.keyCode === 27 && _this._isInVRMode) {
  67041. _this.exitVR();
  67042. }
  67043. });
  67044. // Exiting VR mode double tapping the touch screen
  67045. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  67046. if (_this._isInVRMode) {
  67047. _this.exitVR();
  67048. }
  67049. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  67050. if (navigator.getVRDisplays) {
  67051. navigator.getVRDisplays().then(function (headsets) {
  67052. if (headsets.length > 0) {
  67053. _this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", _this._position, _this._scene);
  67054. _this._webVRsupportedAndReady = true;
  67055. }
  67056. else {
  67057. _this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", _this._position, _this._scene);
  67058. }
  67059. document.body.appendChild(_this._btnVR);
  67060. });
  67061. }
  67062. else {
  67063. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  67064. document.body.appendChild(this._btnVR);
  67065. }
  67066. this._btnVR.addEventListener("click", function () {
  67067. _this.enterVR();
  67068. });
  67069. }
  67070. VRExperienceHelper.prototype.enterVR = function () {
  67071. // If WebVR is supported and a headset is connected
  67072. if (this._webVRsupportedAndReady) {
  67073. this._webVRCamera.position = this._position;
  67074. this._scene.activeCamera = this._webVRCamera;
  67075. }
  67076. else {
  67077. this._vrDeviceOrientationCamera.position = this._position;
  67078. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  67079. this._scene.getEngine().switchFullscreen(true);
  67080. }
  67081. this._scene.activeCamera.attachControl(this._canvas);
  67082. this._isInVRMode = true;
  67083. this._btnVR.style.display = "none";
  67084. };
  67085. VRExperienceHelper.prototype.exitVR = function () {
  67086. if (this._webVRsupportedAndReady) {
  67087. this._scene.getEngine().disableVR();
  67088. }
  67089. if (this._scene.activeCamera) {
  67090. this._position = this._scene.activeCamera.position;
  67091. }
  67092. this._deviceOrientationCamera.position = this._position;
  67093. this._scene.activeCamera = this._deviceOrientationCamera;
  67094. this._scene.activeCamera.attachControl(this._canvas);
  67095. this._isInVRMode = false;
  67096. this._btnVR.style.display = "";
  67097. };
  67098. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  67099. get: function () {
  67100. return this._position;
  67101. },
  67102. set: function (value) {
  67103. this._position = value;
  67104. this._scene.activeCamera.position = value;
  67105. },
  67106. enumerable: true,
  67107. configurable: true
  67108. });
  67109. VRExperienceHelper.prototype.dispose = function () {
  67110. if (this._isInVRMode) {
  67111. this.exitVR();
  67112. }
  67113. this._deviceOrientationCamera.dispose();
  67114. if (this._webVRCamera) {
  67115. this._webVRCamera.dispose();
  67116. }
  67117. if (this._vrDeviceOrientationCamera) {
  67118. this._vrDeviceOrientationCamera.dispose();
  67119. }
  67120. document.body.removeChild(this._btnVR);
  67121. };
  67122. VRExperienceHelper.prototype.getClassName = function () {
  67123. return "VRExperienceHelper";
  67124. };
  67125. return VRExperienceHelper;
  67126. }());
  67127. BABYLON.VRExperienceHelper = VRExperienceHelper;
  67128. })(BABYLON || (BABYLON = {}));
  67129. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  67130. // Mainly based on these 2 articles :
  67131. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  67132. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  67133. var BABYLON;
  67134. (function (BABYLON) {
  67135. var JoystickAxis;
  67136. (function (JoystickAxis) {
  67137. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  67138. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  67139. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  67140. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  67141. var VirtualJoystick = (function () {
  67142. function VirtualJoystick(leftJoystick) {
  67143. var _this = this;
  67144. if (leftJoystick) {
  67145. this._leftJoystick = true;
  67146. }
  67147. else {
  67148. this._leftJoystick = false;
  67149. }
  67150. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  67151. VirtualJoystick._globalJoystickIndex++;
  67152. // By default left & right arrow keys are moving the X
  67153. // and up & down keys are moving the Y
  67154. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  67155. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  67156. this.reverseLeftRight = false;
  67157. this.reverseUpDown = false;
  67158. // collections of pointers
  67159. this._touches = new BABYLON.StringDictionary();
  67160. this.deltaPosition = BABYLON.Vector3.Zero();
  67161. this._joystickSensibility = 25;
  67162. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  67163. this._rotationSpeed = 25;
  67164. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  67165. this._rotateOnAxisRelativeToMesh = false;
  67166. this._onResize = function (evt) {
  67167. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  67168. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  67169. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  67170. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  67171. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  67172. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  67173. };
  67174. // injecting a canvas element on top of the canvas 3D game
  67175. if (!VirtualJoystick.vjCanvas) {
  67176. window.addEventListener("resize", this._onResize, false);
  67177. VirtualJoystick.vjCanvas = document.createElement("canvas");
  67178. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  67179. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  67180. VirtualJoystick.vjCanvas.width = window.innerWidth;
  67181. VirtualJoystick.vjCanvas.height = window.innerHeight;
  67182. VirtualJoystick.vjCanvas.style.width = "100%";
  67183. VirtualJoystick.vjCanvas.style.height = "100%";
  67184. VirtualJoystick.vjCanvas.style.position = "absolute";
  67185. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  67186. VirtualJoystick.vjCanvas.style.top = "0px";
  67187. VirtualJoystick.vjCanvas.style.left = "0px";
  67188. VirtualJoystick.vjCanvas.style.zIndex = "5";
  67189. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  67190. // Support for jQuery PEP polyfill
  67191. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  67192. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  67193. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  67194. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  67195. document.body.appendChild(VirtualJoystick.vjCanvas);
  67196. }
  67197. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  67198. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  67199. this.pressed = false;
  67200. // default joystick color
  67201. this._joystickColor = "cyan";
  67202. this._joystickPointerID = -1;
  67203. // current joystick position
  67204. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  67205. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  67206. // origin joystick position
  67207. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  67208. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  67209. this._onPointerDownHandlerRef = function (evt) {
  67210. _this._onPointerDown(evt);
  67211. };
  67212. this._onPointerMoveHandlerRef = function (evt) {
  67213. _this._onPointerMove(evt);
  67214. };
  67215. this._onPointerOutHandlerRef = function (evt) {
  67216. _this._onPointerUp(evt);
  67217. };
  67218. this._onPointerUpHandlerRef = function (evt) {
  67219. _this._onPointerUp(evt);
  67220. };
  67221. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  67222. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  67223. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  67224. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  67225. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  67226. evt.preventDefault(); // Disables system menu
  67227. }, false);
  67228. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  67229. }
  67230. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  67231. this._joystickSensibility = newJoystickSensibility;
  67232. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  67233. };
  67234. VirtualJoystick.prototype._onPointerDown = function (e) {
  67235. var positionOnScreenCondition;
  67236. e.preventDefault();
  67237. if (this._leftJoystick === true) {
  67238. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  67239. }
  67240. else {
  67241. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  67242. }
  67243. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  67244. // First contact will be dedicated to the virtual joystick
  67245. this._joystickPointerID = e.pointerId;
  67246. this._joystickPointerStartPos.x = e.clientX;
  67247. this._joystickPointerStartPos.y = e.clientY;
  67248. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  67249. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  67250. this._deltaJoystickVector.x = 0;
  67251. this._deltaJoystickVector.y = 0;
  67252. this.pressed = true;
  67253. this._touches.add(e.pointerId.toString(), e);
  67254. }
  67255. else {
  67256. // You can only trigger the action buttons with a joystick declared
  67257. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  67258. this._action();
  67259. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  67260. }
  67261. }
  67262. };
  67263. VirtualJoystick.prototype._onPointerMove = function (e) {
  67264. // If the current pointer is the one associated to the joystick (first touch contact)
  67265. if (this._joystickPointerID == e.pointerId) {
  67266. this._joystickPointerPos.x = e.clientX;
  67267. this._joystickPointerPos.y = e.clientY;
  67268. this._deltaJoystickVector = this._joystickPointerPos.clone();
  67269. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  67270. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  67271. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  67272. switch (this._axisTargetedByLeftAndRight) {
  67273. case JoystickAxis.X:
  67274. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  67275. break;
  67276. case JoystickAxis.Y:
  67277. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  67278. break;
  67279. case JoystickAxis.Z:
  67280. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  67281. break;
  67282. }
  67283. var directionUpDown = this.reverseUpDown ? 1 : -1;
  67284. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  67285. switch (this._axisTargetedByUpAndDown) {
  67286. case JoystickAxis.X:
  67287. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  67288. break;
  67289. case JoystickAxis.Y:
  67290. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  67291. break;
  67292. case JoystickAxis.Z:
  67293. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  67294. break;
  67295. }
  67296. }
  67297. else {
  67298. var data = this._touches.get(e.pointerId.toString());
  67299. if (data) {
  67300. data.x = e.clientX;
  67301. data.y = e.clientY;
  67302. }
  67303. }
  67304. };
  67305. VirtualJoystick.prototype._onPointerUp = function (e) {
  67306. if (this._joystickPointerID == e.pointerId) {
  67307. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  67308. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  67309. this._joystickPointerID = -1;
  67310. this.pressed = false;
  67311. }
  67312. else {
  67313. var touch = this._touches.get(e.pointerId.toString());
  67314. if (touch) {
  67315. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  67316. }
  67317. }
  67318. this._deltaJoystickVector.x = 0;
  67319. this._deltaJoystickVector.y = 0;
  67320. this._touches.remove(e.pointerId.toString());
  67321. };
  67322. /**
  67323. * Change the color of the virtual joystick
  67324. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  67325. */
  67326. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  67327. this._joystickColor = newColor;
  67328. };
  67329. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  67330. this._action = action;
  67331. };
  67332. // Define which axis you'd like to control for left & right
  67333. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  67334. switch (axis) {
  67335. case JoystickAxis.X:
  67336. case JoystickAxis.Y:
  67337. case JoystickAxis.Z:
  67338. this._axisTargetedByLeftAndRight = axis;
  67339. break;
  67340. default:
  67341. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  67342. break;
  67343. }
  67344. };
  67345. // Define which axis you'd like to control for up & down
  67346. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  67347. switch (axis) {
  67348. case JoystickAxis.X:
  67349. case JoystickAxis.Y:
  67350. case JoystickAxis.Z:
  67351. this._axisTargetedByUpAndDown = axis;
  67352. break;
  67353. default:
  67354. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  67355. break;
  67356. }
  67357. };
  67358. VirtualJoystick.prototype._clearCanvas = function () {
  67359. if (this._leftJoystick) {
  67360. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  67361. }
  67362. else {
  67363. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  67364. }
  67365. };
  67366. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  67367. var _this = this;
  67368. if (this.pressed) {
  67369. this._touches.forEach(function (key, touch) {
  67370. if (touch.pointerId === _this._joystickPointerID) {
  67371. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  67372. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  67373. VirtualJoystick.vjCanvasContext.beginPath();
  67374. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  67375. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67376. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  67377. VirtualJoystick.vjCanvasContext.stroke();
  67378. VirtualJoystick.vjCanvasContext.closePath();
  67379. VirtualJoystick.vjCanvasContext.beginPath();
  67380. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67381. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  67382. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  67383. VirtualJoystick.vjCanvasContext.stroke();
  67384. VirtualJoystick.vjCanvasContext.closePath();
  67385. VirtualJoystick.vjCanvasContext.beginPath();
  67386. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67387. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  67388. VirtualJoystick.vjCanvasContext.stroke();
  67389. VirtualJoystick.vjCanvasContext.closePath();
  67390. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  67391. }
  67392. else {
  67393. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  67394. VirtualJoystick.vjCanvasContext.beginPath();
  67395. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  67396. VirtualJoystick.vjCanvasContext.beginPath();
  67397. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  67398. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  67399. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  67400. VirtualJoystick.vjCanvasContext.stroke();
  67401. VirtualJoystick.vjCanvasContext.closePath();
  67402. touch.prevX = touch.x;
  67403. touch.prevY = touch.y;
  67404. }
  67405. ;
  67406. });
  67407. }
  67408. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  67409. };
  67410. VirtualJoystick.prototype.releaseCanvas = function () {
  67411. if (VirtualJoystick.vjCanvas) {
  67412. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  67413. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  67414. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  67415. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  67416. window.removeEventListener("resize", this._onResize);
  67417. document.body.removeChild(VirtualJoystick.vjCanvas);
  67418. VirtualJoystick.vjCanvas = null;
  67419. }
  67420. };
  67421. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  67422. VirtualJoystick._globalJoystickIndex = 0;
  67423. return VirtualJoystick;
  67424. }());
  67425. BABYLON.VirtualJoystick = VirtualJoystick;
  67426. })(BABYLON || (BABYLON = {}));
  67427. //# sourceMappingURL=babylon.virtualJoystick.js.map
  67428. var BABYLON;
  67429. (function (BABYLON) {
  67430. // We're mainly based on the logic defined into the FreeCamera code
  67431. var VirtualJoysticksCamera = (function (_super) {
  67432. __extends(VirtualJoysticksCamera, _super);
  67433. function VirtualJoysticksCamera(name, position, scene) {
  67434. var _this = _super.call(this, name, position, scene) || this;
  67435. _this.inputs.addVirtualJoystick();
  67436. return _this;
  67437. }
  67438. VirtualJoysticksCamera.prototype.getClassName = function () {
  67439. return "VirtualJoysticksCamera";
  67440. };
  67441. return VirtualJoysticksCamera;
  67442. }(BABYLON.FreeCamera));
  67443. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  67444. })(BABYLON || (BABYLON = {}));
  67445. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  67446. var BABYLON;
  67447. (function (BABYLON) {
  67448. var FreeCameraVirtualJoystickInput = (function () {
  67449. function FreeCameraVirtualJoystickInput() {
  67450. }
  67451. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  67452. return this._leftjoystick;
  67453. };
  67454. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  67455. return this._rightjoystick;
  67456. };
  67457. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  67458. if (this._leftjoystick) {
  67459. var camera = this.camera;
  67460. var speed = camera._computeLocalCameraSpeed() * 50;
  67461. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  67462. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  67463. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  67464. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  67465. if (!this._leftjoystick.pressed) {
  67466. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  67467. }
  67468. if (!this._rightjoystick.pressed) {
  67469. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  67470. }
  67471. }
  67472. };
  67473. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  67474. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  67475. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  67476. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  67477. this._leftjoystick.setJoystickSensibility(0.15);
  67478. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  67479. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  67480. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  67481. this._rightjoystick.reverseUpDown = true;
  67482. this._rightjoystick.setJoystickSensibility(0.05);
  67483. this._rightjoystick.setJoystickColor("yellow");
  67484. };
  67485. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  67486. this._leftjoystick.releaseCanvas();
  67487. this._rightjoystick.releaseCanvas();
  67488. };
  67489. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  67490. return "FreeCameraVirtualJoystickInput";
  67491. };
  67492. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  67493. return "virtualJoystick";
  67494. };
  67495. return FreeCameraVirtualJoystickInput;
  67496. }());
  67497. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  67498. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  67499. })(BABYLON || (BABYLON = {}));
  67500. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  67501. var BABYLON;
  67502. (function (BABYLON) {
  67503. var SimplificationSettings = (function () {
  67504. function SimplificationSettings(quality, distance, optimizeMesh) {
  67505. this.quality = quality;
  67506. this.distance = distance;
  67507. this.optimizeMesh = optimizeMesh;
  67508. }
  67509. return SimplificationSettings;
  67510. }());
  67511. BABYLON.SimplificationSettings = SimplificationSettings;
  67512. var SimplificationQueue = (function () {
  67513. function SimplificationQueue() {
  67514. this.running = false;
  67515. this._simplificationArray = [];
  67516. }
  67517. SimplificationQueue.prototype.addTask = function (task) {
  67518. this._simplificationArray.push(task);
  67519. };
  67520. SimplificationQueue.prototype.executeNext = function () {
  67521. var task = this._simplificationArray.pop();
  67522. if (task) {
  67523. this.running = true;
  67524. this.runSimplification(task);
  67525. }
  67526. else {
  67527. this.running = false;
  67528. }
  67529. };
  67530. SimplificationQueue.prototype.runSimplification = function (task) {
  67531. var _this = this;
  67532. if (task.parallelProcessing) {
  67533. //parallel simplifier
  67534. task.settings.forEach(function (setting) {
  67535. var simplifier = _this.getSimplifier(task);
  67536. simplifier.simplify(setting, function (newMesh) {
  67537. task.mesh.addLODLevel(setting.distance, newMesh);
  67538. newMesh.isVisible = true;
  67539. //check if it is the last
  67540. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  67541. //all done, run the success callback.
  67542. task.successCallback();
  67543. }
  67544. _this.executeNext();
  67545. });
  67546. });
  67547. }
  67548. else {
  67549. //single simplifier.
  67550. var simplifier = this.getSimplifier(task);
  67551. var runDecimation = function (setting, callback) {
  67552. simplifier.simplify(setting, function (newMesh) {
  67553. task.mesh.addLODLevel(setting.distance, newMesh);
  67554. newMesh.isVisible = true;
  67555. //run the next quality level
  67556. callback();
  67557. });
  67558. };
  67559. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  67560. runDecimation(task.settings[loop.index], function () {
  67561. loop.executeNext();
  67562. });
  67563. }, function () {
  67564. //execution ended, run the success callback.
  67565. if (task.successCallback) {
  67566. task.successCallback();
  67567. }
  67568. _this.executeNext();
  67569. });
  67570. }
  67571. };
  67572. SimplificationQueue.prototype.getSimplifier = function (task) {
  67573. switch (task.simplificationType) {
  67574. case SimplificationType.QUADRATIC:
  67575. default:
  67576. return new QuadraticErrorSimplification(task.mesh);
  67577. }
  67578. };
  67579. return SimplificationQueue;
  67580. }());
  67581. BABYLON.SimplificationQueue = SimplificationQueue;
  67582. /**
  67583. * The implemented types of simplification.
  67584. * At the moment only Quadratic Error Decimation is implemented.
  67585. */
  67586. var SimplificationType;
  67587. (function (SimplificationType) {
  67588. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  67589. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  67590. var DecimationTriangle = (function () {
  67591. function DecimationTriangle(vertices) {
  67592. this.vertices = vertices;
  67593. this.error = new Array(4);
  67594. this.deleted = false;
  67595. this.isDirty = false;
  67596. this.deletePending = false;
  67597. this.borderFactor = 0;
  67598. }
  67599. return DecimationTriangle;
  67600. }());
  67601. BABYLON.DecimationTriangle = DecimationTriangle;
  67602. var DecimationVertex = (function () {
  67603. function DecimationVertex(position, id) {
  67604. this.position = position;
  67605. this.id = id;
  67606. this.isBorder = true;
  67607. this.q = new QuadraticMatrix();
  67608. this.triangleCount = 0;
  67609. this.triangleStart = 0;
  67610. this.originalOffsets = [];
  67611. }
  67612. DecimationVertex.prototype.updatePosition = function (newPosition) {
  67613. this.position.copyFrom(newPosition);
  67614. };
  67615. return DecimationVertex;
  67616. }());
  67617. BABYLON.DecimationVertex = DecimationVertex;
  67618. var QuadraticMatrix = (function () {
  67619. function QuadraticMatrix(data) {
  67620. this.data = new Array(10);
  67621. for (var i = 0; i < 10; ++i) {
  67622. if (data && data[i]) {
  67623. this.data[i] = data[i];
  67624. }
  67625. else {
  67626. this.data[i] = 0;
  67627. }
  67628. }
  67629. }
  67630. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  67631. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  67632. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  67633. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  67634. return det;
  67635. };
  67636. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  67637. for (var i = 0; i < 10; ++i) {
  67638. this.data[i] += matrix.data[i];
  67639. }
  67640. };
  67641. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  67642. for (var i = 0; i < 10; ++i) {
  67643. this.data[i] += data[i];
  67644. }
  67645. };
  67646. QuadraticMatrix.prototype.add = function (matrix) {
  67647. var m = new QuadraticMatrix();
  67648. for (var i = 0; i < 10; ++i) {
  67649. m.data[i] = this.data[i] + matrix.data[i];
  67650. }
  67651. return m;
  67652. };
  67653. QuadraticMatrix.FromData = function (a, b, c, d) {
  67654. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  67655. };
  67656. //returning an array to avoid garbage collection
  67657. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  67658. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  67659. };
  67660. return QuadraticMatrix;
  67661. }());
  67662. BABYLON.QuadraticMatrix = QuadraticMatrix;
  67663. var Reference = (function () {
  67664. function Reference(vertexId, triangleId) {
  67665. this.vertexId = vertexId;
  67666. this.triangleId = triangleId;
  67667. }
  67668. return Reference;
  67669. }());
  67670. BABYLON.Reference = Reference;
  67671. /**
  67672. * An implementation of the Quadratic Error simplification algorithm.
  67673. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  67674. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  67675. * @author RaananW
  67676. */
  67677. var QuadraticErrorSimplification = (function () {
  67678. function QuadraticErrorSimplification(_mesh) {
  67679. this._mesh = _mesh;
  67680. this.initialized = false;
  67681. this.syncIterations = 5000;
  67682. this.aggressiveness = 7;
  67683. this.decimationIterations = 100;
  67684. this.boundingBoxEpsilon = BABYLON.Epsilon;
  67685. }
  67686. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  67687. var _this = this;
  67688. this.initDecimatedMesh();
  67689. //iterating through the submeshes array, one after the other.
  67690. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  67691. _this.initWithMesh(loop.index, function () {
  67692. _this.runDecimation(settings, loop.index, function () {
  67693. loop.executeNext();
  67694. });
  67695. }, settings.optimizeMesh);
  67696. }, function () {
  67697. setTimeout(function () {
  67698. successCallback(_this._reconstructedMesh);
  67699. }, 0);
  67700. });
  67701. };
  67702. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  67703. var _this = this;
  67704. var gCount = 0;
  67705. triangle.vertices.forEach(function (vertex) {
  67706. var count = 0;
  67707. var vPos = vertex.position;
  67708. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  67709. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  67710. ++count;
  67711. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  67712. ++count;
  67713. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  67714. ++count;
  67715. if (count > 1) {
  67716. ++gCount;
  67717. }
  67718. ;
  67719. });
  67720. if (gCount > 1) {
  67721. console.log(triangle, gCount);
  67722. }
  67723. return gCount > 1;
  67724. };
  67725. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  67726. var _this = this;
  67727. var targetCount = ~~(this.triangles.length * settings.quality);
  67728. var deletedTriangles = 0;
  67729. var triangleCount = this.triangles.length;
  67730. var iterationFunction = function (iteration, callback) {
  67731. setTimeout(function () {
  67732. if (iteration % 5 === 0) {
  67733. _this.updateMesh(iteration === 0);
  67734. }
  67735. for (var i = 0; i < _this.triangles.length; ++i) {
  67736. _this.triangles[i].isDirty = false;
  67737. }
  67738. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  67739. var trianglesIterator = function (i) {
  67740. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  67741. var t = _this.triangles[tIdx];
  67742. if (!t)
  67743. return;
  67744. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  67745. return;
  67746. }
  67747. for (var j = 0; j < 3; ++j) {
  67748. if (t.error[j] < threshold) {
  67749. var deleted0 = [];
  67750. var deleted1 = [];
  67751. var v0 = t.vertices[j];
  67752. var v1 = t.vertices[(j + 1) % 3];
  67753. if (v0.isBorder || v1.isBorder)
  67754. continue;
  67755. var p = BABYLON.Vector3.Zero();
  67756. var n = BABYLON.Vector3.Zero();
  67757. var uv = BABYLON.Vector2.Zero();
  67758. var color = new BABYLON.Color4(0, 0, 0, 1);
  67759. _this.calculateError(v0, v1, p, n, uv, color);
  67760. var delTr = [];
  67761. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  67762. continue;
  67763. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  67764. continue;
  67765. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  67766. continue;
  67767. var uniqueArray = [];
  67768. delTr.forEach(function (deletedT) {
  67769. if (uniqueArray.indexOf(deletedT) === -1) {
  67770. deletedT.deletePending = true;
  67771. uniqueArray.push(deletedT);
  67772. }
  67773. });
  67774. if (uniqueArray.length % 2 !== 0) {
  67775. continue;
  67776. }
  67777. v0.q = v1.q.add(v0.q);
  67778. v0.updatePosition(p);
  67779. var tStart = _this.references.length;
  67780. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  67781. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  67782. var tCount = _this.references.length - tStart;
  67783. if (tCount <= v0.triangleCount) {
  67784. if (tCount) {
  67785. for (var c = 0; c < tCount; c++) {
  67786. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  67787. }
  67788. }
  67789. }
  67790. else {
  67791. v0.triangleStart = tStart;
  67792. }
  67793. v0.triangleCount = tCount;
  67794. break;
  67795. }
  67796. }
  67797. };
  67798. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  67799. }, 0);
  67800. };
  67801. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  67802. if (triangleCount - deletedTriangles <= targetCount)
  67803. loop.breakLoop();
  67804. else {
  67805. iterationFunction(loop.index, function () {
  67806. loop.executeNext();
  67807. });
  67808. }
  67809. }, function () {
  67810. setTimeout(function () {
  67811. //reconstruct this part of the mesh
  67812. _this.reconstructMesh(submeshIndex);
  67813. successCallback();
  67814. }, 0);
  67815. });
  67816. };
  67817. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  67818. var _this = this;
  67819. this.vertices = [];
  67820. this.triangles = [];
  67821. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67822. var indices = this._mesh.getIndices();
  67823. var submesh = this._mesh.subMeshes[submeshIndex];
  67824. var findInVertices = function (positionToSearch) {
  67825. if (optimizeMesh) {
  67826. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  67827. if (_this.vertices[ii].position.equals(positionToSearch)) {
  67828. return _this.vertices[ii];
  67829. }
  67830. }
  67831. }
  67832. return null;
  67833. };
  67834. var vertexReferences = [];
  67835. var vertexInit = function (i) {
  67836. var offset = i + submesh.verticesStart;
  67837. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  67838. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  67839. vertex.originalOffsets.push(offset);
  67840. if (vertex.id === _this.vertices.length) {
  67841. _this.vertices.push(vertex);
  67842. }
  67843. vertexReferences.push(vertex.id);
  67844. };
  67845. //var totalVertices = mesh.getTotalVertices();
  67846. var totalVertices = submesh.verticesCount;
  67847. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  67848. var indicesInit = function (i) {
  67849. var offset = (submesh.indexStart / 3) + i;
  67850. var pos = (offset * 3);
  67851. var i0 = indices[pos + 0];
  67852. var i1 = indices[pos + 1];
  67853. var i2 = indices[pos + 2];
  67854. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  67855. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  67856. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  67857. var triangle = new DecimationTriangle([v0, v1, v2]);
  67858. triangle.originalOffset = pos;
  67859. _this.triangles.push(triangle);
  67860. };
  67861. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  67862. _this.init(callback);
  67863. });
  67864. });
  67865. };
  67866. QuadraticErrorSimplification.prototype.init = function (callback) {
  67867. var _this = this;
  67868. var triangleInit1 = function (i) {
  67869. var t = _this.triangles[i];
  67870. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  67871. for (var j = 0; j < 3; j++) {
  67872. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  67873. }
  67874. };
  67875. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  67876. var triangleInit2 = function (i) {
  67877. var t = _this.triangles[i];
  67878. for (var j = 0; j < 3; ++j) {
  67879. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  67880. }
  67881. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  67882. };
  67883. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  67884. _this.initialized = true;
  67885. callback();
  67886. });
  67887. });
  67888. };
  67889. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  67890. var newTriangles = [];
  67891. var i;
  67892. for (i = 0; i < this.vertices.length; ++i) {
  67893. this.vertices[i].triangleCount = 0;
  67894. }
  67895. var t;
  67896. var j;
  67897. for (i = 0; i < this.triangles.length; ++i) {
  67898. if (!this.triangles[i].deleted) {
  67899. t = this.triangles[i];
  67900. for (j = 0; j < 3; ++j) {
  67901. t.vertices[j].triangleCount = 1;
  67902. }
  67903. newTriangles.push(t);
  67904. }
  67905. }
  67906. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  67907. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  67908. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  67909. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  67910. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67911. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67912. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67913. var vertexCount = 0;
  67914. for (i = 0; i < this.vertices.length; ++i) {
  67915. var vertex = this.vertices[i];
  67916. vertex.id = vertexCount;
  67917. if (vertex.triangleCount) {
  67918. vertex.originalOffsets.forEach(function (originalOffset) {
  67919. newPositionData.push(vertex.position.x);
  67920. newPositionData.push(vertex.position.y);
  67921. newPositionData.push(vertex.position.z);
  67922. newNormalData.push(normalData[originalOffset * 3]);
  67923. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  67924. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  67925. if (uvs && uvs.length) {
  67926. newUVsData.push(uvs[(originalOffset * 2)]);
  67927. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  67928. }
  67929. else if (colorsData && colorsData.length) {
  67930. newColorsData.push(colorsData[(originalOffset * 4)]);
  67931. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  67932. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  67933. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  67934. }
  67935. ++vertexCount;
  67936. });
  67937. }
  67938. }
  67939. var startingIndex = this._reconstructedMesh.getTotalIndices();
  67940. var startingVertex = this._reconstructedMesh.getTotalVertices();
  67941. var submeshesArray = this._reconstructedMesh.subMeshes;
  67942. this._reconstructedMesh.subMeshes = [];
  67943. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  67944. var originalIndices = this._mesh.getIndices();
  67945. for (i = 0; i < newTriangles.length; ++i) {
  67946. t = newTriangles[i]; //now get the new referencing point for each vertex
  67947. [0, 1, 2].forEach(function (idx) {
  67948. var id = originalIndices[t.originalOffset + idx];
  67949. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  67950. if (offset < 0)
  67951. offset = 0;
  67952. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  67953. });
  67954. }
  67955. //overwriting the old vertex buffers and indices.
  67956. this._reconstructedMesh.setIndices(newIndicesArray);
  67957. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  67958. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  67959. if (newUVsData.length > 0)
  67960. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  67961. if (newColorsData.length > 0)
  67962. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  67963. //create submesh
  67964. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  67965. if (submeshIndex > 0) {
  67966. this._reconstructedMesh.subMeshes = [];
  67967. submeshesArray.forEach(function (submesh) {
  67968. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  67969. });
  67970. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  67971. }
  67972. };
  67973. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  67974. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  67975. this._reconstructedMesh.material = this._mesh.material;
  67976. this._reconstructedMesh.parent = this._mesh.parent;
  67977. this._reconstructedMesh.isVisible = false;
  67978. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  67979. };
  67980. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  67981. for (var i = 0; i < vertex1.triangleCount; ++i) {
  67982. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  67983. if (t.deleted)
  67984. continue;
  67985. var s = this.references[vertex1.triangleStart + i].vertexId;
  67986. var v1 = t.vertices[(s + 1) % 3];
  67987. var v2 = t.vertices[(s + 2) % 3];
  67988. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  67989. deletedArray[i] = true;
  67990. delTr.push(t);
  67991. continue;
  67992. }
  67993. var d1 = v1.position.subtract(point);
  67994. d1 = d1.normalize();
  67995. var d2 = v2.position.subtract(point);
  67996. d2 = d2.normalize();
  67997. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  67998. return true;
  67999. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  68000. deletedArray[i] = false;
  68001. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  68002. return true;
  68003. }
  68004. return false;
  68005. };
  68006. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  68007. var newDeleted = deletedTriangles;
  68008. for (var i = 0; i < vertex.triangleCount; ++i) {
  68009. var ref = this.references[vertex.triangleStart + i];
  68010. var t = this.triangles[ref.triangleId];
  68011. if (t.deleted)
  68012. continue;
  68013. if (deletedArray[i] && t.deletePending) {
  68014. t.deleted = true;
  68015. newDeleted++;
  68016. continue;
  68017. }
  68018. t.vertices[ref.vertexId] = origVertex;
  68019. t.isDirty = true;
  68020. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  68021. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  68022. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  68023. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  68024. this.references.push(ref);
  68025. }
  68026. return newDeleted;
  68027. };
  68028. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  68029. for (var i = 0; i < this.vertices.length; ++i) {
  68030. var vCount = [];
  68031. var vId = [];
  68032. var v = this.vertices[i];
  68033. var j;
  68034. for (j = 0; j < v.triangleCount; ++j) {
  68035. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  68036. for (var ii = 0; ii < 3; ii++) {
  68037. var ofs = 0;
  68038. var vv = triangle.vertices[ii];
  68039. while (ofs < vCount.length) {
  68040. if (vId[ofs] === vv.id)
  68041. break;
  68042. ++ofs;
  68043. }
  68044. if (ofs === vCount.length) {
  68045. vCount.push(1);
  68046. vId.push(vv.id);
  68047. }
  68048. else {
  68049. vCount[ofs]++;
  68050. }
  68051. }
  68052. }
  68053. for (j = 0; j < vCount.length; ++j) {
  68054. if (vCount[j] === 1) {
  68055. this.vertices[vId[j]].isBorder = true;
  68056. }
  68057. else {
  68058. this.vertices[vId[j]].isBorder = false;
  68059. }
  68060. }
  68061. }
  68062. };
  68063. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  68064. if (identifyBorders === void 0) { identifyBorders = false; }
  68065. var i;
  68066. if (!identifyBorders) {
  68067. var newTrianglesVector = [];
  68068. for (i = 0; i < this.triangles.length; ++i) {
  68069. if (!this.triangles[i].deleted) {
  68070. newTrianglesVector.push(this.triangles[i]);
  68071. }
  68072. }
  68073. this.triangles = newTrianglesVector;
  68074. }
  68075. for (i = 0; i < this.vertices.length; ++i) {
  68076. this.vertices[i].triangleCount = 0;
  68077. this.vertices[i].triangleStart = 0;
  68078. }
  68079. var t;
  68080. var j;
  68081. var v;
  68082. for (i = 0; i < this.triangles.length; ++i) {
  68083. t = this.triangles[i];
  68084. for (j = 0; j < 3; ++j) {
  68085. v = t.vertices[j];
  68086. v.triangleCount++;
  68087. }
  68088. }
  68089. var tStart = 0;
  68090. for (i = 0; i < this.vertices.length; ++i) {
  68091. this.vertices[i].triangleStart = tStart;
  68092. tStart += this.vertices[i].triangleCount;
  68093. this.vertices[i].triangleCount = 0;
  68094. }
  68095. var newReferences = new Array(this.triangles.length * 3);
  68096. for (i = 0; i < this.triangles.length; ++i) {
  68097. t = this.triangles[i];
  68098. for (j = 0; j < 3; ++j) {
  68099. v = t.vertices[j];
  68100. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  68101. v.triangleCount++;
  68102. }
  68103. }
  68104. this.references = newReferences;
  68105. if (identifyBorders) {
  68106. this.identifyBorder();
  68107. }
  68108. };
  68109. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  68110. var x = point.x;
  68111. var y = point.y;
  68112. var z = point.z;
  68113. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  68114. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  68115. };
  68116. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  68117. var q = vertex1.q.add(vertex2.q);
  68118. var border = vertex1.isBorder && vertex2.isBorder;
  68119. var error = 0;
  68120. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  68121. if (qDet !== 0 && !border) {
  68122. if (!pointResult) {
  68123. pointResult = BABYLON.Vector3.Zero();
  68124. }
  68125. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  68126. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  68127. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  68128. error = this.vertexError(q, pointResult);
  68129. }
  68130. else {
  68131. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  68132. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  68133. var error1 = this.vertexError(q, vertex1.position);
  68134. var error2 = this.vertexError(q, vertex2.position);
  68135. var error3 = this.vertexError(q, p3);
  68136. error = Math.min(error1, error2, error3);
  68137. if (error === error1) {
  68138. if (pointResult) {
  68139. pointResult.copyFrom(vertex1.position);
  68140. }
  68141. }
  68142. else if (error === error2) {
  68143. if (pointResult) {
  68144. pointResult.copyFrom(vertex2.position);
  68145. }
  68146. }
  68147. else {
  68148. if (pointResult) {
  68149. pointResult.copyFrom(p3);
  68150. }
  68151. }
  68152. }
  68153. return error;
  68154. };
  68155. return QuadraticErrorSimplification;
  68156. }());
  68157. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  68158. })(BABYLON || (BABYLON = {}));
  68159. //# sourceMappingURL=babylon.meshSimplification.js.map
  68160. var BABYLON;
  68161. (function (BABYLON) {
  68162. var Internals;
  68163. (function (Internals) {
  68164. var MeshLODLevel = (function () {
  68165. function MeshLODLevel(distance, mesh) {
  68166. this.distance = distance;
  68167. this.mesh = mesh;
  68168. }
  68169. return MeshLODLevel;
  68170. }());
  68171. Internals.MeshLODLevel = MeshLODLevel;
  68172. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68173. })(BABYLON || (BABYLON = {}));
  68174. //# sourceMappingURL=babylon.meshLODLevel.js.map
  68175. var BABYLON;
  68176. (function (BABYLON) {
  68177. // Standard optimizations
  68178. var SceneOptimization = (function () {
  68179. function SceneOptimization(priority) {
  68180. if (priority === void 0) { priority = 0; }
  68181. this.priority = priority;
  68182. this.apply = function (scene) {
  68183. return true; // Return true if everything that can be done was applied
  68184. };
  68185. }
  68186. return SceneOptimization;
  68187. }());
  68188. BABYLON.SceneOptimization = SceneOptimization;
  68189. var TextureOptimization = (function (_super) {
  68190. __extends(TextureOptimization, _super);
  68191. function TextureOptimization(priority, maximumSize) {
  68192. if (priority === void 0) { priority = 0; }
  68193. if (maximumSize === void 0) { maximumSize = 1024; }
  68194. var _this = _super.call(this, priority) || this;
  68195. _this.priority = priority;
  68196. _this.maximumSize = maximumSize;
  68197. _this.apply = function (scene) {
  68198. var allDone = true;
  68199. for (var index = 0; index < scene.textures.length; index++) {
  68200. var texture = scene.textures[index];
  68201. if (!texture.canRescale || texture.getContext) {
  68202. continue;
  68203. }
  68204. var currentSize = texture.getSize();
  68205. var maxDimension = Math.max(currentSize.width, currentSize.height);
  68206. if (maxDimension > _this.maximumSize) {
  68207. texture.scale(0.5);
  68208. allDone = false;
  68209. }
  68210. }
  68211. return allDone;
  68212. };
  68213. return _this;
  68214. }
  68215. return TextureOptimization;
  68216. }(SceneOptimization));
  68217. BABYLON.TextureOptimization = TextureOptimization;
  68218. var HardwareScalingOptimization = (function (_super) {
  68219. __extends(HardwareScalingOptimization, _super);
  68220. function HardwareScalingOptimization(priority, maximumScale) {
  68221. if (priority === void 0) { priority = 0; }
  68222. if (maximumScale === void 0) { maximumScale = 2; }
  68223. var _this = _super.call(this, priority) || this;
  68224. _this.priority = priority;
  68225. _this.maximumScale = maximumScale;
  68226. _this._currentScale = 1;
  68227. _this.apply = function (scene) {
  68228. _this._currentScale++;
  68229. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  68230. return _this._currentScale >= _this.maximumScale;
  68231. };
  68232. return _this;
  68233. }
  68234. return HardwareScalingOptimization;
  68235. }(SceneOptimization));
  68236. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  68237. var ShadowsOptimization = (function (_super) {
  68238. __extends(ShadowsOptimization, _super);
  68239. function ShadowsOptimization() {
  68240. var _this = _super !== null && _super.apply(this, arguments) || this;
  68241. _this.apply = function (scene) {
  68242. scene.shadowsEnabled = false;
  68243. return true;
  68244. };
  68245. return _this;
  68246. }
  68247. return ShadowsOptimization;
  68248. }(SceneOptimization));
  68249. BABYLON.ShadowsOptimization = ShadowsOptimization;
  68250. var PostProcessesOptimization = (function (_super) {
  68251. __extends(PostProcessesOptimization, _super);
  68252. function PostProcessesOptimization() {
  68253. var _this = _super !== null && _super.apply(this, arguments) || this;
  68254. _this.apply = function (scene) {
  68255. scene.postProcessesEnabled = false;
  68256. return true;
  68257. };
  68258. return _this;
  68259. }
  68260. return PostProcessesOptimization;
  68261. }(SceneOptimization));
  68262. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  68263. var LensFlaresOptimization = (function (_super) {
  68264. __extends(LensFlaresOptimization, _super);
  68265. function LensFlaresOptimization() {
  68266. var _this = _super !== null && _super.apply(this, arguments) || this;
  68267. _this.apply = function (scene) {
  68268. scene.lensFlaresEnabled = false;
  68269. return true;
  68270. };
  68271. return _this;
  68272. }
  68273. return LensFlaresOptimization;
  68274. }(SceneOptimization));
  68275. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  68276. var ParticlesOptimization = (function (_super) {
  68277. __extends(ParticlesOptimization, _super);
  68278. function ParticlesOptimization() {
  68279. var _this = _super !== null && _super.apply(this, arguments) || this;
  68280. _this.apply = function (scene) {
  68281. scene.particlesEnabled = false;
  68282. return true;
  68283. };
  68284. return _this;
  68285. }
  68286. return ParticlesOptimization;
  68287. }(SceneOptimization));
  68288. BABYLON.ParticlesOptimization = ParticlesOptimization;
  68289. var RenderTargetsOptimization = (function (_super) {
  68290. __extends(RenderTargetsOptimization, _super);
  68291. function RenderTargetsOptimization() {
  68292. var _this = _super !== null && _super.apply(this, arguments) || this;
  68293. _this.apply = function (scene) {
  68294. scene.renderTargetsEnabled = false;
  68295. return true;
  68296. };
  68297. return _this;
  68298. }
  68299. return RenderTargetsOptimization;
  68300. }(SceneOptimization));
  68301. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  68302. var MergeMeshesOptimization = (function (_super) {
  68303. __extends(MergeMeshesOptimization, _super);
  68304. function MergeMeshesOptimization() {
  68305. var _this = _super !== null && _super.apply(this, arguments) || this;
  68306. _this._canBeMerged = function (abstractMesh) {
  68307. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  68308. return false;
  68309. }
  68310. var mesh = abstractMesh;
  68311. if (!mesh.isVisible || !mesh.isEnabled()) {
  68312. return false;
  68313. }
  68314. if (mesh.instances.length > 0) {
  68315. return false;
  68316. }
  68317. if (mesh.skeleton || mesh.hasLODLevels) {
  68318. return false;
  68319. }
  68320. if (mesh.parent) {
  68321. return false;
  68322. }
  68323. return true;
  68324. };
  68325. _this.apply = function (scene, updateSelectionTree) {
  68326. var globalPool = scene.meshes.slice(0);
  68327. var globalLength = globalPool.length;
  68328. for (var index = 0; index < globalLength; index++) {
  68329. var currentPool = new Array();
  68330. var current = globalPool[index];
  68331. // Checks
  68332. if (!_this._canBeMerged(current)) {
  68333. continue;
  68334. }
  68335. currentPool.push(current);
  68336. // Find compatible meshes
  68337. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  68338. var otherMesh = globalPool[subIndex];
  68339. if (!_this._canBeMerged(otherMesh)) {
  68340. continue;
  68341. }
  68342. if (otherMesh.material !== current.material) {
  68343. continue;
  68344. }
  68345. if (otherMesh.checkCollisions !== current.checkCollisions) {
  68346. continue;
  68347. }
  68348. currentPool.push(otherMesh);
  68349. globalLength--;
  68350. globalPool.splice(subIndex, 1);
  68351. subIndex--;
  68352. }
  68353. if (currentPool.length < 2) {
  68354. continue;
  68355. }
  68356. // Merge meshes
  68357. BABYLON.Mesh.MergeMeshes(currentPool);
  68358. }
  68359. if (updateSelectionTree != undefined) {
  68360. if (updateSelectionTree) {
  68361. scene.createOrUpdateSelectionOctree();
  68362. }
  68363. }
  68364. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  68365. scene.createOrUpdateSelectionOctree();
  68366. }
  68367. return true;
  68368. };
  68369. return _this;
  68370. }
  68371. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  68372. get: function () {
  68373. return MergeMeshesOptimization._UpdateSelectionTree;
  68374. },
  68375. set: function (value) {
  68376. MergeMeshesOptimization._UpdateSelectionTree = value;
  68377. },
  68378. enumerable: true,
  68379. configurable: true
  68380. });
  68381. MergeMeshesOptimization._UpdateSelectionTree = false;
  68382. return MergeMeshesOptimization;
  68383. }(SceneOptimization));
  68384. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  68385. // Options
  68386. var SceneOptimizerOptions = (function () {
  68387. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  68388. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  68389. if (trackerDuration === void 0) { trackerDuration = 2000; }
  68390. this.targetFrameRate = targetFrameRate;
  68391. this.trackerDuration = trackerDuration;
  68392. this.optimizations = new Array();
  68393. }
  68394. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  68395. var result = new SceneOptimizerOptions(targetFrameRate);
  68396. var priority = 0;
  68397. result.optimizations.push(new MergeMeshesOptimization(priority));
  68398. result.optimizations.push(new ShadowsOptimization(priority));
  68399. result.optimizations.push(new LensFlaresOptimization(priority));
  68400. // Next priority
  68401. priority++;
  68402. result.optimizations.push(new PostProcessesOptimization(priority));
  68403. result.optimizations.push(new ParticlesOptimization(priority));
  68404. // Next priority
  68405. priority++;
  68406. result.optimizations.push(new TextureOptimization(priority, 1024));
  68407. return result;
  68408. };
  68409. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  68410. var result = new SceneOptimizerOptions(targetFrameRate);
  68411. var priority = 0;
  68412. result.optimizations.push(new MergeMeshesOptimization(priority));
  68413. result.optimizations.push(new ShadowsOptimization(priority));
  68414. result.optimizations.push(new LensFlaresOptimization(priority));
  68415. // Next priority
  68416. priority++;
  68417. result.optimizations.push(new PostProcessesOptimization(priority));
  68418. result.optimizations.push(new ParticlesOptimization(priority));
  68419. // Next priority
  68420. priority++;
  68421. result.optimizations.push(new TextureOptimization(priority, 512));
  68422. // Next priority
  68423. priority++;
  68424. result.optimizations.push(new RenderTargetsOptimization(priority));
  68425. // Next priority
  68426. priority++;
  68427. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  68428. return result;
  68429. };
  68430. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  68431. var result = new SceneOptimizerOptions(targetFrameRate);
  68432. var priority = 0;
  68433. result.optimizations.push(new MergeMeshesOptimization(priority));
  68434. result.optimizations.push(new ShadowsOptimization(priority));
  68435. result.optimizations.push(new LensFlaresOptimization(priority));
  68436. // Next priority
  68437. priority++;
  68438. result.optimizations.push(new PostProcessesOptimization(priority));
  68439. result.optimizations.push(new ParticlesOptimization(priority));
  68440. // Next priority
  68441. priority++;
  68442. result.optimizations.push(new TextureOptimization(priority, 256));
  68443. // Next priority
  68444. priority++;
  68445. result.optimizations.push(new RenderTargetsOptimization(priority));
  68446. // Next priority
  68447. priority++;
  68448. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  68449. return result;
  68450. };
  68451. return SceneOptimizerOptions;
  68452. }());
  68453. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  68454. // Scene optimizer tool
  68455. var SceneOptimizer = (function () {
  68456. function SceneOptimizer() {
  68457. }
  68458. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  68459. // TODO: add an epsilon
  68460. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  68461. if (onSuccess) {
  68462. onSuccess();
  68463. }
  68464. return;
  68465. }
  68466. // Apply current level of optimizations
  68467. var allDone = true;
  68468. var noOptimizationApplied = true;
  68469. for (var index = 0; index < options.optimizations.length; index++) {
  68470. var optimization = options.optimizations[index];
  68471. if (optimization.priority === currentPriorityLevel) {
  68472. noOptimizationApplied = false;
  68473. allDone = allDone && optimization.apply(scene);
  68474. }
  68475. }
  68476. // If no optimization was applied, this is a failure :(
  68477. if (noOptimizationApplied) {
  68478. if (onFailure) {
  68479. onFailure();
  68480. }
  68481. return;
  68482. }
  68483. // If all optimizations were done, move to next level
  68484. if (allDone) {
  68485. currentPriorityLevel++;
  68486. }
  68487. // Let's the system running for a specific amount of time before checking FPS
  68488. scene.executeWhenReady(function () {
  68489. setTimeout(function () {
  68490. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  68491. }, options.trackerDuration);
  68492. });
  68493. };
  68494. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  68495. if (!options) {
  68496. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  68497. }
  68498. // Let's the system running for a specific amount of time before checking FPS
  68499. scene.executeWhenReady(function () {
  68500. setTimeout(function () {
  68501. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  68502. }, options.trackerDuration);
  68503. });
  68504. };
  68505. return SceneOptimizer;
  68506. }());
  68507. BABYLON.SceneOptimizer = SceneOptimizer;
  68508. })(BABYLON || (BABYLON = {}));
  68509. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  68510. var BABYLON;
  68511. (function (BABYLON) {
  68512. var OutlineRenderer = (function () {
  68513. function OutlineRenderer(scene) {
  68514. this.zOffset = 1;
  68515. this._scene = scene;
  68516. }
  68517. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  68518. var _this = this;
  68519. if (useOverlay === void 0) { useOverlay = false; }
  68520. var scene = this._scene;
  68521. var engine = this._scene.getEngine();
  68522. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68523. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  68524. return;
  68525. }
  68526. var mesh = subMesh.getRenderingMesh();
  68527. var material = subMesh.getMaterial();
  68528. engine.enableEffect(this._effect);
  68529. // Logarithmic depth
  68530. if (material.useLogarithmicDepth) {
  68531. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  68532. }
  68533. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  68534. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  68535. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68536. // Bones
  68537. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68538. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68539. }
  68540. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68541. // Alpha test
  68542. if (material && material.needAlphaTesting()) {
  68543. var alphaTexture = material.getAlphaTestTexture();
  68544. if (alphaTexture) {
  68545. this._effect.setTexture("diffuseSampler", alphaTexture);
  68546. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68547. }
  68548. }
  68549. engine.setZOffset(-this.zOffset);
  68550. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  68551. engine.setZOffset(0);
  68552. };
  68553. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  68554. var defines = [];
  68555. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68556. var mesh = subMesh.getMesh();
  68557. var material = subMesh.getMaterial();
  68558. if (material) {
  68559. // Alpha test
  68560. if (material.needAlphaTesting()) {
  68561. defines.push("#define ALPHATEST");
  68562. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68563. attribs.push(BABYLON.VertexBuffer.UVKind);
  68564. defines.push("#define UV1");
  68565. }
  68566. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68567. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68568. defines.push("#define UV2");
  68569. }
  68570. }
  68571. //Logarithmic depth
  68572. if (material.useLogarithmicDepth) {
  68573. defines.push("#define LOGARITHMICDEPTH");
  68574. }
  68575. }
  68576. // Bones
  68577. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68578. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68579. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68580. if (mesh.numBoneInfluencers > 4) {
  68581. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68582. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68583. }
  68584. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68585. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68586. }
  68587. else {
  68588. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68589. }
  68590. // Instances
  68591. if (useInstances) {
  68592. defines.push("#define INSTANCES");
  68593. attribs.push("world0");
  68594. attribs.push("world1");
  68595. attribs.push("world2");
  68596. attribs.push("world3");
  68597. }
  68598. // Get correct effect
  68599. var join = defines.join("\n");
  68600. if (this._cachedDefines !== join) {
  68601. this._cachedDefines = join;
  68602. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  68603. }
  68604. return this._effect.isReady();
  68605. };
  68606. return OutlineRenderer;
  68607. }());
  68608. BABYLON.OutlineRenderer = OutlineRenderer;
  68609. })(BABYLON || (BABYLON = {}));
  68610. //# sourceMappingURL=babylon.outlineRenderer.js.map
  68611. var BABYLON;
  68612. (function (BABYLON) {
  68613. var FaceAdjacencies = (function () {
  68614. function FaceAdjacencies() {
  68615. this.edges = new Array();
  68616. this.edgesConnectedCount = 0;
  68617. }
  68618. return FaceAdjacencies;
  68619. }());
  68620. var EdgesRenderer = (function () {
  68621. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  68622. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  68623. if (epsilon === void 0) { epsilon = 0.95; }
  68624. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  68625. this.edgesWidthScalerForOrthographic = 1000.0;
  68626. this.edgesWidthScalerForPerspective = 50.0;
  68627. this._linesPositions = new Array();
  68628. this._linesNormals = new Array();
  68629. this._linesIndices = new Array();
  68630. this._buffers = {};
  68631. this._checkVerticesInsteadOfIndices = false;
  68632. this._source = source;
  68633. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  68634. this._epsilon = epsilon;
  68635. this._prepareRessources();
  68636. this._generateEdgesLines();
  68637. }
  68638. EdgesRenderer.prototype._prepareRessources = function () {
  68639. if (this._lineShader) {
  68640. return;
  68641. }
  68642. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  68643. attributes: ["position", "normal"],
  68644. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  68645. });
  68646. this._lineShader.disableDepthWrite = true;
  68647. this._lineShader.backFaceCulling = false;
  68648. };
  68649. EdgesRenderer.prototype._rebuild = function () {
  68650. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  68651. if (buffer) {
  68652. buffer._rebuild();
  68653. }
  68654. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  68655. if (buffer) {
  68656. buffer._rebuild();
  68657. }
  68658. var scene = this._source.getScene();
  68659. var engine = scene.getEngine();
  68660. this._ib = engine.createIndexBuffer(this._linesIndices);
  68661. };
  68662. EdgesRenderer.prototype.dispose = function () {
  68663. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  68664. if (buffer) {
  68665. buffer.dispose();
  68666. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  68667. }
  68668. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  68669. if (buffer) {
  68670. buffer.dispose();
  68671. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  68672. }
  68673. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  68674. this._lineShader.dispose();
  68675. };
  68676. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  68677. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  68678. return 0;
  68679. }
  68680. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  68681. return 1;
  68682. }
  68683. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  68684. return 2;
  68685. }
  68686. return -1;
  68687. };
  68688. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  68689. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  68690. return 0;
  68691. }
  68692. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  68693. return 1;
  68694. }
  68695. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  68696. return 2;
  68697. }
  68698. return -1;
  68699. };
  68700. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  68701. var needToCreateLine;
  68702. if (edge === undefined) {
  68703. needToCreateLine = true;
  68704. }
  68705. else {
  68706. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  68707. needToCreateLine = dotProduct < this._epsilon;
  68708. }
  68709. if (needToCreateLine) {
  68710. var offset = this._linesPositions.length / 3;
  68711. var normal = p0.subtract(p1);
  68712. normal.normalize();
  68713. // Positions
  68714. this._linesPositions.push(p0.x);
  68715. this._linesPositions.push(p0.y);
  68716. this._linesPositions.push(p0.z);
  68717. this._linesPositions.push(p0.x);
  68718. this._linesPositions.push(p0.y);
  68719. this._linesPositions.push(p0.z);
  68720. this._linesPositions.push(p1.x);
  68721. this._linesPositions.push(p1.y);
  68722. this._linesPositions.push(p1.z);
  68723. this._linesPositions.push(p1.x);
  68724. this._linesPositions.push(p1.y);
  68725. this._linesPositions.push(p1.z);
  68726. // Normals
  68727. this._linesNormals.push(p1.x);
  68728. this._linesNormals.push(p1.y);
  68729. this._linesNormals.push(p1.z);
  68730. this._linesNormals.push(-1);
  68731. this._linesNormals.push(p1.x);
  68732. this._linesNormals.push(p1.y);
  68733. this._linesNormals.push(p1.z);
  68734. this._linesNormals.push(1);
  68735. this._linesNormals.push(p0.x);
  68736. this._linesNormals.push(p0.y);
  68737. this._linesNormals.push(p0.z);
  68738. this._linesNormals.push(-1);
  68739. this._linesNormals.push(p0.x);
  68740. this._linesNormals.push(p0.y);
  68741. this._linesNormals.push(p0.z);
  68742. this._linesNormals.push(1);
  68743. // Indices
  68744. this._linesIndices.push(offset);
  68745. this._linesIndices.push(offset + 1);
  68746. this._linesIndices.push(offset + 2);
  68747. this._linesIndices.push(offset);
  68748. this._linesIndices.push(offset + 2);
  68749. this._linesIndices.push(offset + 3);
  68750. }
  68751. };
  68752. EdgesRenderer.prototype._generateEdgesLines = function () {
  68753. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68754. var indices = this._source.getIndices();
  68755. // First let's find adjacencies
  68756. var adjacencies = new Array();
  68757. var faceNormals = new Array();
  68758. var index;
  68759. var faceAdjacencies;
  68760. // Prepare faces
  68761. for (index = 0; index < indices.length; index += 3) {
  68762. faceAdjacencies = new FaceAdjacencies();
  68763. var p0Index = indices[index];
  68764. var p1Index = indices[index + 1];
  68765. var p2Index = indices[index + 2];
  68766. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  68767. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  68768. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  68769. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  68770. faceNormal.normalize();
  68771. faceNormals.push(faceNormal);
  68772. adjacencies.push(faceAdjacencies);
  68773. }
  68774. // Scan
  68775. for (index = 0; index < adjacencies.length; index++) {
  68776. faceAdjacencies = adjacencies[index];
  68777. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  68778. var otherFaceAdjacencies = adjacencies[otherIndex];
  68779. if (faceAdjacencies.edgesConnectedCount === 3) {
  68780. break;
  68781. }
  68782. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  68783. continue;
  68784. }
  68785. var otherP0 = indices[otherIndex * 3];
  68786. var otherP1 = indices[otherIndex * 3 + 1];
  68787. var otherP2 = indices[otherIndex * 3 + 2];
  68788. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  68789. var otherEdgeIndex;
  68790. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  68791. continue;
  68792. }
  68793. switch (edgeIndex) {
  68794. case 0:
  68795. if (this._checkVerticesInsteadOfIndices) {
  68796. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  68797. }
  68798. else {
  68799. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  68800. }
  68801. break;
  68802. case 1:
  68803. if (this._checkVerticesInsteadOfIndices) {
  68804. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  68805. }
  68806. else {
  68807. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  68808. }
  68809. break;
  68810. case 2:
  68811. if (this._checkVerticesInsteadOfIndices) {
  68812. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  68813. }
  68814. else {
  68815. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  68816. }
  68817. break;
  68818. }
  68819. if (otherEdgeIndex === -1) {
  68820. continue;
  68821. }
  68822. faceAdjacencies.edges[edgeIndex] = otherIndex;
  68823. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  68824. faceAdjacencies.edgesConnectedCount++;
  68825. otherFaceAdjacencies.edgesConnectedCount++;
  68826. if (faceAdjacencies.edgesConnectedCount === 3) {
  68827. break;
  68828. }
  68829. }
  68830. }
  68831. }
  68832. // Create lines
  68833. for (index = 0; index < adjacencies.length; index++) {
  68834. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  68835. var current = adjacencies[index];
  68836. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  68837. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  68838. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  68839. }
  68840. // Merge into a single mesh
  68841. var engine = this._source.getScene().getEngine();
  68842. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  68843. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  68844. this._ib = engine.createIndexBuffer(this._linesIndices);
  68845. this._indicesCount = this._linesIndices.length;
  68846. };
  68847. EdgesRenderer.prototype.render = function () {
  68848. if (!this._lineShader.isReady()) {
  68849. return;
  68850. }
  68851. var scene = this._source.getScene();
  68852. var engine = scene.getEngine();
  68853. this._lineShader._preBind();
  68854. // VBOs
  68855. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  68856. scene.resetCachedMaterial();
  68857. this._lineShader.setColor4("color", this._source.edgesColor);
  68858. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  68859. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  68860. }
  68861. else {
  68862. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  68863. }
  68864. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  68865. this._lineShader.bind(this._source.getWorldMatrix());
  68866. // Draw order
  68867. engine.draw(true, 0, this._indicesCount);
  68868. this._lineShader.unbind();
  68869. engine.setDepthWrite(true);
  68870. };
  68871. return EdgesRenderer;
  68872. }());
  68873. BABYLON.EdgesRenderer = EdgesRenderer;
  68874. })(BABYLON || (BABYLON = {}));
  68875. //# sourceMappingURL=babylon.edgesRenderer.js.map
  68876. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  68877. /// <reference path="..\Math\babylon.math.ts" />
  68878. var BABYLON;
  68879. (function (BABYLON) {
  68880. /**
  68881. * Special Glow Blur post process only blurring the alpha channel
  68882. * It enforces keeping the most luminous color in the color channel.
  68883. */
  68884. var GlowBlurPostProcess = (function (_super) {
  68885. __extends(GlowBlurPostProcess, _super);
  68886. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  68887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68888. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  68889. _this.direction = direction;
  68890. _this.kernel = kernel;
  68891. _this.onApplyObservable.add(function (effect) {
  68892. effect.setFloat2("screenSize", _this.width, _this.height);
  68893. effect.setVector2("direction", _this.direction);
  68894. effect.setFloat("blurWidth", _this.kernel);
  68895. });
  68896. return _this;
  68897. }
  68898. return GlowBlurPostProcess;
  68899. }(BABYLON.PostProcess));
  68900. /**
  68901. * The highlight layer Helps adding a glow effect around a mesh.
  68902. *
  68903. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  68904. * glowy meshes to your scene.
  68905. *
  68906. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  68907. */
  68908. var HighlightLayer = (function () {
  68909. /**
  68910. * Instantiates a new highlight Layer and references it to the scene..
  68911. * @param name The name of the layer
  68912. * @param scene The scene to use the layer in
  68913. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  68914. */
  68915. function HighlightLayer(name, scene, options) {
  68916. this.name = name;
  68917. this._vertexBuffers = {};
  68918. this._mainTextureDesiredSize = { width: 0, height: 0 };
  68919. this._meshes = {};
  68920. this._maxSize = 0;
  68921. this._shouldRender = false;
  68922. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  68923. this._excludedMeshes = {};
  68924. /**
  68925. * Specifies whether or not the inner glow is ACTIVE in the layer.
  68926. */
  68927. this.innerGlow = true;
  68928. /**
  68929. * Specifies whether or not the outer glow is ACTIVE in the layer.
  68930. */
  68931. this.outerGlow = true;
  68932. /**
  68933. * Specifies wether the highlight layer is enabled or not.
  68934. */
  68935. this.isEnabled = true;
  68936. /**
  68937. * An event triggered when the highlight layer has been disposed.
  68938. * @type {BABYLON.Observable}
  68939. */
  68940. this.onDisposeObservable = new BABYLON.Observable();
  68941. /**
  68942. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  68943. * @type {BABYLON.Observable}
  68944. */
  68945. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  68946. /**
  68947. * An event triggered when the highlight layer is being blurred.
  68948. * @type {BABYLON.Observable}
  68949. */
  68950. this.onBeforeBlurObservable = new BABYLON.Observable();
  68951. /**
  68952. * An event triggered when the highlight layer has been blurred.
  68953. * @type {BABYLON.Observable}
  68954. */
  68955. this.onAfterBlurObservable = new BABYLON.Observable();
  68956. /**
  68957. * An event triggered when the glowing blurred texture is being merged in the scene.
  68958. * @type {BABYLON.Observable}
  68959. */
  68960. this.onBeforeComposeObservable = new BABYLON.Observable();
  68961. /**
  68962. * An event triggered when the glowing blurred texture has been merged in the scene.
  68963. * @type {BABYLON.Observable}
  68964. */
  68965. this.onAfterComposeObservable = new BABYLON.Observable();
  68966. /**
  68967. * An event triggered when the highlight layer changes its size.
  68968. * @type {BABYLON.Observable}
  68969. */
  68970. this.onSizeChangedObservable = new BABYLON.Observable();
  68971. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68972. var engine = scene.getEngine();
  68973. this._engine = engine;
  68974. this._maxSize = this._engine.getCaps().maxTextureSize;
  68975. this._scene.highlightLayers.push(this);
  68976. // Warn on stencil.
  68977. if (!this._engine.isStencilEnable) {
  68978. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  68979. }
  68980. // Adapt options
  68981. this._options = options || {
  68982. mainTextureRatio: 0.5,
  68983. blurTextureSizeRatio: 0.5,
  68984. blurHorizontalSize: 1.0,
  68985. blurVerticalSize: 1.0,
  68986. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  68987. };
  68988. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  68989. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  68990. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  68991. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  68992. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  68993. // VBO
  68994. var vertices = [];
  68995. vertices.push(1, 1);
  68996. vertices.push(-1, 1);
  68997. vertices.push(-1, -1);
  68998. vertices.push(1, -1);
  68999. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69000. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  69001. this._createIndexBuffer();
  69002. // Effect
  69003. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  69004. // Render target
  69005. this.setMainTextureSize();
  69006. // Create Textures and post processes
  69007. this.createTextureAndPostProcesses();
  69008. }
  69009. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  69010. /**
  69011. * Gets the horizontal size of the blur.
  69012. */
  69013. get: function () {
  69014. return this._horizontalBlurPostprocess.kernel;
  69015. },
  69016. /**
  69017. * Specifies the horizontal size of the blur.
  69018. */
  69019. set: function (value) {
  69020. this._horizontalBlurPostprocess.kernel = value;
  69021. },
  69022. enumerable: true,
  69023. configurable: true
  69024. });
  69025. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  69026. /**
  69027. * Gets the vertical size of the blur.
  69028. */
  69029. get: function () {
  69030. return this._verticalBlurPostprocess.kernel;
  69031. },
  69032. /**
  69033. * Specifies the vertical size of the blur.
  69034. */
  69035. set: function (value) {
  69036. this._verticalBlurPostprocess.kernel = value;
  69037. },
  69038. enumerable: true,
  69039. configurable: true
  69040. });
  69041. Object.defineProperty(HighlightLayer.prototype, "camera", {
  69042. /**
  69043. * Gets the camera attached to the layer.
  69044. */
  69045. get: function () {
  69046. return this._options.camera;
  69047. },
  69048. enumerable: true,
  69049. configurable: true
  69050. });
  69051. HighlightLayer.prototype._createIndexBuffer = function () {
  69052. var engine = this._scene.getEngine();
  69053. // Indices
  69054. var indices = [];
  69055. indices.push(0);
  69056. indices.push(1);
  69057. indices.push(2);
  69058. indices.push(0);
  69059. indices.push(2);
  69060. indices.push(3);
  69061. this._indexBuffer = engine.createIndexBuffer(indices);
  69062. };
  69063. HighlightLayer.prototype._rebuild = function () {
  69064. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  69065. this._createIndexBuffer();
  69066. };
  69067. /**
  69068. * Creates the render target textures and post processes used in the highlight layer.
  69069. */
  69070. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  69071. var _this = this;
  69072. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  69073. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  69074. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  69075. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  69076. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  69077. width: this._mainTextureDesiredSize.width,
  69078. height: this._mainTextureDesiredSize.height
  69079. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69080. this._mainTexture.activeCamera = this._options.camera;
  69081. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69082. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69083. this._mainTexture.anisotropicFilteringLevel = 1;
  69084. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69085. this._mainTexture.renderParticles = false;
  69086. this._mainTexture.renderList = null;
  69087. this._mainTexture.ignoreCameraViewport = true;
  69088. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  69089. width: blurTextureWidth,
  69090. height: blurTextureHeight
  69091. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69092. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69093. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69094. this._blurTexture.anisotropicFilteringLevel = 16;
  69095. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69096. this._blurTexture.renderParticles = false;
  69097. this._blurTexture.ignoreCameraViewport = true;
  69098. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69099. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  69100. effect.setTexture("textureSampler", _this._mainTexture);
  69101. });
  69102. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  69103. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69104. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  69105. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69106. });
  69107. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69108. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  69109. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69110. });
  69111. }
  69112. else {
  69113. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69114. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  69115. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69116. });
  69117. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69118. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  69119. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69120. });
  69121. }
  69122. this._mainTexture.onAfterUnbindObservable.add(function () {
  69123. _this.onBeforeBlurObservable.notifyObservers(_this);
  69124. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  69125. _this.onAfterBlurObservable.notifyObservers(_this);
  69126. });
  69127. // Custom render function
  69128. var renderSubMesh = function (subMesh) {
  69129. var mesh = subMesh.getRenderingMesh();
  69130. var scene = _this._scene;
  69131. var engine = scene.getEngine();
  69132. // Culling
  69133. engine.setState(subMesh.getMaterial().backFaceCulling);
  69134. // Managing instances
  69135. var batch = mesh._getInstancesRenderList(subMesh._id);
  69136. if (batch.mustReturn) {
  69137. return;
  69138. }
  69139. // Excluded Mesh
  69140. if (_this._excludedMeshes[mesh.uniqueId]) {
  69141. return;
  69142. }
  69143. ;
  69144. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69145. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  69146. var material = subMesh.getMaterial();
  69147. var emissiveTexture = null;
  69148. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  69149. emissiveTexture = material.emissiveTexture;
  69150. }
  69151. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  69152. engine.enableEffect(_this._glowMapGenerationEffect);
  69153. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  69154. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  69155. if (highlightLayerMesh) {
  69156. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  69157. }
  69158. else {
  69159. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  69160. }
  69161. // Alpha test
  69162. if (material && material.needAlphaTesting()) {
  69163. var alphaTexture = material.getAlphaTestTexture();
  69164. if (alphaTexture) {
  69165. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  69166. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69167. }
  69168. }
  69169. // Glow emissive only
  69170. if (emissiveTexture) {
  69171. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  69172. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  69173. }
  69174. // Bones
  69175. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69176. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69177. }
  69178. // Draw
  69179. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  69180. }
  69181. else {
  69182. // Need to reset refresh rate of the shadowMap
  69183. _this._mainTexture.resetRefreshCounter();
  69184. }
  69185. };
  69186. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69187. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  69188. var index;
  69189. var engine = _this._scene.getEngine();
  69190. if (depthOnlySubMeshes.length) {
  69191. engine.setColorWrite(false);
  69192. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69193. renderSubMesh(depthOnlySubMeshes.data[index]);
  69194. }
  69195. engine.setColorWrite(true);
  69196. }
  69197. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69198. renderSubMesh(opaqueSubMeshes.data[index]);
  69199. }
  69200. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69201. renderSubMesh(alphaTestSubMeshes.data[index]);
  69202. }
  69203. for (index = 0; index < transparentSubMeshes.length; index++) {
  69204. renderSubMesh(transparentSubMeshes.data[index]);
  69205. }
  69206. };
  69207. this._mainTexture.onClearObservable.add(function (engine) {
  69208. engine.clear(HighlightLayer.neutralColor, true, true, true);
  69209. });
  69210. };
  69211. /**
  69212. * Checks for the readiness of the element composing the layer.
  69213. * @param subMesh the mesh to check for
  69214. * @param useInstances specify wether or not to use instances to render the mesh
  69215. * @param emissiveTexture the associated emissive texture used to generate the glow
  69216. * @return true if ready otherwise, false
  69217. */
  69218. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  69219. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  69220. return false;
  69221. }
  69222. var defines = [];
  69223. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69224. var mesh = subMesh.getMesh();
  69225. var material = subMesh.getMaterial();
  69226. var uv1 = false;
  69227. var uv2 = false;
  69228. // Alpha test
  69229. if (material && material.needAlphaTesting()) {
  69230. var alphaTexture = material.getAlphaTestTexture();
  69231. if (alphaTexture) {
  69232. defines.push("#define ALPHATEST");
  69233. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  69234. alphaTexture.coordinatesIndex === 1) {
  69235. defines.push("#define DIFFUSEUV2");
  69236. uv2 = true;
  69237. }
  69238. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69239. defines.push("#define DIFFUSEUV1");
  69240. uv1 = true;
  69241. }
  69242. }
  69243. }
  69244. // Emissive
  69245. if (emissiveTexture) {
  69246. defines.push("#define EMISSIVE");
  69247. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  69248. emissiveTexture.coordinatesIndex === 1) {
  69249. defines.push("#define EMISSIVEUV2");
  69250. uv2 = true;
  69251. }
  69252. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69253. defines.push("#define EMISSIVEUV1");
  69254. uv1 = true;
  69255. }
  69256. }
  69257. if (uv1) {
  69258. attribs.push(BABYLON.VertexBuffer.UVKind);
  69259. defines.push("#define UV1");
  69260. }
  69261. if (uv2) {
  69262. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69263. defines.push("#define UV2");
  69264. }
  69265. // Bones
  69266. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69267. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69268. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69269. if (mesh.numBoneInfluencers > 4) {
  69270. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69271. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69272. }
  69273. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69274. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69275. }
  69276. else {
  69277. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69278. }
  69279. // Instances
  69280. if (useInstances) {
  69281. defines.push("#define INSTANCES");
  69282. attribs.push("world0");
  69283. attribs.push("world1");
  69284. attribs.push("world2");
  69285. attribs.push("world3");
  69286. }
  69287. // Get correct effect
  69288. var join = defines.join("\n");
  69289. if (this._cachedDefines !== join) {
  69290. this._cachedDefines = join;
  69291. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  69292. }
  69293. return this._glowMapGenerationEffect.isReady();
  69294. };
  69295. /**
  69296. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  69297. */
  69298. HighlightLayer.prototype.render = function () {
  69299. var currentEffect = this._glowMapMergeEffect;
  69300. // Check
  69301. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  69302. return;
  69303. var engine = this._scene.getEngine();
  69304. this.onBeforeComposeObservable.notifyObservers(this);
  69305. // Render
  69306. engine.enableEffect(currentEffect);
  69307. engine.setState(false);
  69308. // Cache
  69309. var previousStencilBuffer = engine.getStencilBuffer();
  69310. var previousStencilFunction = engine.getStencilFunction();
  69311. var previousStencilMask = engine.getStencilMask();
  69312. var previousStencilOperationPass = engine.getStencilOperationPass();
  69313. var previousStencilOperationFail = engine.getStencilOperationFail();
  69314. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  69315. var previousAlphaMode = engine.getAlphaMode();
  69316. // Texture
  69317. currentEffect.setTexture("textureSampler", this._blurTexture);
  69318. // VBOs
  69319. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  69320. // Stencil operations
  69321. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  69322. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  69323. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  69324. // Draw order
  69325. engine.setAlphaMode(this._options.alphaBlendingMode);
  69326. engine.setStencilMask(0x00);
  69327. engine.setStencilBuffer(true);
  69328. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  69329. if (this.outerGlow) {
  69330. currentEffect.setFloat("offset", 0);
  69331. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  69332. engine.draw(true, 0, 6);
  69333. }
  69334. if (this.innerGlow) {
  69335. currentEffect.setFloat("offset", 1);
  69336. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  69337. engine.draw(true, 0, 6);
  69338. }
  69339. // Restore Cache
  69340. engine.setStencilFunction(previousStencilFunction);
  69341. engine.setStencilMask(previousStencilMask);
  69342. engine.setAlphaMode(previousAlphaMode);
  69343. engine.setStencilBuffer(previousStencilBuffer);
  69344. engine.setStencilOperationPass(previousStencilOperationPass);
  69345. engine.setStencilOperationFail(previousStencilOperationFail);
  69346. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  69347. engine._stencilState.reset();
  69348. this.onAfterComposeObservable.notifyObservers(this);
  69349. // Handle size changes.
  69350. var size = this._mainTexture.getSize();
  69351. this.setMainTextureSize();
  69352. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  69353. // Recreate RTT and post processes on size change.
  69354. this.onSizeChangedObservable.notifyObservers(this);
  69355. this.disposeTextureAndPostProcesses();
  69356. this.createTextureAndPostProcesses();
  69357. }
  69358. };
  69359. /**
  69360. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  69361. * @param mesh The mesh to exclude from the highlight layer
  69362. */
  69363. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  69364. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  69365. if (!meshExcluded) {
  69366. this._excludedMeshes[mesh.uniqueId] = {
  69367. mesh: mesh,
  69368. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  69369. mesh.getEngine().setStencilBuffer(false);
  69370. }),
  69371. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  69372. mesh.getEngine().setStencilBuffer(true);
  69373. }),
  69374. };
  69375. }
  69376. };
  69377. /**
  69378. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  69379. * @param mesh The mesh to highlight
  69380. */
  69381. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  69382. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  69383. if (meshExcluded) {
  69384. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  69385. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  69386. }
  69387. this._excludedMeshes[mesh.uniqueId] = undefined;
  69388. };
  69389. /**
  69390. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  69391. * @param mesh The mesh to highlight
  69392. * @param color The color of the highlight
  69393. * @param glowEmissiveOnly Extract the glow from the emissive texture
  69394. */
  69395. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  69396. var _this = this;
  69397. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  69398. var meshHighlight = this._meshes[mesh.uniqueId];
  69399. if (meshHighlight) {
  69400. meshHighlight.color = color;
  69401. }
  69402. else {
  69403. this._meshes[mesh.uniqueId] = {
  69404. mesh: mesh,
  69405. color: color,
  69406. // Lambda required for capture due to Observable this context
  69407. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  69408. if (_this._excludedMeshes[mesh.uniqueId]) {
  69409. _this.defaultStencilReference(mesh);
  69410. }
  69411. else {
  69412. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  69413. }
  69414. }),
  69415. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  69416. glowEmissiveOnly: glowEmissiveOnly
  69417. };
  69418. }
  69419. this._shouldRender = true;
  69420. };
  69421. /**
  69422. * Remove a mesh from the highlight layer in order to make it stop glowing.
  69423. * @param mesh The mesh to highlight
  69424. */
  69425. HighlightLayer.prototype.removeMesh = function (mesh) {
  69426. var meshHighlight = this._meshes[mesh.uniqueId];
  69427. if (meshHighlight) {
  69428. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  69429. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  69430. }
  69431. this._meshes[mesh.uniqueId] = undefined;
  69432. this._shouldRender = false;
  69433. for (var meshHighlightToCheck in this._meshes) {
  69434. if (meshHighlightToCheck) {
  69435. this._shouldRender = true;
  69436. break;
  69437. }
  69438. }
  69439. };
  69440. /**
  69441. * Returns true if the layer contains information to display, otherwise false.
  69442. */
  69443. HighlightLayer.prototype.shouldRender = function () {
  69444. return this.isEnabled && this._shouldRender;
  69445. };
  69446. /**
  69447. * Sets the main texture desired size which is the closest power of two
  69448. * of the engine canvas size.
  69449. */
  69450. HighlightLayer.prototype.setMainTextureSize = function () {
  69451. if (this._options.mainTextureFixedSize) {
  69452. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  69453. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  69454. }
  69455. else {
  69456. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  69457. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  69458. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  69459. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  69460. }
  69461. };
  69462. /**
  69463. * Force the stencil to the normal expected value for none glowing parts
  69464. */
  69465. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  69466. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  69467. };
  69468. /**
  69469. * Dispose only the render target textures and post process.
  69470. */
  69471. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  69472. this._blurTexture.dispose();
  69473. this._mainTexture.dispose();
  69474. this._downSamplePostprocess.dispose();
  69475. this._horizontalBlurPostprocess.dispose();
  69476. this._verticalBlurPostprocess.dispose();
  69477. };
  69478. /**
  69479. * Dispose the highlight layer and free resources.
  69480. */
  69481. HighlightLayer.prototype.dispose = function () {
  69482. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69483. if (vertexBuffer) {
  69484. vertexBuffer.dispose();
  69485. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69486. }
  69487. if (this._indexBuffer) {
  69488. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69489. this._indexBuffer = null;
  69490. }
  69491. // Clean textures and post processes
  69492. this.disposeTextureAndPostProcesses();
  69493. // Clean mesh references
  69494. for (var id in this._meshes) {
  69495. var meshHighlight = this._meshes[id];
  69496. if (meshHighlight && meshHighlight.mesh) {
  69497. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  69498. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  69499. }
  69500. }
  69501. this._meshes = null;
  69502. for (var id in this._excludedMeshes) {
  69503. var meshHighlight = this._excludedMeshes[id];
  69504. if (meshHighlight) {
  69505. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  69506. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  69507. }
  69508. }
  69509. this._excludedMeshes = null;
  69510. // Remove from scene
  69511. var index = this._scene.highlightLayers.indexOf(this, 0);
  69512. if (index > -1) {
  69513. this._scene.highlightLayers.splice(index, 1);
  69514. }
  69515. // Callback
  69516. this.onDisposeObservable.notifyObservers(this);
  69517. this.onDisposeObservable.clear();
  69518. this.onBeforeRenderMainTextureObservable.clear();
  69519. this.onBeforeBlurObservable.clear();
  69520. this.onBeforeComposeObservable.clear();
  69521. this.onAfterComposeObservable.clear();
  69522. this.onSizeChangedObservable.clear();
  69523. };
  69524. /**
  69525. * The neutral color used during the preparation of the glow effect.
  69526. * This is black by default as the blend operation is a blend operation.
  69527. */
  69528. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  69529. /**
  69530. * Stencil value used for glowing meshes.
  69531. */
  69532. HighlightLayer.glowingMeshStencilReference = 0x02;
  69533. /**
  69534. * Stencil value used for the other meshes in the scene.
  69535. */
  69536. HighlightLayer.normalMeshStencilReference = 0x01;
  69537. return HighlightLayer;
  69538. }());
  69539. BABYLON.HighlightLayer = HighlightLayer;
  69540. })(BABYLON || (BABYLON = {}));
  69541. //# sourceMappingURL=babylon.highlightlayer.js.map
  69542. var BABYLON;
  69543. (function (BABYLON) {
  69544. var MeshAssetTask = (function () {
  69545. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  69546. this.name = name;
  69547. this.meshesNames = meshesNames;
  69548. this.rootUrl = rootUrl;
  69549. this.sceneFilename = sceneFilename;
  69550. this.isCompleted = false;
  69551. }
  69552. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69553. var _this = this;
  69554. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  69555. _this.loadedMeshes = meshes;
  69556. _this.loadedParticleSystems = particleSystems;
  69557. _this.loadedSkeletons = skeletons;
  69558. _this.isCompleted = true;
  69559. if (_this.onSuccess) {
  69560. _this.onSuccess(_this);
  69561. }
  69562. onSuccess();
  69563. }, null, function () {
  69564. if (_this.onError) {
  69565. _this.onError(_this);
  69566. }
  69567. onError();
  69568. });
  69569. };
  69570. return MeshAssetTask;
  69571. }());
  69572. BABYLON.MeshAssetTask = MeshAssetTask;
  69573. var TextFileAssetTask = (function () {
  69574. function TextFileAssetTask(name, url) {
  69575. this.name = name;
  69576. this.url = url;
  69577. this.isCompleted = false;
  69578. }
  69579. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69580. var _this = this;
  69581. BABYLON.Tools.LoadFile(this.url, function (data) {
  69582. _this.text = data;
  69583. _this.isCompleted = true;
  69584. if (_this.onSuccess) {
  69585. _this.onSuccess(_this);
  69586. }
  69587. onSuccess();
  69588. }, null, scene.database, false, function () {
  69589. if (_this.onError) {
  69590. _this.onError(_this);
  69591. }
  69592. onError();
  69593. });
  69594. };
  69595. return TextFileAssetTask;
  69596. }());
  69597. BABYLON.TextFileAssetTask = TextFileAssetTask;
  69598. var BinaryFileAssetTask = (function () {
  69599. function BinaryFileAssetTask(name, url) {
  69600. this.name = name;
  69601. this.url = url;
  69602. this.isCompleted = false;
  69603. }
  69604. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69605. var _this = this;
  69606. BABYLON.Tools.LoadFile(this.url, function (data) {
  69607. _this.data = data;
  69608. _this.isCompleted = true;
  69609. if (_this.onSuccess) {
  69610. _this.onSuccess(_this);
  69611. }
  69612. onSuccess();
  69613. }, null, scene.database, true, function () {
  69614. if (_this.onError) {
  69615. _this.onError(_this);
  69616. }
  69617. onError();
  69618. });
  69619. };
  69620. return BinaryFileAssetTask;
  69621. }());
  69622. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  69623. var ImageAssetTask = (function () {
  69624. function ImageAssetTask(name, url) {
  69625. this.name = name;
  69626. this.url = url;
  69627. this.isCompleted = false;
  69628. }
  69629. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69630. var _this = this;
  69631. var img = new Image();
  69632. BABYLON.Tools.SetCorsBehavior(this.url, img);
  69633. img.onload = function () {
  69634. _this.image = img;
  69635. _this.isCompleted = true;
  69636. if (_this.onSuccess) {
  69637. _this.onSuccess(_this);
  69638. }
  69639. onSuccess();
  69640. };
  69641. img.onerror = function () {
  69642. if (_this.onError) {
  69643. _this.onError(_this);
  69644. }
  69645. onError();
  69646. };
  69647. img.src = this.url;
  69648. };
  69649. return ImageAssetTask;
  69650. }());
  69651. BABYLON.ImageAssetTask = ImageAssetTask;
  69652. var TextureAssetTask = (function () {
  69653. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  69654. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69655. this.name = name;
  69656. this.url = url;
  69657. this.noMipmap = noMipmap;
  69658. this.invertY = invertY;
  69659. this.samplingMode = samplingMode;
  69660. this.isCompleted = false;
  69661. }
  69662. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69663. var _this = this;
  69664. var onload = function () {
  69665. _this.isCompleted = true;
  69666. if (_this.onSuccess) {
  69667. _this.onSuccess(_this);
  69668. }
  69669. onSuccess();
  69670. };
  69671. var onerror = function () {
  69672. if (_this.onError) {
  69673. _this.onError(_this);
  69674. }
  69675. onError();
  69676. };
  69677. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  69678. };
  69679. return TextureAssetTask;
  69680. }());
  69681. BABYLON.TextureAssetTask = TextureAssetTask;
  69682. var CubeTextureAssetTask = (function () {
  69683. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  69684. this.name = name;
  69685. this.url = url;
  69686. this.extensions = extensions;
  69687. this.noMipmap = noMipmap;
  69688. this.files = files;
  69689. this.isCompleted = false;
  69690. }
  69691. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69692. var _this = this;
  69693. var onload = function () {
  69694. _this.isCompleted = true;
  69695. if (_this.onSuccess) {
  69696. _this.onSuccess(_this);
  69697. }
  69698. onSuccess();
  69699. };
  69700. var onerror = function () {
  69701. if (_this.onError) {
  69702. _this.onError(_this);
  69703. }
  69704. onError();
  69705. };
  69706. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  69707. };
  69708. return CubeTextureAssetTask;
  69709. }());
  69710. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  69711. var HDRCubeTextureAssetTask = (function () {
  69712. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  69713. if (noMipmap === void 0) { noMipmap = false; }
  69714. if (generateHarmonics === void 0) { generateHarmonics = true; }
  69715. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  69716. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  69717. this.name = name;
  69718. this.url = url;
  69719. this.size = size;
  69720. this.noMipmap = noMipmap;
  69721. this.generateHarmonics = generateHarmonics;
  69722. this.useInGammaSpace = useInGammaSpace;
  69723. this.usePMREMGenerator = usePMREMGenerator;
  69724. this.isCompleted = false;
  69725. }
  69726. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69727. var _this = this;
  69728. var onload = function () {
  69729. _this.isCompleted = true;
  69730. if (_this.onSuccess) {
  69731. _this.onSuccess(_this);
  69732. }
  69733. onSuccess();
  69734. };
  69735. var onerror = function () {
  69736. if (_this.onError) {
  69737. _this.onError(_this);
  69738. }
  69739. onError();
  69740. };
  69741. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  69742. };
  69743. return HDRCubeTextureAssetTask;
  69744. }());
  69745. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  69746. var AssetsManager = (function () {
  69747. function AssetsManager(scene) {
  69748. this.tasks = new Array();
  69749. this.waitingTasksCount = 0;
  69750. this.useDefaultLoadingScreen = true;
  69751. this._scene = scene;
  69752. }
  69753. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  69754. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  69755. this.tasks.push(task);
  69756. return task;
  69757. };
  69758. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  69759. var task = new TextFileAssetTask(taskName, url);
  69760. this.tasks.push(task);
  69761. return task;
  69762. };
  69763. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  69764. var task = new BinaryFileAssetTask(taskName, url);
  69765. this.tasks.push(task);
  69766. return task;
  69767. };
  69768. AssetsManager.prototype.addImageTask = function (taskName, url) {
  69769. var task = new ImageAssetTask(taskName, url);
  69770. this.tasks.push(task);
  69771. return task;
  69772. };
  69773. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  69774. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69775. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  69776. this.tasks.push(task);
  69777. return task;
  69778. };
  69779. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  69780. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  69781. this.tasks.push(task);
  69782. return task;
  69783. };
  69784. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  69785. if (noMipmap === void 0) { noMipmap = false; }
  69786. if (generateHarmonics === void 0) { generateHarmonics = true; }
  69787. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  69788. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  69789. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  69790. this.tasks.push(task);
  69791. return task;
  69792. };
  69793. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  69794. this.waitingTasksCount--;
  69795. if (this.waitingTasksCount === 0) {
  69796. if (this.onFinish) {
  69797. this.onFinish(this.tasks);
  69798. }
  69799. this._scene.getEngine().hideLoadingUI();
  69800. }
  69801. };
  69802. AssetsManager.prototype._runTask = function (task) {
  69803. var _this = this;
  69804. task.run(this._scene, function () {
  69805. if (_this.onTaskSuccess) {
  69806. _this.onTaskSuccess(task);
  69807. }
  69808. _this._decreaseWaitingTasksCount();
  69809. }, function () {
  69810. if (_this.onTaskError) {
  69811. _this.onTaskError(task);
  69812. }
  69813. _this._decreaseWaitingTasksCount();
  69814. });
  69815. };
  69816. AssetsManager.prototype.reset = function () {
  69817. this.tasks = new Array();
  69818. return this;
  69819. };
  69820. AssetsManager.prototype.load = function () {
  69821. this.waitingTasksCount = this.tasks.length;
  69822. if (this.waitingTasksCount === 0) {
  69823. if (this.onFinish) {
  69824. this.onFinish(this.tasks);
  69825. }
  69826. return this;
  69827. }
  69828. if (this.useDefaultLoadingScreen) {
  69829. this._scene.getEngine().displayLoadingUI();
  69830. }
  69831. for (var index = 0; index < this.tasks.length; index++) {
  69832. var task = this.tasks[index];
  69833. this._runTask(task);
  69834. }
  69835. return this;
  69836. };
  69837. return AssetsManager;
  69838. }());
  69839. BABYLON.AssetsManager = AssetsManager;
  69840. })(BABYLON || (BABYLON = {}));
  69841. //# sourceMappingURL=babylon.assetsManager.js.map
  69842. var BABYLON;
  69843. (function (BABYLON) {
  69844. var MapTexture = (function (_super) {
  69845. __extends(MapTexture, _super);
  69846. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  69847. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69848. if (useMipMap === void 0) { useMipMap = false; }
  69849. if (margin === void 0) { margin = 0; }
  69850. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  69851. _this.name = name;
  69852. _this._size = size;
  69853. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69854. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69855. // Create the rectPackMap that will allocate portion of the texture
  69856. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  69857. // Create the texture that will store the content
  69858. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  69859. return _this;
  69860. }
  69861. /**
  69862. * Allocate a rectangle of a given size in the texture map
  69863. * @param size the size of the rectangle to allocation
  69864. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  69865. */
  69866. MapTexture.prototype.allocateRect = function (size) {
  69867. return this._rectPackingMap.addRect(size);
  69868. };
  69869. /**
  69870. * Free a given rectangle from the texture map
  69871. * @param rectInfo the instance corresponding to the rect to free.
  69872. */
  69873. MapTexture.prototype.freeRect = function (rectInfo) {
  69874. if (rectInfo) {
  69875. rectInfo.freeContent();
  69876. }
  69877. };
  69878. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  69879. /**
  69880. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  69881. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  69882. * @returns {}
  69883. */
  69884. get: function () {
  69885. return this._rectPackingMap.freeSpace;
  69886. },
  69887. enumerable: true,
  69888. configurable: true
  69889. });
  69890. /**
  69891. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  69892. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  69893. * Don't forget to call unbindTexture when you're done rendering
  69894. * @param rect the zone to render to
  69895. * @param clear true to clear the portion's color/depth data
  69896. */
  69897. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  69898. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  69899. };
  69900. /**
  69901. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  69902. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  69903. * Don't forget to call unbindTexture when you're done rendering
  69904. * @param pos the position into the texture
  69905. * @param size the portion to fit the clip space to
  69906. * @param clear true to clear the portion's color/depth data
  69907. */
  69908. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  69909. var engine = this.getScene().getEngine();
  69910. engine.bindFramebuffer(this._texture);
  69911. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  69912. if (clear) {
  69913. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  69914. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  69915. }
  69916. };
  69917. /**
  69918. * Unbind the texture map from the rendering engine.
  69919. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  69920. * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
  69921. */
  69922. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  69923. // Dump ?
  69924. if (dumpForDebug) {
  69925. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  69926. }
  69927. var engine = this.getScene().getEngine();
  69928. if (this._replacedViewport) {
  69929. engine.setViewport(this._replacedViewport);
  69930. this._replacedViewport = null;
  69931. }
  69932. engine.unBindFramebuffer(this._texture);
  69933. };
  69934. Object.defineProperty(MapTexture.prototype, "canRescale", {
  69935. get: function () {
  69936. return false;
  69937. },
  69938. enumerable: true,
  69939. configurable: true
  69940. });
  69941. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  69942. // Anyway, there's not much point to use this method for this kind of texture I guess
  69943. MapTexture.prototype.clone = function () {
  69944. return null;
  69945. };
  69946. return MapTexture;
  69947. }(BABYLON.Texture));
  69948. BABYLON.MapTexture = MapTexture;
  69949. })(BABYLON || (BABYLON = {}));
  69950. //# sourceMappingURL=babylon.mapTexture.js.map
  69951. var BABYLON;
  69952. (function (BABYLON) {
  69953. /**
  69954. * This class describe a rectangle that were added to the map.
  69955. * You have access to its coordinates either in pixel or normalized (UV)
  69956. */
  69957. var PackedRect = (function () {
  69958. function PackedRect(root, parent, pos, size) {
  69959. this._pos = pos;
  69960. this._size = size;
  69961. this._root = root;
  69962. this._parent = parent;
  69963. this._contentSize = null;
  69964. this._bottomNode = null;
  69965. this._leftNode = null;
  69966. this._initialSize = null;
  69967. this._rightNode = null;
  69968. }
  69969. Object.defineProperty(PackedRect.prototype, "pos", {
  69970. /**
  69971. * @returns the position of this node into the map
  69972. */
  69973. get: function () {
  69974. return this._pos;
  69975. },
  69976. enumerable: true,
  69977. configurable: true
  69978. });
  69979. Object.defineProperty(PackedRect.prototype, "contentSize", {
  69980. /**
  69981. * @returns the size of the rectangle this node handles
  69982. */
  69983. get: function () {
  69984. return this._contentSize;
  69985. },
  69986. enumerable: true,
  69987. configurable: true
  69988. });
  69989. /**
  69990. * Retrieve the inner position (considering the margin) and stores it into the res object
  69991. * @param res must be a valid Vector2 that will contain the inner position after this call
  69992. */
  69993. PackedRect.prototype.getInnerPosToRef = function (res) {
  69994. var m = this._root._margin;
  69995. res.x = this._pos.x + m;
  69996. res.y = this._pos.y + m;
  69997. };
  69998. /**
  69999. * Retrieve the inner size (considering the margin) and stores it into the res object
  70000. * @param res must be a valid Size that will contain the inner size after this call
  70001. */
  70002. PackedRect.prototype.getInnerSizeToRef = function (res) {
  70003. var m = this._root._margin;
  70004. res.width = this._contentSize.width - (m * 2);
  70005. res.height = this._contentSize.height - (m * 2);
  70006. };
  70007. Object.defineProperty(PackedRect.prototype, "UVs", {
  70008. /**
  70009. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  70010. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  70011. */
  70012. get: function () {
  70013. if (!this._contentSize) {
  70014. throw new Error("Can't compute UVs for this object because it's nor allocated");
  70015. }
  70016. return this.getUVsForCustomSize(this._contentSize);
  70017. },
  70018. enumerable: true,
  70019. configurable: true
  70020. });
  70021. /**
  70022. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  70023. * and then using only a part of the PackRect.
  70024. * This method will return the UVs for this part by given the custom size of what you really use
  70025. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  70026. */
  70027. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  70028. var mainWidth = this._root._size.width;
  70029. var mainHeight = this._root._size.height;
  70030. var margin = this._root._margin;
  70031. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  70032. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  70033. var uvs = new Array();
  70034. uvs.push(topLeft);
  70035. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  70036. uvs.push(rightBottom);
  70037. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  70038. return uvs;
  70039. };
  70040. /**
  70041. * Free this rectangle from the map.
  70042. * Call this method when you no longer need the rectangle to be in the map.
  70043. */
  70044. PackedRect.prototype.freeContent = function () {
  70045. if (!this.contentSize) {
  70046. return;
  70047. }
  70048. this._contentSize = null;
  70049. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  70050. this.attemptDefrag();
  70051. };
  70052. Object.defineProperty(PackedRect.prototype, "isUsed", {
  70053. get: function () {
  70054. return this._contentSize != null || this._leftNode != null;
  70055. },
  70056. enumerable: true,
  70057. configurable: true
  70058. });
  70059. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  70060. var node = this.findNode(contentSize);
  70061. // Not enough space...
  70062. if (!node) {
  70063. return null;
  70064. }
  70065. node.splitNode(contentSize);
  70066. return node;
  70067. };
  70068. PackedRect.prototype.findNode = function (size) {
  70069. var resNode = null;
  70070. var margin = this._root._margin * 2;
  70071. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  70072. if (this.isUsed) {
  70073. if (this._leftNode) {
  70074. resNode = this._leftNode.findNode(size);
  70075. }
  70076. if (!resNode && this._rightNode) {
  70077. resNode = this._rightNode.findNode(size);
  70078. }
  70079. if (!resNode && this._bottomNode) {
  70080. resNode = this._bottomNode.findNode(size);
  70081. }
  70082. }
  70083. else if (this._initialSize) {
  70084. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  70085. resNode = this;
  70086. }
  70087. else {
  70088. return null;
  70089. }
  70090. }
  70091. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  70092. resNode = this;
  70093. }
  70094. return resNode;
  70095. };
  70096. PackedRect.prototype.splitNode = function (contentSize) {
  70097. var cs = PackedRect.TpsSize;
  70098. var margin = this._root._margin * 2;
  70099. cs.copyFrom(contentSize);
  70100. cs.width += margin;
  70101. cs.height += margin;
  70102. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  70103. if (!this._contentSize && this._initialSize) {
  70104. this._contentSize = cs.clone();
  70105. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  70106. return this._leftNode.splitNode(contentSize);
  70107. }
  70108. else {
  70109. this._contentSize = cs.clone();
  70110. this._initialSize = cs.clone();
  70111. if (cs.width !== this._size.width) {
  70112. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + cs.width, this._pos.y), new BABYLON.Size(this._size.width - cs.width, cs.height));
  70113. }
  70114. if (cs.height !== this._size.height) {
  70115. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + cs.height), new BABYLON.Size(this._size.width, this._size.height - cs.height));
  70116. }
  70117. return this;
  70118. }
  70119. };
  70120. PackedRect.prototype.attemptDefrag = function () {
  70121. if (!this.isUsed && this.isRecursiveFree) {
  70122. this.clearNode();
  70123. if (this._parent) {
  70124. this._parent.attemptDefrag();
  70125. }
  70126. }
  70127. };
  70128. PackedRect.prototype.clearNode = function () {
  70129. this._initialSize = null;
  70130. this._rightNode = null;
  70131. this._bottomNode = null;
  70132. };
  70133. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  70134. get: function () {
  70135. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  70136. },
  70137. enumerable: true,
  70138. configurable: true
  70139. });
  70140. PackedRect.prototype.evalFreeSize = function (size) {
  70141. var levelSize = 0;
  70142. if (!this.isUsed) {
  70143. var margin = this._root._margin;
  70144. var is = this._initialSize;
  70145. if (is) {
  70146. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  70147. }
  70148. else {
  70149. var size_1 = this._size;
  70150. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  70151. }
  70152. }
  70153. if (this._rightNode) {
  70154. levelSize += this._rightNode.evalFreeSize(0);
  70155. }
  70156. if (this._bottomNode) {
  70157. levelSize += this._bottomNode.evalFreeSize(0);
  70158. }
  70159. return levelSize + size;
  70160. };
  70161. PackedRect.TpsSize = BABYLON.Size.Zero();
  70162. return PackedRect;
  70163. }());
  70164. BABYLON.PackedRect = PackedRect;
  70165. /**
  70166. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  70167. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  70168. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
  70169. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  70170. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  70171. */
  70172. var RectPackingMap = (function (_super) {
  70173. __extends(RectPackingMap, _super);
  70174. /**
  70175. * Create an instance of the object with a dimension using the given size
  70176. * @param size The dimension of the rectangle that will contain all the sub ones.
  70177. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  70178. */
  70179. function RectPackingMap(size, margin) {
  70180. if (margin === void 0) { margin = 0; }
  70181. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  70182. _this._margin = margin;
  70183. _this._root = _this;
  70184. return _this;
  70185. }
  70186. /**
  70187. * Add a rectangle, finding the best location to store it into the map
  70188. * @param size the dimension of the rectangle to store
  70189. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  70190. */
  70191. RectPackingMap.prototype.addRect = function (size) {
  70192. var node = this.findAndSplitNode(size);
  70193. return node;
  70194. };
  70195. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  70196. /**
  70197. * Return the current space free normalized between [0;1]
  70198. * @returns {}
  70199. */
  70200. get: function () {
  70201. var freeSize = 0;
  70202. freeSize = this.evalFreeSize(freeSize);
  70203. return freeSize / (this._size.width * this._size.height);
  70204. },
  70205. enumerable: true,
  70206. configurable: true
  70207. });
  70208. return RectPackingMap;
  70209. }(PackedRect));
  70210. BABYLON.RectPackingMap = RectPackingMap;
  70211. })(BABYLON || (BABYLON = {}));
  70212. //# sourceMappingURL=babylon.rectPackingMap.js.map
  70213. var BABYLON;
  70214. (function (BABYLON) {
  70215. /**
  70216. * This groups together the common properties used for image processing either in direct forward pass
  70217. * or through post processing effect depending on the use of the image processing pipeline in your scene
  70218. * or not.
  70219. */
  70220. var ImageProcessingConfiguration = (function () {
  70221. function ImageProcessingConfiguration() {
  70222. /**
  70223. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  70224. */
  70225. this.colorCurves = new BABYLON.ColorCurves();
  70226. this._colorCurvesEnabled = false;
  70227. this._colorGradingEnabled = false;
  70228. this._colorGradingWithGreenDepth = false;
  70229. this._colorGradingBGR = false;
  70230. this._exposure = 1.0;
  70231. this._toneMappingEnabled = false;
  70232. this._contrast = 1.0;
  70233. /**
  70234. * Vignette stretch size.
  70235. */
  70236. this.vignetteStretch = 0;
  70237. /**
  70238. * Vignette centre X Offset.
  70239. */
  70240. this.vignetteCentreX = 0;
  70241. /**
  70242. * Vignette centre Y Offset.
  70243. */
  70244. this.vignetteCentreY = 0;
  70245. /**
  70246. * Vignette weight or intensity of the vignette effect.
  70247. */
  70248. this.vignetteWeight = 1.5;
  70249. /**
  70250. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70251. * if vignetteEnabled is set to true.
  70252. */
  70253. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  70254. /**
  70255. * Camera field of view used by the Vignette effect.
  70256. */
  70257. this.vignetteCameraFov = 0.5;
  70258. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  70259. this._vignetteEnabled = false;
  70260. this._applyByPostProcess = false;
  70261. /**
  70262. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  70263. * @type {BABYLON.Observable}
  70264. */
  70265. this.onUpdateParameters = new BABYLON.Observable();
  70266. }
  70267. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  70268. /**
  70269. * Gets wether the color curves effect is enabled.
  70270. */
  70271. get: function () {
  70272. return this._colorCurvesEnabled;
  70273. },
  70274. /**
  70275. * Sets wether the color curves effect is enabled.
  70276. */
  70277. set: function (value) {
  70278. if (this._colorCurvesEnabled === value) {
  70279. return;
  70280. }
  70281. this._colorCurvesEnabled = value;
  70282. this._updateParameters();
  70283. },
  70284. enumerable: true,
  70285. configurable: true
  70286. });
  70287. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  70288. /**
  70289. * Gets wether the color grading effect is enabled.
  70290. */
  70291. get: function () {
  70292. return this._colorGradingEnabled;
  70293. },
  70294. /**
  70295. * Sets wether the color grading effect is enabled.
  70296. */
  70297. set: function (value) {
  70298. if (this._colorGradingEnabled === value) {
  70299. return;
  70300. }
  70301. this._colorGradingEnabled = value;
  70302. this._updateParameters();
  70303. },
  70304. enumerable: true,
  70305. configurable: true
  70306. });
  70307. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  70308. /**
  70309. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  70310. */
  70311. get: function () {
  70312. return this._colorGradingWithGreenDepth;
  70313. },
  70314. /**
  70315. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  70316. */
  70317. set: function (value) {
  70318. if (this._colorGradingWithGreenDepth === value) {
  70319. return;
  70320. }
  70321. this._colorGradingWithGreenDepth = value;
  70322. this._updateParameters();
  70323. },
  70324. enumerable: true,
  70325. configurable: true
  70326. });
  70327. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  70328. /**
  70329. * Gets wether the color grading texture contains BGR values.
  70330. */
  70331. get: function () {
  70332. return this._colorGradingBGR;
  70333. },
  70334. /**
  70335. * Sets wether the color grading texture contains BGR values.
  70336. */
  70337. set: function (value) {
  70338. if (this._colorGradingBGR === value) {
  70339. return;
  70340. }
  70341. this._colorGradingBGR = value;
  70342. this._updateParameters();
  70343. },
  70344. enumerable: true,
  70345. configurable: true
  70346. });
  70347. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  70348. /**
  70349. * Gets the Exposure used in the effect.
  70350. */
  70351. get: function () {
  70352. return this._exposure;
  70353. },
  70354. /**
  70355. * Sets the Exposure used in the effect.
  70356. */
  70357. set: function (value) {
  70358. if (this._exposure === value) {
  70359. return;
  70360. }
  70361. this._exposure = value;
  70362. this._updateParameters();
  70363. },
  70364. enumerable: true,
  70365. configurable: true
  70366. });
  70367. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  70368. /**
  70369. * Gets wether the tone mapping effect is enabled.
  70370. */
  70371. get: function () {
  70372. return this._toneMappingEnabled;
  70373. },
  70374. /**
  70375. * Sets wether the tone mapping effect is enabled.
  70376. */
  70377. set: function (value) {
  70378. if (this._toneMappingEnabled === value) {
  70379. return;
  70380. }
  70381. this._toneMappingEnabled = value;
  70382. this._updateParameters();
  70383. },
  70384. enumerable: true,
  70385. configurable: true
  70386. });
  70387. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  70388. /**
  70389. * Gets the contrast used in the effect.
  70390. */
  70391. get: function () {
  70392. return this._contrast;
  70393. },
  70394. /**
  70395. * Sets the contrast used in the effect.
  70396. */
  70397. set: function (value) {
  70398. if (this._contrast === value) {
  70399. return;
  70400. }
  70401. this._contrast = value;
  70402. this._updateParameters();
  70403. },
  70404. enumerable: true,
  70405. configurable: true
  70406. });
  70407. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  70408. /**
  70409. * Gets the vignette blend mode allowing different kind of effect.
  70410. */
  70411. get: function () {
  70412. return this._vignetteBlendMode;
  70413. },
  70414. /**
  70415. * Sets the vignette blend mode allowing different kind of effect.
  70416. */
  70417. set: function (value) {
  70418. if (this._vignetteBlendMode === value) {
  70419. return;
  70420. }
  70421. this._vignetteBlendMode = value;
  70422. this._updateParameters();
  70423. },
  70424. enumerable: true,
  70425. configurable: true
  70426. });
  70427. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  70428. /**
  70429. * Gets wether the vignette effect is enabled.
  70430. */
  70431. get: function () {
  70432. return this._vignetteEnabled;
  70433. },
  70434. /**
  70435. * Sets wether the vignette effect is enabled.
  70436. */
  70437. set: function (value) {
  70438. if (this._vignetteEnabled === value) {
  70439. return;
  70440. }
  70441. this._vignetteEnabled = value;
  70442. this._updateParameters();
  70443. },
  70444. enumerable: true,
  70445. configurable: true
  70446. });
  70447. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  70448. /**
  70449. * Gets wether the image processing is applied through a post process or not.
  70450. */
  70451. get: function () {
  70452. return this._applyByPostProcess;
  70453. },
  70454. /**
  70455. * Sets wether the image processing is applied through a post process or not.
  70456. */
  70457. set: function (value) {
  70458. if (this._applyByPostProcess === value) {
  70459. return;
  70460. }
  70461. this._applyByPostProcess = value;
  70462. this._updateParameters();
  70463. },
  70464. enumerable: true,
  70465. configurable: true
  70466. });
  70467. /**
  70468. * Method called each time the image processing information changes requires to recompile the effect.
  70469. */
  70470. ImageProcessingConfiguration.prototype._updateParameters = function () {
  70471. this.onUpdateParameters.notifyObservers(this);
  70472. };
  70473. ImageProcessingConfiguration.prototype.getClassName = function () {
  70474. return "ImageProcessingConfiguration";
  70475. };
  70476. /**
  70477. * Prepare the list of uniforms associated with the Image Processing effects.
  70478. * @param uniformsList The list of uniforms used in the effect
  70479. * @param defines the list of defines currently in use
  70480. */
  70481. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  70482. if (defines.EXPOSURE) {
  70483. uniforms.push("exposureLinear");
  70484. }
  70485. if (defines.CONTRAST) {
  70486. uniforms.push("contrast");
  70487. }
  70488. if (defines.COLORGRADING) {
  70489. uniforms.push("colorTransformSettings");
  70490. }
  70491. if (defines.VIGNETTE) {
  70492. uniforms.push("vInverseScreenSize");
  70493. uniforms.push("vignetteSettings1");
  70494. uniforms.push("vignetteSettings2");
  70495. }
  70496. if (defines.COLORCURVES) {
  70497. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  70498. }
  70499. };
  70500. /**
  70501. * Prepare the list of samplers associated with the Image Processing effects.
  70502. * @param uniformsList The list of uniforms used in the effect
  70503. * @param defines the list of defines currently in use
  70504. */
  70505. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  70506. if (defines.COLORGRADING) {
  70507. samplersList.push("txColorTransform");
  70508. }
  70509. };
  70510. /**
  70511. * Prepare the list of defines associated to the shader.
  70512. * @param defines the list of defines to complete
  70513. */
  70514. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  70515. defines.VIGNETTE = this.vignetteEnabled;
  70516. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  70517. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  70518. defines.TONEMAPPING = this.toneMappingEnabled;
  70519. defines.CONTRAST = (this.contrast !== 1.0);
  70520. defines.EXPOSURE = (this.exposure !== 1.0);
  70521. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  70522. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  70523. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  70524. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  70525. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  70526. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  70527. };
  70528. /**
  70529. * Returns true if all the image processing information are ready.
  70530. */
  70531. ImageProcessingConfiguration.prototype.isReady = function () {
  70532. // Color Grading texure can not be none blocking.
  70533. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  70534. };
  70535. /**
  70536. * Binds the image processing to the shader.
  70537. * @param effect The effect to bind to
  70538. */
  70539. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  70540. if (aspectRatio === void 0) { aspectRatio = 1; }
  70541. // Color Curves
  70542. if (this._colorCurvesEnabled) {
  70543. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  70544. }
  70545. // Vignette
  70546. if (this._vignetteEnabled) {
  70547. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  70548. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  70549. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  70550. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  70551. var vignetteScaleX = vignetteScaleY * aspectRatio;
  70552. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  70553. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  70554. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  70555. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  70556. var vignettePower = -2.0 * this.vignetteWeight;
  70557. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  70558. }
  70559. // Exposure
  70560. effect.setFloat("exposureLinear", this.exposure);
  70561. // Contrast
  70562. effect.setFloat("contrast", this.contrast);
  70563. // Color transform settings
  70564. if (this.colorGradingTexture) {
  70565. effect.setTexture("txColorTransform", this.colorGradingTexture);
  70566. var textureSize = this.colorGradingTexture.getSize().height;
  70567. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  70568. 0.5 / textureSize, // textureOffset
  70569. textureSize, // textureSize
  70570. this.colorGradingTexture.level // weight
  70571. );
  70572. }
  70573. };
  70574. /**
  70575. * Clones the current image processing instance.
  70576. * @return The cloned image processing
  70577. */
  70578. ImageProcessingConfiguration.prototype.clone = function () {
  70579. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  70580. };
  70581. /**
  70582. * Serializes the current image processing instance to a json representation.
  70583. * @return a JSON representation
  70584. */
  70585. ImageProcessingConfiguration.prototype.serialize = function () {
  70586. return BABYLON.SerializationHelper.Serialize(this);
  70587. };
  70588. /**
  70589. * Parses the image processing from a json representation.
  70590. * @param source the JSON source to parse
  70591. * @return The parsed image processing
  70592. */
  70593. ImageProcessingConfiguration.Parse = function (source) {
  70594. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  70595. };
  70596. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  70597. /**
  70598. * Used to apply the vignette as a mix with the pixel color.
  70599. */
  70600. get: function () {
  70601. return this._VIGNETTEMODE_MULTIPLY;
  70602. },
  70603. enumerable: true,
  70604. configurable: true
  70605. });
  70606. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  70607. /**
  70608. * Used to apply the vignette as a replacement of the pixel color.
  70609. */
  70610. get: function () {
  70611. return this._VIGNETTEMODE_OPAQUE;
  70612. },
  70613. enumerable: true,
  70614. configurable: true
  70615. });
  70616. // Static constants associated to the image processing.
  70617. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  70618. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  70619. __decorate([
  70620. BABYLON.serializeAsColorCurves()
  70621. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  70622. __decorate([
  70623. BABYLON.serialize()
  70624. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  70625. __decorate([
  70626. BABYLON.serializeAsTexture()
  70627. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  70628. __decorate([
  70629. BABYLON.serialize()
  70630. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  70631. __decorate([
  70632. BABYLON.serialize()
  70633. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  70634. __decorate([
  70635. BABYLON.serialize()
  70636. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  70637. __decorate([
  70638. BABYLON.serialize()
  70639. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  70640. __decorate([
  70641. BABYLON.serialize()
  70642. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  70643. __decorate([
  70644. BABYLON.serialize()
  70645. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  70646. __decorate([
  70647. BABYLON.serialize()
  70648. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  70649. __decorate([
  70650. BABYLON.serialize()
  70651. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  70652. __decorate([
  70653. BABYLON.serialize()
  70654. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  70655. __decorate([
  70656. BABYLON.serialize()
  70657. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  70658. __decorate([
  70659. BABYLON.serializeAsColor4()
  70660. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  70661. __decorate([
  70662. BABYLON.serialize()
  70663. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  70664. __decorate([
  70665. BABYLON.serialize()
  70666. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  70667. __decorate([
  70668. BABYLON.serialize()
  70669. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  70670. __decorate([
  70671. BABYLON.serialize()
  70672. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  70673. return ImageProcessingConfiguration;
  70674. }());
  70675. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  70676. })(BABYLON || (BABYLON = {}));
  70677. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  70678. var BABYLON;
  70679. (function (BABYLON) {
  70680. var serializedGeometries = [];
  70681. var serializeGeometry = function (geometry, serializationGeometries) {
  70682. if (serializedGeometries[geometry.id]) {
  70683. return;
  70684. }
  70685. if (geometry.doNotSerialize) {
  70686. return;
  70687. }
  70688. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  70689. serializationGeometries.boxes.push(geometry.serialize());
  70690. }
  70691. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  70692. serializationGeometries.spheres.push(geometry.serialize());
  70693. }
  70694. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  70695. serializationGeometries.cylinders.push(geometry.serialize());
  70696. }
  70697. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  70698. serializationGeometries.toruses.push(geometry.serialize());
  70699. }
  70700. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  70701. serializationGeometries.grounds.push(geometry.serialize());
  70702. }
  70703. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  70704. serializationGeometries.planes.push(geometry.serialize());
  70705. }
  70706. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  70707. serializationGeometries.torusKnots.push(geometry.serialize());
  70708. }
  70709. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  70710. throw new Error("Unknown primitive type");
  70711. }
  70712. else {
  70713. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  70714. }
  70715. serializedGeometries[geometry.id] = true;
  70716. };
  70717. var serializeMesh = function (mesh, serializationScene) {
  70718. var serializationObject = {};
  70719. // Geometry
  70720. var geometry = mesh._geometry;
  70721. if (geometry) {
  70722. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  70723. // Geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  70724. serializeGeometry(geometry, serializationScene.geometries);
  70725. }
  70726. }
  70727. // Custom
  70728. if (mesh.serialize) {
  70729. mesh.serialize(serializationObject);
  70730. }
  70731. return serializationObject;
  70732. };
  70733. var finalizeSingleMesh = function (mesh, serializationObject) {
  70734. //only works if the mesh is already loaded
  70735. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  70736. //serialize material
  70737. if (mesh.material) {
  70738. if (mesh.material instanceof BABYLON.StandardMaterial) {
  70739. serializationObject.materials = serializationObject.materials || [];
  70740. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  70741. serializationObject.materials.push(mesh.material.serialize());
  70742. }
  70743. }
  70744. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  70745. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  70746. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  70747. serializationObject.multiMaterials.push(mesh.material.serialize());
  70748. }
  70749. }
  70750. }
  70751. //serialize geometry
  70752. var geometry = mesh._geometry;
  70753. if (geometry) {
  70754. if (!serializationObject.geometries) {
  70755. serializationObject.geometries = {};
  70756. serializationObject.geometries.boxes = [];
  70757. serializationObject.geometries.spheres = [];
  70758. serializationObject.geometries.cylinders = [];
  70759. serializationObject.geometries.toruses = [];
  70760. serializationObject.geometries.grounds = [];
  70761. serializationObject.geometries.planes = [];
  70762. serializationObject.geometries.torusKnots = [];
  70763. serializationObject.geometries.vertexData = [];
  70764. }
  70765. serializeGeometry(geometry, serializationObject.geometries);
  70766. }
  70767. // Skeletons
  70768. if (mesh.skeleton) {
  70769. serializationObject.skeletons = serializationObject.skeletons || [];
  70770. serializationObject.skeletons.push(mesh.skeleton.serialize());
  70771. }
  70772. //serialize the actual mesh
  70773. serializationObject.meshes = serializationObject.meshes || [];
  70774. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  70775. }
  70776. };
  70777. var SceneSerializer = (function () {
  70778. function SceneSerializer() {
  70779. }
  70780. SceneSerializer.ClearCache = function () {
  70781. serializedGeometries = [];
  70782. };
  70783. SceneSerializer.Serialize = function (scene) {
  70784. var serializationObject = {};
  70785. SceneSerializer.ClearCache();
  70786. // Scene
  70787. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  70788. serializationObject.autoClear = scene.autoClear;
  70789. serializationObject.clearColor = scene.clearColor.asArray();
  70790. serializationObject.ambientColor = scene.ambientColor.asArray();
  70791. serializationObject.gravity = scene.gravity.asArray();
  70792. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  70793. serializationObject.workerCollisions = scene.workerCollisions;
  70794. // Fog
  70795. if (scene.fogMode && scene.fogMode !== 0) {
  70796. serializationObject.fogMode = scene.fogMode;
  70797. serializationObject.fogColor = scene.fogColor.asArray();
  70798. serializationObject.fogStart = scene.fogStart;
  70799. serializationObject.fogEnd = scene.fogEnd;
  70800. serializationObject.fogDensity = scene.fogDensity;
  70801. }
  70802. //Physics
  70803. if (scene.isPhysicsEnabled()) {
  70804. serializationObject.physicsEnabled = true;
  70805. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  70806. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  70807. }
  70808. // Metadata
  70809. if (scene.metadata) {
  70810. serializationObject.metadata = scene.metadata;
  70811. }
  70812. // Morph targets
  70813. serializationObject.morphTargetManagers = [];
  70814. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  70815. var abstractMesh = _a[_i];
  70816. var manager = abstractMesh.morphTargetManager;
  70817. if (manager) {
  70818. serializationObject.morphTargetManagers.push(manager.serialize());
  70819. }
  70820. }
  70821. // Lights
  70822. serializationObject.lights = [];
  70823. var index;
  70824. var light;
  70825. for (index = 0; index < scene.lights.length; index++) {
  70826. light = scene.lights[index];
  70827. if (!light.doNotSerialize) {
  70828. serializationObject.lights.push(light.serialize());
  70829. }
  70830. }
  70831. // Cameras
  70832. serializationObject.cameras = [];
  70833. for (index = 0; index < scene.cameras.length; index++) {
  70834. var camera = scene.cameras[index];
  70835. if (!camera.doNotSerialize) {
  70836. serializationObject.cameras.push(camera.serialize());
  70837. }
  70838. }
  70839. if (scene.activeCamera) {
  70840. serializationObject.activeCameraID = scene.activeCamera.id;
  70841. }
  70842. // Animations
  70843. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  70844. // Materials
  70845. serializationObject.materials = [];
  70846. serializationObject.multiMaterials = [];
  70847. var material;
  70848. for (index = 0; index < scene.materials.length; index++) {
  70849. material = scene.materials[index];
  70850. if (!material.doNotSerialize) {
  70851. serializationObject.materials.push(material.serialize());
  70852. }
  70853. }
  70854. // MultiMaterials
  70855. serializationObject.multiMaterials = [];
  70856. for (index = 0; index < scene.multiMaterials.length; index++) {
  70857. var multiMaterial = scene.multiMaterials[index];
  70858. serializationObject.multiMaterials.push(multiMaterial.serialize());
  70859. }
  70860. // Skeletons
  70861. serializationObject.skeletons = [];
  70862. for (index = 0; index < scene.skeletons.length; index++) {
  70863. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  70864. }
  70865. // Geometries
  70866. serializationObject.geometries = {};
  70867. serializationObject.geometries.boxes = [];
  70868. serializationObject.geometries.spheres = [];
  70869. serializationObject.geometries.cylinders = [];
  70870. serializationObject.geometries.toruses = [];
  70871. serializationObject.geometries.grounds = [];
  70872. serializationObject.geometries.planes = [];
  70873. serializationObject.geometries.torusKnots = [];
  70874. serializationObject.geometries.vertexData = [];
  70875. serializedGeometries = [];
  70876. var geometries = scene.getGeometries();
  70877. for (index = 0; index < geometries.length; index++) {
  70878. var geometry = geometries[index];
  70879. if (geometry.isReady()) {
  70880. serializeGeometry(geometry, serializationObject.geometries);
  70881. }
  70882. }
  70883. // Meshes
  70884. serializationObject.meshes = [];
  70885. for (index = 0; index < scene.meshes.length; index++) {
  70886. var abstractMesh = scene.meshes[index];
  70887. if (abstractMesh instanceof BABYLON.Mesh) {
  70888. var mesh = abstractMesh;
  70889. if (!mesh.doNotSerialize) {
  70890. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  70891. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  70892. }
  70893. }
  70894. }
  70895. }
  70896. // Particles Systems
  70897. serializationObject.particleSystems = [];
  70898. for (index = 0; index < scene.particleSystems.length; index++) {
  70899. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  70900. }
  70901. // Lens flares
  70902. serializationObject.lensFlareSystems = [];
  70903. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  70904. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  70905. }
  70906. // Shadows
  70907. serializationObject.shadowGenerators = [];
  70908. for (index = 0; index < scene.lights.length; index++) {
  70909. light = scene.lights[index];
  70910. var shadowGenerator = light.getShadowGenerator();
  70911. if (shadowGenerator) {
  70912. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  70913. }
  70914. }
  70915. // Action Manager
  70916. if (scene.actionManager) {
  70917. serializationObject.actions = scene.actionManager.serialize("scene");
  70918. }
  70919. // Audio
  70920. serializationObject.sounds = [];
  70921. for (index = 0; index < scene.soundTracks.length; index++) {
  70922. var soundtrack = scene.soundTracks[index];
  70923. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70924. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70925. }
  70926. }
  70927. return serializationObject;
  70928. };
  70929. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  70930. if (withParents === void 0) { withParents = false; }
  70931. if (withChildren === void 0) { withChildren = false; }
  70932. var serializationObject = {};
  70933. SceneSerializer.ClearCache();
  70934. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  70935. if (withParents || withChildren) {
  70936. //deliberate for loop! not for each, appended should be processed as well.
  70937. for (var i = 0; i < toSerialize.length; ++i) {
  70938. if (withChildren) {
  70939. toSerialize[i].getDescendants().forEach(function (node) {
  70940. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  70941. toSerialize.push(node);
  70942. }
  70943. });
  70944. }
  70945. //make sure the array doesn't contain the object already
  70946. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  70947. toSerialize.push(toSerialize[i].parent);
  70948. }
  70949. }
  70950. }
  70951. toSerialize.forEach(function (mesh) {
  70952. finalizeSingleMesh(mesh, serializationObject);
  70953. });
  70954. return serializationObject;
  70955. };
  70956. return SceneSerializer;
  70957. }());
  70958. BABYLON.SceneSerializer = SceneSerializer;
  70959. })(BABYLON || (BABYLON = {}));
  70960. //# sourceMappingURL=babylon.sceneSerializer.js.map
  70961. var BABYLON;
  70962. (function (BABYLON) {
  70963. var ReflectionProbe = (function () {
  70964. function ReflectionProbe(name, size, scene, generateMipMaps) {
  70965. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70966. var _this = this;
  70967. this.name = name;
  70968. this._viewMatrix = BABYLON.Matrix.Identity();
  70969. this._target = BABYLON.Vector3.Zero();
  70970. this._add = BABYLON.Vector3.Zero();
  70971. this.invertYAxis = false;
  70972. this.position = BABYLON.Vector3.Zero();
  70973. this._scene = scene;
  70974. this._scene.reflectionProbes.push(this);
  70975. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  70976. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  70977. switch (faceIndex) {
  70978. case 0:
  70979. _this._add.copyFromFloats(1, 0, 0);
  70980. break;
  70981. case 1:
  70982. _this._add.copyFromFloats(-1, 0, 0);
  70983. break;
  70984. case 2:
  70985. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  70986. break;
  70987. case 3:
  70988. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  70989. break;
  70990. case 4:
  70991. _this._add.copyFromFloats(0, 0, 1);
  70992. break;
  70993. case 5:
  70994. _this._add.copyFromFloats(0, 0, -1);
  70995. break;
  70996. }
  70997. if (_this._attachedMesh) {
  70998. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  70999. }
  71000. _this.position.addToRef(_this._add, _this._target);
  71001. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  71002. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  71003. });
  71004. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  71005. scene.updateTransformMatrix(true);
  71006. });
  71007. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  71008. }
  71009. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  71010. get: function () {
  71011. return this._renderTargetTexture.samples;
  71012. },
  71013. set: function (value) {
  71014. this._renderTargetTexture.samples = value;
  71015. },
  71016. enumerable: true,
  71017. configurable: true
  71018. });
  71019. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  71020. get: function () {
  71021. return this._renderTargetTexture.refreshRate;
  71022. },
  71023. set: function (value) {
  71024. this._renderTargetTexture.refreshRate = value;
  71025. },
  71026. enumerable: true,
  71027. configurable: true
  71028. });
  71029. ReflectionProbe.prototype.getScene = function () {
  71030. return this._scene;
  71031. };
  71032. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  71033. get: function () {
  71034. return this._renderTargetTexture;
  71035. },
  71036. enumerable: true,
  71037. configurable: true
  71038. });
  71039. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  71040. get: function () {
  71041. return this._renderTargetTexture.renderList;
  71042. },
  71043. enumerable: true,
  71044. configurable: true
  71045. });
  71046. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  71047. this._attachedMesh = mesh;
  71048. };
  71049. /**
  71050. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  71051. *
  71052. * @param renderingGroupId The rendering group id corresponding to its index
  71053. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  71054. */
  71055. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  71056. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  71057. };
  71058. ReflectionProbe.prototype.dispose = function () {
  71059. var index = this._scene.reflectionProbes.indexOf(this);
  71060. if (index !== -1) {
  71061. // Remove from the scene if found
  71062. this._scene.reflectionProbes.splice(index, 1);
  71063. }
  71064. if (this._renderTargetTexture) {
  71065. this._renderTargetTexture.dispose();
  71066. this._renderTargetTexture = null;
  71067. }
  71068. };
  71069. return ReflectionProbe;
  71070. }());
  71071. BABYLON.ReflectionProbe = ReflectionProbe;
  71072. })(BABYLON || (BABYLON = {}));
  71073. //# sourceMappingURL=babylon.reflectionProbe.js.map
  71074. var BABYLON;
  71075. (function (BABYLON) {
  71076. var Layer = (function () {
  71077. function Layer(name, imgUrl, scene, isBackground, color) {
  71078. this.name = name;
  71079. this.scale = new BABYLON.Vector2(1, 1);
  71080. this.offset = new BABYLON.Vector2(0, 0);
  71081. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  71082. this.layerMask = 0x0FFFFFFF;
  71083. this._vertexBuffers = {};
  71084. // Events
  71085. /**
  71086. * An event triggered when the layer is disposed.
  71087. * @type {BABYLON.Observable}
  71088. */
  71089. this.onDisposeObservable = new BABYLON.Observable();
  71090. /**
  71091. * An event triggered before rendering the scene
  71092. * @type {BABYLON.Observable}
  71093. */
  71094. this.onBeforeRenderObservable = new BABYLON.Observable();
  71095. /**
  71096. * An event triggered after rendering the scene
  71097. * @type {BABYLON.Observable}
  71098. */
  71099. this.onAfterRenderObservable = new BABYLON.Observable();
  71100. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  71101. this.isBackground = isBackground === undefined ? true : isBackground;
  71102. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  71103. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71104. this._scene.layers.push(this);
  71105. var engine = this._scene.getEngine();
  71106. // VBO
  71107. var vertices = [];
  71108. vertices.push(1, 1);
  71109. vertices.push(-1, 1);
  71110. vertices.push(-1, -1);
  71111. vertices.push(1, -1);
  71112. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71113. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71114. this._createIndexBuffer();
  71115. // Effects
  71116. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  71117. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  71118. }
  71119. Object.defineProperty(Layer.prototype, "onDispose", {
  71120. set: function (callback) {
  71121. if (this._onDisposeObserver) {
  71122. this.onDisposeObservable.remove(this._onDisposeObserver);
  71123. }
  71124. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  71125. },
  71126. enumerable: true,
  71127. configurable: true
  71128. });
  71129. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  71130. set: function (callback) {
  71131. if (this._onBeforeRenderObserver) {
  71132. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71133. }
  71134. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71135. },
  71136. enumerable: true,
  71137. configurable: true
  71138. });
  71139. Object.defineProperty(Layer.prototype, "onAfterRender", {
  71140. set: function (callback) {
  71141. if (this._onAfterRenderObserver) {
  71142. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71143. }
  71144. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71145. },
  71146. enumerable: true,
  71147. configurable: true
  71148. });
  71149. Layer.prototype._createIndexBuffer = function () {
  71150. var engine = this._scene.getEngine();
  71151. // Indices
  71152. var indices = [];
  71153. indices.push(0);
  71154. indices.push(1);
  71155. indices.push(2);
  71156. indices.push(0);
  71157. indices.push(2);
  71158. indices.push(3);
  71159. this._indexBuffer = engine.createIndexBuffer(indices);
  71160. };
  71161. Layer.prototype._rebuild = function () {
  71162. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  71163. this._createIndexBuffer();
  71164. };
  71165. Layer.prototype.render = function () {
  71166. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  71167. // Check
  71168. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  71169. return;
  71170. var engine = this._scene.getEngine();
  71171. this.onBeforeRenderObservable.notifyObservers(this);
  71172. // Render
  71173. engine.enableEffect(currentEffect);
  71174. engine.setState(false);
  71175. // Texture
  71176. currentEffect.setTexture("textureSampler", this.texture);
  71177. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  71178. // Color
  71179. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  71180. // Scale / offset
  71181. currentEffect.setVector2("offset", this.offset);
  71182. currentEffect.setVector2("scale", this.scale);
  71183. // VBOs
  71184. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  71185. // Draw order
  71186. if (!this.alphaTest) {
  71187. engine.setAlphaMode(this.alphaBlendingMode);
  71188. engine.draw(true, 0, 6);
  71189. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71190. }
  71191. else {
  71192. engine.draw(true, 0, 6);
  71193. }
  71194. this.onAfterRenderObservable.notifyObservers(this);
  71195. };
  71196. Layer.prototype.dispose = function () {
  71197. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71198. if (vertexBuffer) {
  71199. vertexBuffer.dispose();
  71200. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71201. }
  71202. if (this._indexBuffer) {
  71203. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71204. this._indexBuffer = null;
  71205. }
  71206. if (this.texture) {
  71207. this.texture.dispose();
  71208. this.texture = null;
  71209. }
  71210. // Remove from scene
  71211. var index = this._scene.layers.indexOf(this);
  71212. this._scene.layers.splice(index, 1);
  71213. // Callback
  71214. this.onDisposeObservable.notifyObservers(this);
  71215. this.onDisposeObservable.clear();
  71216. this.onAfterRenderObservable.clear();
  71217. this.onBeforeRenderObservable.clear();
  71218. };
  71219. return Layer;
  71220. }());
  71221. BABYLON.Layer = Layer;
  71222. })(BABYLON || (BABYLON = {}));
  71223. //# sourceMappingURL=babylon.layer.js.map
  71224. var BABYLON;
  71225. (function (BABYLON) {
  71226. var TextureTools = (function () {
  71227. function TextureTools() {
  71228. }
  71229. /**
  71230. * Uses the GPU to create a copy texture rescaled at a given size
  71231. * @param texture Texture to copy from
  71232. * @param width Desired width
  71233. * @param height Desired height
  71234. * @return Generated texture
  71235. */
  71236. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  71237. if (useBilinearMode === void 0) { useBilinearMode = true; }
  71238. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  71239. var scene = texture.getScene();
  71240. var engine = scene.getEngine();
  71241. rtt.wrapU = texture.wrapU;
  71242. rtt.wrapV = texture.wrapV;
  71243. rtt.uOffset = texture.uOffset;
  71244. rtt.vOffset = texture.vOffset;
  71245. rtt.uScale = texture.uScale;
  71246. rtt.vScale = texture.vScale;
  71247. rtt.uAng = texture.uAng;
  71248. rtt.vAng = texture.vAng;
  71249. rtt.wAng = texture.wAng;
  71250. rtt.coordinatesIndex = texture.coordinatesIndex;
  71251. rtt.level = texture.level;
  71252. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  71253. rtt._texture.isReady = false;
  71254. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71255. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71256. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71257. passPostProcess.getEffect().executeWhenCompiled(function () {
  71258. passPostProcess.onApply = function (effect) {
  71259. effect.setTexture("textureSampler", texture);
  71260. };
  71261. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  71262. engine.unBindFramebuffer(rtt.getInternalTexture());
  71263. rtt.disposeFramebufferObjects();
  71264. passPostProcess.dispose();
  71265. rtt._texture.isReady = true;
  71266. });
  71267. return rtt;
  71268. };
  71269. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  71270. if (!scene._environmentBRDFTexture) {
  71271. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71272. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71273. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71274. scene._environmentBRDFTexture = texture;
  71275. }
  71276. return scene._environmentBRDFTexture;
  71277. };
  71278. 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=";
  71279. return TextureTools;
  71280. }());
  71281. BABYLON.TextureTools = TextureTools;
  71282. })(BABYLON || (BABYLON = {}));
  71283. //# sourceMappingURL=babylon.textureTools.js.map
  71284. var BABYLON;
  71285. (function (BABYLON) {
  71286. var FramingBehavior = (function () {
  71287. function FramingBehavior() {
  71288. this._mode = FramingBehavior.FitFrustumSidesMode;
  71289. this._radiusScale = 1.0;
  71290. this._positionScale = 0.5;
  71291. this._defaultElevation = 0.3;
  71292. this._elevationReturnTime = 1500;
  71293. this._elevationReturnWaitTime = 1000;
  71294. this._zoomStopsAnimation = false;
  71295. this._framingTime = 1500;
  71296. this._isPointerDown = false;
  71297. this._lastFrameTime = null;
  71298. this._lastInteractionTime = -Infinity;
  71299. // Framing control
  71300. this._animatables = new Array();
  71301. this._betaIsAnimating = false;
  71302. this._lastFrameRadius = 0;
  71303. }
  71304. Object.defineProperty(FramingBehavior.prototype, "name", {
  71305. get: function () {
  71306. return "Framing";
  71307. },
  71308. enumerable: true,
  71309. configurable: true
  71310. });
  71311. Object.defineProperty(FramingBehavior.prototype, "mode", {
  71312. /**
  71313. * Gets current mode used by the behavior.
  71314. */
  71315. get: function () {
  71316. return this._mode;
  71317. },
  71318. /**
  71319. * Sets the current mode used by the behavior
  71320. */
  71321. set: function (mode) {
  71322. this._mode = mode;
  71323. },
  71324. enumerable: true,
  71325. configurable: true
  71326. });
  71327. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  71328. /**
  71329. * Gets the scale applied to the radius
  71330. */
  71331. get: function () {
  71332. return this._radiusScale;
  71333. },
  71334. /**
  71335. * Sets the scale applied to the radius (1 by default)
  71336. */
  71337. set: function (radius) {
  71338. this._radiusScale = radius;
  71339. },
  71340. enumerable: true,
  71341. configurable: true
  71342. });
  71343. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  71344. /**
  71345. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  71346. */
  71347. get: function () {
  71348. return this._positionScale;
  71349. },
  71350. /**
  71351. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  71352. */
  71353. set: function (scale) {
  71354. this._positionScale = scale;
  71355. },
  71356. enumerable: true,
  71357. configurable: true
  71358. });
  71359. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  71360. /**
  71361. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  71362. * behaviour is triggered, in radians.
  71363. */
  71364. get: function () {
  71365. return this._defaultElevation;
  71366. },
  71367. /**
  71368. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  71369. * behaviour is triggered, in radians.
  71370. */
  71371. set: function (elevation) {
  71372. this._defaultElevation = elevation;
  71373. },
  71374. enumerable: true,
  71375. configurable: true
  71376. });
  71377. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  71378. /**
  71379. * Gets the time (in milliseconds) taken to return to the default beta position.
  71380. * Negative value indicates camera should not return to default.
  71381. */
  71382. get: function () {
  71383. return this._elevationReturnTime;
  71384. },
  71385. /**
  71386. * Sets the time (in milliseconds) taken to return to the default beta position.
  71387. * Negative value indicates camera should not return to default.
  71388. */
  71389. set: function (speed) {
  71390. this._elevationReturnTime = speed;
  71391. },
  71392. enumerable: true,
  71393. configurable: true
  71394. });
  71395. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  71396. /**
  71397. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  71398. */
  71399. get: function () {
  71400. return this._elevationReturnWaitTime;
  71401. },
  71402. /**
  71403. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  71404. */
  71405. set: function (time) {
  71406. this._elevationReturnWaitTime = time;
  71407. },
  71408. enumerable: true,
  71409. configurable: true
  71410. });
  71411. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  71412. /**
  71413. * Gets the flag that indicates if user zooming should stop animation.
  71414. */
  71415. get: function () {
  71416. return this._zoomStopsAnimation;
  71417. },
  71418. /**
  71419. * Sets the flag that indicates if user zooming should stop animation.
  71420. */
  71421. set: function (flag) {
  71422. this._zoomStopsAnimation = flag;
  71423. },
  71424. enumerable: true,
  71425. configurable: true
  71426. });
  71427. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  71428. /**
  71429. * Gets the transition time when framing the mesh, in milliseconds
  71430. */
  71431. get: function () {
  71432. return this._framingTime;
  71433. },
  71434. /**
  71435. * Sets the transition time when framing the mesh, in milliseconds
  71436. */
  71437. set: function (time) {
  71438. this._framingTime = time;
  71439. },
  71440. enumerable: true,
  71441. configurable: true
  71442. });
  71443. FramingBehavior.prototype.attach = function (camera) {
  71444. var _this = this;
  71445. this._attachedCamera = camera;
  71446. var scene = this._attachedCamera.getScene();
  71447. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  71448. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  71449. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71450. _this._isPointerDown = true;
  71451. return;
  71452. }
  71453. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  71454. _this._isPointerDown = false;
  71455. }
  71456. });
  71457. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  71458. if (mesh) {
  71459. _this.zoomOnMesh(mesh);
  71460. }
  71461. });
  71462. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71463. // Stop the animation if there is user interaction and the animation should stop for this interaction
  71464. _this._applyUserInteraction();
  71465. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  71466. // back to the default position after a given timeout
  71467. _this._maintainCameraAboveGround();
  71468. });
  71469. };
  71470. FramingBehavior.prototype.detach = function () {
  71471. var scene = this._attachedCamera.getScene();
  71472. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  71473. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71474. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71475. this._attachedCamera = null;
  71476. };
  71477. /**
  71478. * Targets the given mesh and updates zoom level accordingly.
  71479. * @param mesh The mesh to target.
  71480. * @param radius Optional. If a cached radius position already exists, overrides default.
  71481. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  71482. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  71483. * @param onAnimationEnd Callback triggered at the end of the framing animation
  71484. */
  71485. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  71486. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  71487. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  71488. mesh.computeWorldMatrix(true);
  71489. var boundingBox = mesh.getBoundingInfo().boundingBox;
  71490. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  71491. };
  71492. /**
  71493. * Targets the given mesh and updates zoom level accordingly.
  71494. * @param mesh The mesh to target.
  71495. * @param radius Optional. If a cached radius position already exists, overrides default.
  71496. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  71497. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  71498. * @param onAnimationEnd Callback triggered at the end of the framing animation
  71499. */
  71500. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  71501. var _this = this;
  71502. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  71503. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  71504. var zoomTarget;
  71505. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  71506. var bottom = minimumWorld.y;
  71507. var top = maximumWorld.y;
  71508. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  71509. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  71510. if (focusOnOriginXZ) {
  71511. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  71512. }
  71513. else {
  71514. var centerWorld = minimumWorld.add(radiusWorld);
  71515. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  71516. }
  71517. if (!this._vectorTransition) {
  71518. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  71519. }
  71520. this._betaIsAnimating = true;
  71521. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  71522. // sets the radius and lower radius bounds
  71523. // Small delta ensures camera is not always at lower zoom limit.
  71524. var delta = 0.1;
  71525. var radius = 0;
  71526. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  71527. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  71528. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  71529. radius = position;
  71530. }
  71531. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  71532. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  71533. if (this._attachedCamera.lowerRadiusLimit === null) {
  71534. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  71535. }
  71536. }
  71537. // Set sensibilities
  71538. var extend = maximumWorld.subtract(minimumWorld).length();
  71539. this._attachedCamera.panningSensibility = 5000 / extend;
  71540. this._attachedCamera.wheelPrecision = 100 / radius;
  71541. // transition to new radius
  71542. if (!this._radiusTransition) {
  71543. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  71544. }
  71545. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  71546. if (onAnimationEnd) {
  71547. onAnimationEnd();
  71548. }
  71549. _this._attachedCamera.storeState();
  71550. }));
  71551. };
  71552. /**
  71553. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  71554. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  71555. * frustum width.
  71556. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  71557. * to fully enclose the mesh in the viewing frustum.
  71558. */
  71559. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  71560. var size = maximumWorld.subtract(minimumWorld);
  71561. var boxVectorGlobalDiagonal = size.length();
  71562. var frustumSlope = this._getFrustumSlope();
  71563. // Formula for setting distance
  71564. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  71565. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  71566. // Horizon distance
  71567. var radius = radiusWithoutFraming * this._radiusScale;
  71568. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  71569. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  71570. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  71571. var camera = this._attachedCamera;
  71572. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  71573. // Don't exceed the requested limit
  71574. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  71575. }
  71576. // Don't exceed the upper radius limit
  71577. if (camera.upperRadiusLimit) {
  71578. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  71579. }
  71580. return distance;
  71581. };
  71582. /**
  71583. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  71584. * is automatically returned to its default position (expected to be above ground plane).
  71585. */
  71586. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  71587. var _this = this;
  71588. if (this._elevationReturnTime < 0) {
  71589. return;
  71590. }
  71591. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  71592. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  71593. var limitBeta = Math.PI * 0.5;
  71594. // Bring the camera back up if below the ground plane
  71595. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  71596. this._betaIsAnimating = true;
  71597. //Transition to new position
  71598. this.stopAllAnimations();
  71599. if (!this._betaTransition) {
  71600. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  71601. }
  71602. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  71603. _this._clearAnimationLocks();
  71604. _this.stopAllAnimations();
  71605. }));
  71606. }
  71607. };
  71608. /**
  71609. * Returns the frustum slope based on the canvas ratio and camera FOV
  71610. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  71611. */
  71612. FramingBehavior.prototype._getFrustumSlope = function () {
  71613. // Calculate the viewport ratio
  71614. // Aspect Ratio is Height/Width.
  71615. var camera = this._attachedCamera;
  71616. var engine = camera.getScene().getEngine();
  71617. var aspectRatio = engine.getAspectRatio(camera);
  71618. // Camera FOV is the vertical field of view (top-bottom) in radians.
  71619. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  71620. var frustumSlopeY = Math.tan(camera.fov / 2);
  71621. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  71622. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  71623. // along the forward vector.
  71624. var frustumSlopeX = frustumSlopeY * aspectRatio;
  71625. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  71626. };
  71627. /**
  71628. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  71629. */
  71630. FramingBehavior.prototype._clearAnimationLocks = function () {
  71631. this._betaIsAnimating = false;
  71632. };
  71633. /**
  71634. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  71635. */
  71636. FramingBehavior.prototype._applyUserInteraction = function () {
  71637. if (this.isUserIsMoving) {
  71638. this._lastInteractionTime = BABYLON.Tools.Now;
  71639. this.stopAllAnimations();
  71640. this._clearAnimationLocks();
  71641. }
  71642. };
  71643. /**
  71644. * Stops and removes all animations that have been applied to the camera
  71645. */
  71646. FramingBehavior.prototype.stopAllAnimations = function () {
  71647. this._attachedCamera.animations = [];
  71648. while (this._animatables.length) {
  71649. if (this._animatables[0]) {
  71650. this._animatables[0].onAnimationEnd = null;
  71651. this._animatables[0].stop();
  71652. }
  71653. this._animatables.shift();
  71654. }
  71655. };
  71656. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  71657. /**
  71658. * Gets a value indicating if the user is moving the camera
  71659. */
  71660. get: function () {
  71661. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  71662. this._attachedCamera.inertialBetaOffset !== 0 ||
  71663. this._attachedCamera.inertialRadiusOffset !== 0 ||
  71664. this._attachedCamera.inertialPanningX !== 0 ||
  71665. this._attachedCamera.inertialPanningY !== 0 ||
  71666. this._isPointerDown;
  71667. },
  71668. enumerable: true,
  71669. configurable: true
  71670. });
  71671. /**
  71672. * The easing function used by animations
  71673. */
  71674. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  71675. /**
  71676. * The easing mode used by animations
  71677. */
  71678. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  71679. // Statics
  71680. /**
  71681. * The camera can move all the way towards the mesh.
  71682. */
  71683. FramingBehavior.IgnoreBoundsSizeMode = 0;
  71684. /**
  71685. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  71686. */
  71687. FramingBehavior.FitFrustumSidesMode = 1;
  71688. return FramingBehavior;
  71689. }());
  71690. BABYLON.FramingBehavior = FramingBehavior;
  71691. })(BABYLON || (BABYLON = {}));
  71692. //# sourceMappingURL=babylon.framingBehavior.js.map
  71693. var BABYLON;
  71694. (function (BABYLON) {
  71695. /**
  71696. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  71697. */
  71698. var BouncingBehavior = (function () {
  71699. function BouncingBehavior() {
  71700. /**
  71701. * The duration of the animation, in milliseconds
  71702. */
  71703. this.transitionDuration = 450;
  71704. /**
  71705. * Length of the distance animated by the transition when lower radius is reached
  71706. */
  71707. this.lowerRadiusTransitionRange = 2;
  71708. /**
  71709. * Length of the distance animated by the transition when upper radius is reached
  71710. */
  71711. this.upperRadiusTransitionRange = -2;
  71712. this._autoTransitionRange = false;
  71713. // Animations
  71714. this._radiusIsAnimating = false;
  71715. this._radiusBounceTransition = null;
  71716. this._animatables = new Array();
  71717. }
  71718. Object.defineProperty(BouncingBehavior.prototype, "name", {
  71719. get: function () {
  71720. return "Bouncing";
  71721. },
  71722. enumerable: true,
  71723. configurable: true
  71724. });
  71725. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  71726. /**
  71727. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  71728. */
  71729. get: function () {
  71730. return this._autoTransitionRange;
  71731. },
  71732. /**
  71733. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  71734. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  71735. */
  71736. set: function (value) {
  71737. var _this = this;
  71738. if (this._autoTransitionRange === value) {
  71739. return;
  71740. }
  71741. this._autoTransitionRange = value;
  71742. var camera = this._attachedCamera;
  71743. if (value) {
  71744. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  71745. if (!mesh) {
  71746. return;
  71747. }
  71748. mesh.computeWorldMatrix(true);
  71749. var diagonal = mesh.getBoundingInfo().diagonalLength;
  71750. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  71751. _this.upperRadiusTransitionRange = diagonal * 0.05;
  71752. });
  71753. }
  71754. else if (this._onMeshTargetChangedObserver) {
  71755. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71756. }
  71757. },
  71758. enumerable: true,
  71759. configurable: true
  71760. });
  71761. BouncingBehavior.prototype.attach = function (camera) {
  71762. var _this = this;
  71763. this._attachedCamera = camera;
  71764. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71765. // Add the bounce animation to the lower radius limit
  71766. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  71767. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  71768. }
  71769. // Add the bounce animation to the upper radius limit
  71770. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  71771. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  71772. }
  71773. });
  71774. };
  71775. BouncingBehavior.prototype.detach = function () {
  71776. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71777. if (this._onMeshTargetChangedObserver) {
  71778. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71779. }
  71780. this._attachedCamera = null;
  71781. };
  71782. /**
  71783. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  71784. * @param radiusLimit The limit to check against.
  71785. * @return Bool to indicate if at limit.
  71786. */
  71787. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  71788. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  71789. return true;
  71790. }
  71791. return false;
  71792. };
  71793. /**
  71794. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  71795. * @param radiusDelta The delta by which to animate to. Can be negative.
  71796. */
  71797. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  71798. var _this = this;
  71799. if (!this._radiusBounceTransition) {
  71800. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  71801. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  71802. }
  71803. // Prevent zoom until bounce has completed
  71804. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  71805. this._attachedCamera.wheelPrecision = Infinity;
  71806. this._attachedCamera.inertialRadiusOffset = 0;
  71807. // Animate to the radius limit
  71808. this.stopAllAnimations();
  71809. this._radiusIsAnimating = true;
  71810. 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(); }));
  71811. };
  71812. /**
  71813. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  71814. */
  71815. BouncingBehavior.prototype._clearAnimationLocks = function () {
  71816. this._radiusIsAnimating = false;
  71817. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  71818. };
  71819. /**
  71820. * Stops and removes all animations that have been applied to the camera
  71821. */
  71822. BouncingBehavior.prototype.stopAllAnimations = function () {
  71823. this._attachedCamera.animations = [];
  71824. while (this._animatables.length) {
  71825. this._animatables[0].onAnimationEnd = null;
  71826. this._animatables[0].stop();
  71827. this._animatables.shift();
  71828. }
  71829. };
  71830. /**
  71831. * The easing function used by animations
  71832. */
  71833. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  71834. /**
  71835. * The easing mode used by animations
  71836. */
  71837. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  71838. return BouncingBehavior;
  71839. }());
  71840. BABYLON.BouncingBehavior = BouncingBehavior;
  71841. })(BABYLON || (BABYLON = {}));
  71842. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  71843. var BABYLON;
  71844. (function (BABYLON) {
  71845. var AutoRotationBehavior = (function () {
  71846. function AutoRotationBehavior() {
  71847. this._zoomStopsAnimation = false;
  71848. this._idleRotationSpeed = 0.05;
  71849. this._idleRotationWaitTime = 2000;
  71850. this._idleRotationSpinupTime = 2000;
  71851. this._isPointerDown = false;
  71852. this._lastFrameTime = null;
  71853. this._lastInteractionTime = -Infinity;
  71854. this._cameraRotationSpeed = 0;
  71855. this._lastFrameRadius = 0;
  71856. }
  71857. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  71858. get: function () {
  71859. return "AutoRotation";
  71860. },
  71861. enumerable: true,
  71862. configurable: true
  71863. });
  71864. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  71865. /**
  71866. * Gets the flag that indicates if user zooming should stop animation.
  71867. */
  71868. get: function () {
  71869. return this._zoomStopsAnimation;
  71870. },
  71871. /**
  71872. * Sets the flag that indicates if user zooming should stop animation.
  71873. */
  71874. set: function (flag) {
  71875. this._zoomStopsAnimation = flag;
  71876. },
  71877. enumerable: true,
  71878. configurable: true
  71879. });
  71880. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  71881. /**
  71882. * Gets the default speed at which the camera rotates around the model.
  71883. */
  71884. get: function () {
  71885. return this._idleRotationSpeed;
  71886. },
  71887. /**
  71888. * Sets the default speed at which the camera rotates around the model.
  71889. */
  71890. set: function (speed) {
  71891. this._idleRotationSpeed = speed;
  71892. },
  71893. enumerable: true,
  71894. configurable: true
  71895. });
  71896. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  71897. /**
  71898. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  71899. */
  71900. get: function () {
  71901. return this._idleRotationWaitTime;
  71902. },
  71903. /**
  71904. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  71905. */
  71906. set: function (time) {
  71907. this._idleRotationWaitTime = time;
  71908. },
  71909. enumerable: true,
  71910. configurable: true
  71911. });
  71912. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  71913. /**
  71914. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  71915. */
  71916. get: function () {
  71917. return this._idleRotationSpinupTime;
  71918. },
  71919. /**
  71920. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  71921. */
  71922. set: function (time) {
  71923. this._idleRotationSpinupTime = time;
  71924. },
  71925. enumerable: true,
  71926. configurable: true
  71927. });
  71928. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  71929. /**
  71930. * Gets a value indicating if the camera is currently rotating because of this behavior
  71931. */
  71932. get: function () {
  71933. return Math.abs(this._cameraRotationSpeed) > 0;
  71934. },
  71935. enumerable: true,
  71936. configurable: true
  71937. });
  71938. AutoRotationBehavior.prototype.attach = function (camera) {
  71939. var _this = this;
  71940. this._attachedCamera = camera;
  71941. var scene = this._attachedCamera.getScene();
  71942. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  71943. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71944. _this._isPointerDown = true;
  71945. return;
  71946. }
  71947. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  71948. _this._isPointerDown = false;
  71949. }
  71950. });
  71951. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71952. var now = BABYLON.Tools.Now;
  71953. var dt = 0;
  71954. if (_this._lastFrameTime != null) {
  71955. dt = now - _this._lastFrameTime;
  71956. }
  71957. _this._lastFrameTime = now;
  71958. // Stop the animation if there is user interaction and the animation should stop for this interaction
  71959. _this._applyUserInteraction();
  71960. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  71961. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  71962. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  71963. // Step camera rotation by rotation speed
  71964. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  71965. });
  71966. };
  71967. AutoRotationBehavior.prototype.detach = function () {
  71968. var scene = this._attachedCamera.getScene();
  71969. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  71970. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71971. this._attachedCamera = null;
  71972. };
  71973. /**
  71974. * Returns true if user is scrolling.
  71975. * @return true if user is scrolling.
  71976. */
  71977. AutoRotationBehavior.prototype._userIsZooming = function () {
  71978. return this._attachedCamera.inertialRadiusOffset !== 0;
  71979. };
  71980. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  71981. var zoomHasHitLimit = false;
  71982. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  71983. zoomHasHitLimit = true;
  71984. }
  71985. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  71986. this._lastFrameRadius = this._attachedCamera.radius;
  71987. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  71988. };
  71989. /**
  71990. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  71991. */
  71992. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  71993. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  71994. this._lastInteractionTime = BABYLON.Tools.Now;
  71995. }
  71996. };
  71997. // Tools
  71998. AutoRotationBehavior.prototype._userIsMoving = function () {
  71999. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  72000. this._attachedCamera.inertialBetaOffset !== 0 ||
  72001. this._attachedCamera.inertialRadiusOffset !== 0 ||
  72002. this._attachedCamera.inertialPanningX !== 0 ||
  72003. this._attachedCamera.inertialPanningY !== 0 ||
  72004. this._isPointerDown;
  72005. };
  72006. return AutoRotationBehavior;
  72007. }());
  72008. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  72009. })(BABYLON || (BABYLON = {}));
  72010. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  72011. BABYLON.Effect.ShadersStore={"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#include<depthPrePass>\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}","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#include<depthPrePass>\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}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\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}","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}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\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}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\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(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\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}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\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}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\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}","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}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\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\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\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#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\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}"};
  72012. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","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","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\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","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","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}","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","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","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","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};","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","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}","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}","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","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};","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}","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}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\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};"};
  72013. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  72014. var BABYLON;
  72015. (function (BABYLON) {
  72016. var GridMaterialDefines = (function (_super) {
  72017. __extends(GridMaterialDefines, _super);
  72018. function GridMaterialDefines() {
  72019. var _this = _super.call(this) || this;
  72020. _this.TRANSPARENT = false;
  72021. _this.FOG = false;
  72022. _this.PREMULTIPLYALPHA = false;
  72023. _this.rebuild();
  72024. return _this;
  72025. }
  72026. return GridMaterialDefines;
  72027. }(BABYLON.MaterialDefines));
  72028. /**
  72029. * The grid materials allows you to wrap any shape with a grid.
  72030. * Colors are customizable.
  72031. */
  72032. var GridMaterial = (function (_super) {
  72033. __extends(GridMaterial, _super);
  72034. /**
  72035. * constructor
  72036. * @param name The name given to the material in order to identify it afterwards.
  72037. * @param scene The scene the material is used in.
  72038. */
  72039. function GridMaterial(name, scene) {
  72040. var _this = _super.call(this, name, scene) || this;
  72041. /**
  72042. * Main color of the grid (e.g. between lines)
  72043. */
  72044. _this.mainColor = BABYLON.Color3.Black();
  72045. /**
  72046. * Color of the grid lines.
  72047. */
  72048. _this.lineColor = BABYLON.Color3.Teal();
  72049. /**
  72050. * The scale of the grid compared to unit.
  72051. */
  72052. _this.gridRatio = 1.0;
  72053. /**
  72054. * The frequency of thicker lines.
  72055. */
  72056. _this.majorUnitFrequency = 10;
  72057. /**
  72058. * The visibility of minor units in the grid.
  72059. */
  72060. _this.minorUnitVisibility = 0.33;
  72061. /**
  72062. * The grid opacity outside of the lines.
  72063. */
  72064. _this.opacity = 1.0;
  72065. /**
  72066. * Determine RBG output is premultiplied by alpha value.
  72067. */
  72068. _this.preMultiplyAlpha = false;
  72069. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  72070. return _this;
  72071. }
  72072. /**
  72073. * Returns wehter or not the grid requires alpha blending.
  72074. */
  72075. GridMaterial.prototype.needAlphaBlending = function () {
  72076. return this.opacity < 1.0;
  72077. };
  72078. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72079. if (this.isFrozen) {
  72080. if (this._wasPreviouslyReady && subMesh.effect) {
  72081. return true;
  72082. }
  72083. }
  72084. if (!subMesh._materialDefines) {
  72085. subMesh._materialDefines = new GridMaterialDefines();
  72086. }
  72087. var defines = subMesh._materialDefines;
  72088. var scene = this.getScene();
  72089. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  72090. if (this._renderId === scene.getRenderId()) {
  72091. return true;
  72092. }
  72093. }
  72094. var engine = scene.getEngine();
  72095. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  72096. defines.TRANSPARENT = !defines.TRANSPARENT;
  72097. defines.markAsUnprocessed();
  72098. }
  72099. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  72100. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  72101. defines.markAsUnprocessed();
  72102. }
  72103. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  72104. // Get correct effect
  72105. if (defines.isDirty) {
  72106. defines.markAsProcessed();
  72107. scene.resetCachedMaterial();
  72108. // Attributes
  72109. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  72110. // Defines
  72111. var join = defines.toString();
  72112. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  72113. }
  72114. if (!subMesh.effect.isReady()) {
  72115. return false;
  72116. }
  72117. this._renderId = scene.getRenderId();
  72118. this._wasPreviouslyReady = true;
  72119. return true;
  72120. };
  72121. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  72122. var scene = this.getScene();
  72123. var defines = subMesh._materialDefines;
  72124. if (!defines) {
  72125. return;
  72126. }
  72127. var effect = subMesh.effect;
  72128. this._activeEffect = effect;
  72129. // Matrices
  72130. this.bindOnlyWorldMatrix(world);
  72131. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  72132. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  72133. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  72134. // Uniforms
  72135. if (this._mustRebind(scene, effect)) {
  72136. this._activeEffect.setColor3("mainColor", this.mainColor);
  72137. this._activeEffect.setColor3("lineColor", this.lineColor);
  72138. this._gridControl.x = this.gridRatio;
  72139. this._gridControl.y = Math.round(this.majorUnitFrequency);
  72140. this._gridControl.z = this.minorUnitVisibility;
  72141. this._gridControl.w = this.opacity;
  72142. this._activeEffect.setVector4("gridControl", this._gridControl);
  72143. }
  72144. // Fog
  72145. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  72146. this._afterBind(mesh, this._activeEffect);
  72147. };
  72148. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  72149. _super.prototype.dispose.call(this, forceDisposeEffect);
  72150. };
  72151. GridMaterial.prototype.clone = function (name) {
  72152. var _this = this;
  72153. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  72154. };
  72155. GridMaterial.prototype.serialize = function () {
  72156. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72157. serializationObject.customType = "BABYLON.GridMaterial";
  72158. return serializationObject;
  72159. };
  72160. GridMaterial.prototype.getClassName = function () {
  72161. return "GridMaterial";
  72162. };
  72163. GridMaterial.Parse = function (source, scene, rootUrl) {
  72164. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  72165. };
  72166. __decorate([
  72167. BABYLON.serializeAsColor3()
  72168. ], GridMaterial.prototype, "mainColor", void 0);
  72169. __decorate([
  72170. BABYLON.serializeAsColor3()
  72171. ], GridMaterial.prototype, "lineColor", void 0);
  72172. __decorate([
  72173. BABYLON.serialize()
  72174. ], GridMaterial.prototype, "gridRatio", void 0);
  72175. __decorate([
  72176. BABYLON.serialize()
  72177. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  72178. __decorate([
  72179. BABYLON.serialize()
  72180. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  72181. __decorate([
  72182. BABYLON.serialize()
  72183. ], GridMaterial.prototype, "opacity", void 0);
  72184. __decorate([
  72185. BABYLON.serialize()
  72186. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  72187. return GridMaterial;
  72188. }(BABYLON.PushMaterial));
  72189. BABYLON.GridMaterial = GridMaterial;
  72190. })(BABYLON || (BABYLON = {}));
  72191. //# sourceMappingURL=babylon.gridmaterial.js.map
  72192. 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}";
  72193. 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}";
  72194. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  72195. var BABYLON;
  72196. (function (BABYLON) {
  72197. var GLTFLoaderCoordinateSystemMode;
  72198. (function (GLTFLoaderCoordinateSystemMode) {
  72199. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  72200. // 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.
  72201. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  72202. // The glTF right-handed data is not transformed in any form and is loaded directly.
  72203. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  72204. // Sets the useRightHandedSystem flag on the scene.
  72205. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  72206. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  72207. var GLTFFileLoader = (function () {
  72208. function GLTFFileLoader() {
  72209. // V2 options
  72210. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  72211. this.name = "gltf";
  72212. this.extensions = {
  72213. ".gltf": { isBinary: false },
  72214. ".glb": { isBinary: true }
  72215. };
  72216. }
  72217. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  72218. var loaderData = GLTFFileLoader._parse(data, onError);
  72219. if (!loaderData) {
  72220. return;
  72221. }
  72222. var loader = this._getLoader(loaderData, onError);
  72223. if (!loader) {
  72224. return;
  72225. }
  72226. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  72227. };
  72228. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  72229. var loaderData = GLTFFileLoader._parse(data, onError);
  72230. if (!loaderData) {
  72231. return;
  72232. }
  72233. var loader = this._getLoader(loaderData, onError);
  72234. if (!loader) {
  72235. return;
  72236. }
  72237. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  72238. };
  72239. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  72240. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  72241. };
  72242. GLTFFileLoader._parse = function (data, onError) {
  72243. if (data instanceof ArrayBuffer) {
  72244. return GLTFFileLoader._parseBinary(data, onError);
  72245. }
  72246. try {
  72247. return {
  72248. json: JSON.parse(data),
  72249. bin: null
  72250. };
  72251. }
  72252. catch (e) {
  72253. onError(e.message);
  72254. return null;
  72255. }
  72256. };
  72257. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  72258. var loaderVersion = { major: 2, minor: 0 };
  72259. var asset = loaderData.json.asset || {};
  72260. var version = GLTFFileLoader._parseVersion(asset.version);
  72261. if (!version) {
  72262. onError("Invalid version: " + asset.version);
  72263. return null;
  72264. }
  72265. if (asset.minVersion !== undefined) {
  72266. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  72267. if (!minVersion) {
  72268. onError("Invalid minimum version: " + asset.minVersion);
  72269. return null;
  72270. }
  72271. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  72272. onError("Incompatible minimum version: " + asset.minVersion);
  72273. return null;
  72274. }
  72275. }
  72276. var createLoaders = {
  72277. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  72278. 2: GLTFFileLoader.CreateGLTFLoaderV2
  72279. };
  72280. var createLoader = createLoaders[version.major];
  72281. if (!createLoader) {
  72282. onError("Unsupported version: " + asset.version);
  72283. return null;
  72284. }
  72285. return createLoader(this);
  72286. };
  72287. GLTFFileLoader._parseBinary = function (data, onError) {
  72288. var Binary = {
  72289. Magic: 0x46546C67
  72290. };
  72291. var binaryReader = new BinaryReader(data);
  72292. var magic = binaryReader.readUint32();
  72293. if (magic !== Binary.Magic) {
  72294. onError("Unexpected magic: " + magic);
  72295. return null;
  72296. }
  72297. var version = binaryReader.readUint32();
  72298. switch (version) {
  72299. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  72300. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  72301. }
  72302. onError("Unsupported version: " + version);
  72303. return null;
  72304. };
  72305. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  72306. var ContentFormat = {
  72307. JSON: 0
  72308. };
  72309. var length = binaryReader.readUint32();
  72310. if (length != binaryReader.getLength()) {
  72311. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  72312. return null;
  72313. }
  72314. var contentLength = binaryReader.readUint32();
  72315. var contentFormat = binaryReader.readUint32();
  72316. var content;
  72317. switch (contentFormat) {
  72318. case ContentFormat.JSON:
  72319. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  72320. break;
  72321. default:
  72322. onError("Unexpected content format: " + contentFormat);
  72323. return null;
  72324. }
  72325. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  72326. var body = binaryReader.readUint8Array(bytesRemaining);
  72327. return {
  72328. json: content,
  72329. bin: body
  72330. };
  72331. };
  72332. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  72333. var ChunkFormat = {
  72334. JSON: 0x4E4F534A,
  72335. BIN: 0x004E4942
  72336. };
  72337. var length = binaryReader.readUint32();
  72338. if (length !== binaryReader.getLength()) {
  72339. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  72340. return null;
  72341. }
  72342. // JSON chunk
  72343. var chunkLength = binaryReader.readUint32();
  72344. var chunkFormat = binaryReader.readUint32();
  72345. if (chunkFormat !== ChunkFormat.JSON) {
  72346. onError("First chunk format is not JSON");
  72347. return null;
  72348. }
  72349. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  72350. // Look for BIN chunk
  72351. var bin = null;
  72352. while (binaryReader.getPosition() < binaryReader.getLength()) {
  72353. chunkLength = binaryReader.readUint32();
  72354. chunkFormat = binaryReader.readUint32();
  72355. switch (chunkFormat) {
  72356. case ChunkFormat.JSON:
  72357. onError("Unexpected JSON chunk");
  72358. return null;
  72359. case ChunkFormat.BIN:
  72360. bin = binaryReader.readUint8Array(chunkLength);
  72361. break;
  72362. default:
  72363. // ignore unrecognized chunkFormat
  72364. binaryReader.skipBytes(chunkLength);
  72365. break;
  72366. }
  72367. }
  72368. return {
  72369. json: json,
  72370. bin: bin
  72371. };
  72372. };
  72373. GLTFFileLoader._parseVersion = function (version) {
  72374. if (!version) {
  72375. return null;
  72376. }
  72377. var parts = version.split(".");
  72378. if (parts.length != 2) {
  72379. return null;
  72380. }
  72381. var major = +parts[0];
  72382. if (isNaN(major)) {
  72383. return null;
  72384. }
  72385. var minor = +parts[1];
  72386. if (isNaN(minor)) {
  72387. return null;
  72388. }
  72389. return {
  72390. major: major,
  72391. minor: minor
  72392. };
  72393. };
  72394. GLTFFileLoader._compareVersion = function (a, b) {
  72395. if (a.major > b.major)
  72396. return 1;
  72397. if (a.major < b.major)
  72398. return -1;
  72399. if (a.minor > b.minor)
  72400. return 1;
  72401. if (a.minor < b.minor)
  72402. return -1;
  72403. return 0;
  72404. };
  72405. GLTFFileLoader._decodeBufferToText = function (view) {
  72406. var result = "";
  72407. var length = view.byteLength;
  72408. for (var i = 0; i < length; ++i) {
  72409. result += String.fromCharCode(view[i]);
  72410. }
  72411. return result;
  72412. };
  72413. // V1 options
  72414. GLTFFileLoader.HomogeneousCoordinates = false;
  72415. GLTFFileLoader.IncrementalLoading = true;
  72416. return GLTFFileLoader;
  72417. }());
  72418. BABYLON.GLTFFileLoader = GLTFFileLoader;
  72419. var BinaryReader = (function () {
  72420. function BinaryReader(arrayBuffer) {
  72421. this._arrayBuffer = arrayBuffer;
  72422. this._dataView = new DataView(arrayBuffer);
  72423. this._byteOffset = 0;
  72424. }
  72425. BinaryReader.prototype.getPosition = function () {
  72426. return this._byteOffset;
  72427. };
  72428. BinaryReader.prototype.getLength = function () {
  72429. return this._arrayBuffer.byteLength;
  72430. };
  72431. BinaryReader.prototype.readUint32 = function () {
  72432. var value = this._dataView.getUint32(this._byteOffset, true);
  72433. this._byteOffset += 4;
  72434. return value;
  72435. };
  72436. BinaryReader.prototype.readUint8Array = function (length) {
  72437. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  72438. this._byteOffset += length;
  72439. return value;
  72440. };
  72441. BinaryReader.prototype.skipBytes = function (length) {
  72442. this._byteOffset += length;
  72443. };
  72444. return BinaryReader;
  72445. }());
  72446. if (BABYLON.SceneLoader) {
  72447. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  72448. }
  72449. })(BABYLON || (BABYLON = {}));
  72450. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  72451. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  72452. var BABYLON;
  72453. (function (BABYLON) {
  72454. var GLTF1;
  72455. (function (GLTF1) {
  72456. /**
  72457. * Enums
  72458. */
  72459. var EComponentType;
  72460. (function (EComponentType) {
  72461. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  72462. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  72463. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  72464. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  72465. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  72466. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  72467. var EShaderType;
  72468. (function (EShaderType) {
  72469. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  72470. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  72471. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  72472. var EParameterType;
  72473. (function (EParameterType) {
  72474. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  72475. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  72476. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  72477. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  72478. EParameterType[EParameterType["INT"] = 5124] = "INT";
  72479. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  72480. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  72481. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  72482. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  72483. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  72484. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  72485. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  72486. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  72487. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  72488. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  72489. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  72490. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  72491. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  72492. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  72493. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  72494. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  72495. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  72496. var ETextureWrapMode;
  72497. (function (ETextureWrapMode) {
  72498. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  72499. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  72500. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  72501. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  72502. var ETextureFilterType;
  72503. (function (ETextureFilterType) {
  72504. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  72505. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  72506. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  72507. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  72508. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  72509. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  72510. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  72511. var ETextureFormat;
  72512. (function (ETextureFormat) {
  72513. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  72514. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  72515. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  72516. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  72517. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  72518. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  72519. var ECullingType;
  72520. (function (ECullingType) {
  72521. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  72522. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  72523. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  72524. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  72525. var EBlendingFunction;
  72526. (function (EBlendingFunction) {
  72527. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  72528. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  72529. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  72530. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  72531. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  72532. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  72533. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  72534. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  72535. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  72536. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  72537. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  72538. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  72539. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  72540. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  72541. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  72542. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  72543. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  72544. })(BABYLON || (BABYLON = {}));
  72545. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  72546. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  72547. var BABYLON;
  72548. (function (BABYLON) {
  72549. var GLTF1;
  72550. (function (GLTF1) {
  72551. /**
  72552. * Tokenizer. Used for shaders compatibility
  72553. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  72554. */
  72555. var ETokenType;
  72556. (function (ETokenType) {
  72557. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  72558. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  72559. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  72560. })(ETokenType || (ETokenType = {}));
  72561. var Tokenizer = (function () {
  72562. function Tokenizer(toParse) {
  72563. this._pos = 0;
  72564. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  72565. this._toParse = toParse;
  72566. this._maxPos = toParse.length;
  72567. }
  72568. Tokenizer.prototype.getNextToken = function () {
  72569. if (this.isEnd())
  72570. return ETokenType.END_OF_INPUT;
  72571. this.currentString = this.read();
  72572. this.currentToken = ETokenType.UNKNOWN;
  72573. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  72574. this.currentToken = ETokenType.IDENTIFIER;
  72575. this.currentIdentifier = this.currentString;
  72576. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  72577. this.currentIdentifier += this.currentString;
  72578. this.forward();
  72579. }
  72580. }
  72581. return this.currentToken;
  72582. };
  72583. Tokenizer.prototype.peek = function () {
  72584. return this._toParse[this._pos];
  72585. };
  72586. Tokenizer.prototype.read = function () {
  72587. return this._toParse[this._pos++];
  72588. };
  72589. Tokenizer.prototype.forward = function () {
  72590. this._pos++;
  72591. };
  72592. Tokenizer.prototype.isEnd = function () {
  72593. return this._pos >= this._maxPos;
  72594. };
  72595. return Tokenizer;
  72596. }());
  72597. /**
  72598. * Values
  72599. */
  72600. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  72601. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  72602. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  72603. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  72604. /**
  72605. * Parse
  72606. */
  72607. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  72608. for (var buf in parsedBuffers) {
  72609. var parsedBuffer = parsedBuffers[buf];
  72610. gltfRuntime.buffers[buf] = parsedBuffer;
  72611. gltfRuntime.buffersCount++;
  72612. }
  72613. };
  72614. var parseShaders = function (parsedShaders, gltfRuntime) {
  72615. for (var sha in parsedShaders) {
  72616. var parsedShader = parsedShaders[sha];
  72617. gltfRuntime.shaders[sha] = parsedShader;
  72618. gltfRuntime.shaderscount++;
  72619. }
  72620. };
  72621. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  72622. for (var object in parsedObjects) {
  72623. var parsedObject = parsedObjects[object];
  72624. gltfRuntime[runtimeProperty][object] = parsedObject;
  72625. }
  72626. };
  72627. /**
  72628. * Utils
  72629. */
  72630. var normalizeUVs = function (buffer) {
  72631. if (!buffer) {
  72632. return;
  72633. }
  72634. for (var i = 0; i < buffer.length / 2; i++) {
  72635. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  72636. }
  72637. };
  72638. var replaceInString = function (str, searchValue, replaceValue) {
  72639. while (str.indexOf(searchValue) !== -1) {
  72640. str = str.replace(searchValue, replaceValue);
  72641. }
  72642. return str;
  72643. };
  72644. var getAttribute = function (attributeParameter) {
  72645. if (attributeParameter.semantic === "NORMAL") {
  72646. return "normal";
  72647. }
  72648. else if (attributeParameter.semantic === "POSITION") {
  72649. return "position";
  72650. }
  72651. else if (attributeParameter.semantic === "JOINT") {
  72652. return "matricesIndices";
  72653. }
  72654. else if (attributeParameter.semantic === "WEIGHT") {
  72655. return "matricesWeights";
  72656. }
  72657. else if (attributeParameter.semantic === "COLOR") {
  72658. return "color";
  72659. }
  72660. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  72661. var channel = Number(attributeParameter.semantic.split("_")[1]);
  72662. return "uv" + (channel === 0 ? "" : channel + 1);
  72663. }
  72664. };
  72665. /**
  72666. * Returns the animation path (glTF -> Babylon)
  72667. */
  72668. var getAnimationPath = function (path) {
  72669. var index = glTFAnimationPaths.indexOf(path);
  72670. if (index !== -1) {
  72671. return babylonAnimationPaths[index];
  72672. }
  72673. return path;
  72674. };
  72675. /**
  72676. * Loads and creates animations
  72677. */
  72678. var loadAnimations = function (gltfRuntime) {
  72679. for (var anim in gltfRuntime.animations) {
  72680. var animation = gltfRuntime.animations[anim];
  72681. var lastAnimation = null;
  72682. for (var i = 0; i < animation.channels.length; i++) {
  72683. // Get parameters and load buffers
  72684. var channel = animation.channels[i];
  72685. var sampler = animation.samplers[channel.sampler];
  72686. if (!sampler) {
  72687. continue;
  72688. }
  72689. var inputData = null;
  72690. var outputData = null;
  72691. if (animation.parameters) {
  72692. inputData = animation.parameters[sampler.input];
  72693. outputData = animation.parameters[sampler.output];
  72694. }
  72695. else {
  72696. inputData = sampler.input;
  72697. outputData = sampler.output;
  72698. }
  72699. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  72700. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  72701. var targetID = channel.target.id;
  72702. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  72703. if (targetNode === null) {
  72704. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  72705. }
  72706. if (targetNode === null) {
  72707. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  72708. continue;
  72709. }
  72710. var isBone = targetNode instanceof BABYLON.Bone;
  72711. // Get target path (position, rotation or scaling)
  72712. var targetPath = channel.target.path;
  72713. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  72714. if (targetPathIndex !== -1) {
  72715. targetPath = babylonAnimationPaths[targetPathIndex];
  72716. }
  72717. // Determine animation type
  72718. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  72719. if (!isBone) {
  72720. if (targetPath === "rotationQuaternion") {
  72721. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  72722. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  72723. }
  72724. else {
  72725. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  72726. }
  72727. }
  72728. // Create animation and key frames
  72729. var babylonAnimation = null;
  72730. var keys = [];
  72731. var arrayOffset = 0;
  72732. var modifyKey = false;
  72733. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  72734. babylonAnimation = lastAnimation;
  72735. modifyKey = true;
  72736. }
  72737. if (!modifyKey) {
  72738. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  72739. }
  72740. // For each frame
  72741. for (var j = 0; j < bufferInput.length; j++) {
  72742. var value = null;
  72743. if (targetPath === "rotationQuaternion") {
  72744. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  72745. arrayOffset += 4;
  72746. }
  72747. else {
  72748. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  72749. arrayOffset += 3;
  72750. }
  72751. if (isBone) {
  72752. var bone = targetNode;
  72753. var translation = BABYLON.Vector3.Zero();
  72754. var rotationQuaternion = new BABYLON.Quaternion();
  72755. var scaling = BABYLON.Vector3.Zero();
  72756. // Warning on decompose
  72757. var mat = bone.getBaseMatrix();
  72758. if (modifyKey) {
  72759. mat = lastAnimation.getKeys()[j].value;
  72760. }
  72761. mat.decompose(scaling, rotationQuaternion, translation);
  72762. if (targetPath === "position") {
  72763. translation = value;
  72764. }
  72765. else if (targetPath === "rotationQuaternion") {
  72766. rotationQuaternion = value;
  72767. }
  72768. else {
  72769. scaling = value;
  72770. }
  72771. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  72772. }
  72773. if (!modifyKey) {
  72774. keys.push({
  72775. frame: bufferInput[j],
  72776. value: value
  72777. });
  72778. }
  72779. else {
  72780. lastAnimation.getKeys()[j].value = value;
  72781. }
  72782. }
  72783. // Finish
  72784. if (!modifyKey) {
  72785. babylonAnimation.setKeys(keys);
  72786. targetNode.animations.push(babylonAnimation);
  72787. }
  72788. lastAnimation = babylonAnimation;
  72789. gltfRuntime.scene.stopAnimation(targetNode);
  72790. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  72791. }
  72792. }
  72793. };
  72794. /**
  72795. * Returns the bones transformation matrix
  72796. */
  72797. var configureBoneTransformation = function (node) {
  72798. var mat = null;
  72799. if (node.translation || node.rotation || node.scale) {
  72800. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  72801. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  72802. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  72803. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  72804. }
  72805. else {
  72806. mat = BABYLON.Matrix.FromArray(node.matrix);
  72807. }
  72808. return mat;
  72809. };
  72810. /**
  72811. * Returns the parent bone
  72812. */
  72813. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  72814. // Try to find
  72815. for (var i = 0; i < newSkeleton.bones.length; i++) {
  72816. if (newSkeleton.bones[i].name === jointName) {
  72817. return newSkeleton.bones[i];
  72818. }
  72819. }
  72820. // Not found, search in gltf nodes
  72821. var nodes = gltfRuntime.nodes;
  72822. for (var nde in nodes) {
  72823. var node = nodes[nde];
  72824. if (!node.jointName) {
  72825. continue;
  72826. }
  72827. var children = node.children;
  72828. for (var i = 0; i < children.length; i++) {
  72829. var child = gltfRuntime.nodes[children[i]];
  72830. if (!child.jointName) {
  72831. continue;
  72832. }
  72833. if (child.jointName === jointName) {
  72834. var mat = configureBoneTransformation(node);
  72835. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  72836. bone.id = nde;
  72837. return bone;
  72838. }
  72839. }
  72840. }
  72841. return null;
  72842. };
  72843. /**
  72844. * Returns the appropriate root node
  72845. */
  72846. var getNodeToRoot = function (nodesToRoot, id) {
  72847. for (var i = 0; i < nodesToRoot.length; i++) {
  72848. var nodeToRoot = nodesToRoot[i];
  72849. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  72850. var child = nodeToRoot.node.children[j];
  72851. if (child === id) {
  72852. return nodeToRoot.bone;
  72853. }
  72854. }
  72855. }
  72856. return null;
  72857. };
  72858. /**
  72859. * Returns the node with the joint name
  72860. */
  72861. var getJointNode = function (gltfRuntime, jointName) {
  72862. var nodes = gltfRuntime.nodes;
  72863. var node = nodes[jointName];
  72864. if (node) {
  72865. return {
  72866. node: node,
  72867. id: jointName
  72868. };
  72869. }
  72870. for (var nde in nodes) {
  72871. node = nodes[nde];
  72872. if (node.jointName === jointName) {
  72873. return {
  72874. node: node,
  72875. id: nde
  72876. };
  72877. }
  72878. }
  72879. return null;
  72880. };
  72881. /**
  72882. * Checks if a nodes is in joints
  72883. */
  72884. var nodeIsInJoints = function (skins, id) {
  72885. for (var i = 0; i < skins.jointNames.length; i++) {
  72886. if (skins.jointNames[i] === id) {
  72887. return true;
  72888. }
  72889. }
  72890. return false;
  72891. };
  72892. /**
  72893. * Fills the nodes to root for bones and builds hierarchy
  72894. */
  72895. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  72896. // Creates nodes for root
  72897. for (var nde in gltfRuntime.nodes) {
  72898. var node = gltfRuntime.nodes[nde];
  72899. var id = nde;
  72900. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  72901. continue;
  72902. }
  72903. // Create node to root bone
  72904. var mat = configureBoneTransformation(node);
  72905. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  72906. bone.id = id;
  72907. nodesToRoot.push({ bone: bone, node: node, id: id });
  72908. }
  72909. // Parenting
  72910. for (var i = 0; i < nodesToRoot.length; i++) {
  72911. var nodeToRoot = nodesToRoot[i];
  72912. var children = nodeToRoot.node.children;
  72913. for (var j = 0; j < children.length; j++) {
  72914. var child = null;
  72915. for (var k = 0; k < nodesToRoot.length; k++) {
  72916. if (nodesToRoot[k].id === children[j]) {
  72917. child = nodesToRoot[k];
  72918. break;
  72919. }
  72920. }
  72921. if (child) {
  72922. child.bone._parent = nodeToRoot.bone;
  72923. nodeToRoot.bone.children.push(child.bone);
  72924. }
  72925. }
  72926. }
  72927. };
  72928. var printMat = function (m) {
  72929. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  72930. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  72931. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  72932. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  72933. };
  72934. /**
  72935. * Imports a skeleton
  72936. */
  72937. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  72938. if (!newSkeleton) {
  72939. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  72940. }
  72941. if (!skins.babylonSkeleton) {
  72942. return newSkeleton;
  72943. }
  72944. // Matrices
  72945. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  72946. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  72947. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  72948. // Find the root bones
  72949. var nodesToRoot = [];
  72950. var nodesToRootToAdd = [];
  72951. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  72952. newSkeleton.bones = [];
  72953. // Joints
  72954. for (var i = 0; i < skins.jointNames.length; i++) {
  72955. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  72956. var node = jointNode.node;
  72957. if (!node) {
  72958. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  72959. continue;
  72960. }
  72961. var id = jointNode.id;
  72962. // Optimize, if the bone already exists...
  72963. var existingBone = gltfRuntime.scene.getBoneByID(id);
  72964. if (existingBone) {
  72965. newSkeleton.bones.push(existingBone);
  72966. continue;
  72967. }
  72968. // Search for parent bone
  72969. var foundBone = false;
  72970. var parentBone = null;
  72971. for (var j = 0; j < i; j++) {
  72972. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  72973. if (!joint) {
  72974. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  72975. continue;
  72976. }
  72977. var children = joint.children;
  72978. if (!children) {
  72979. continue;
  72980. }
  72981. foundBone = false;
  72982. for (var k = 0; k < children.length; k++) {
  72983. if (children[k] === id) {
  72984. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  72985. foundBone = true;
  72986. break;
  72987. }
  72988. }
  72989. if (foundBone) {
  72990. break;
  72991. }
  72992. }
  72993. // Create bone
  72994. var mat = configureBoneTransformation(node);
  72995. if (!parentBone && nodesToRoot.length > 0) {
  72996. parentBone = getNodeToRoot(nodesToRoot, id);
  72997. if (parentBone) {
  72998. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  72999. nodesToRootToAdd.push(parentBone);
  73000. }
  73001. }
  73002. }
  73003. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  73004. bone.id = id;
  73005. }
  73006. // Polish
  73007. var bones = newSkeleton.bones;
  73008. newSkeleton.bones = [];
  73009. for (var i = 0; i < skins.jointNames.length; i++) {
  73010. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  73011. if (!jointNode) {
  73012. continue;
  73013. }
  73014. for (var j = 0; j < bones.length; j++) {
  73015. if (bones[j].id === jointNode.id) {
  73016. newSkeleton.bones.push(bones[j]);
  73017. break;
  73018. }
  73019. }
  73020. }
  73021. newSkeleton.prepare();
  73022. // Finish
  73023. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  73024. newSkeleton.bones.push(nodesToRootToAdd[i]);
  73025. }
  73026. return newSkeleton;
  73027. };
  73028. /**
  73029. * Imports a mesh and its geometries
  73030. */
  73031. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  73032. if (!newMesh) {
  73033. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  73034. newMesh.id = id;
  73035. }
  73036. if (!node.babylonNode) {
  73037. return newMesh;
  73038. }
  73039. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  73040. if (!newMesh.material) {
  73041. newMesh.material = multiMat;
  73042. }
  73043. var vertexData = new BABYLON.VertexData();
  73044. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  73045. var verticesStarts = [];
  73046. var verticesCounts = [];
  73047. var indexStarts = [];
  73048. var indexCounts = [];
  73049. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  73050. var meshID = meshes[meshIndex];
  73051. var mesh = gltfRuntime.meshes[meshID];
  73052. if (!mesh) {
  73053. continue;
  73054. }
  73055. // Positions, normals and UVs
  73056. for (var i = 0; i < mesh.primitives.length; i++) {
  73057. // Temporary vertex data
  73058. var tempVertexData = new BABYLON.VertexData();
  73059. var primitive = mesh.primitives[i];
  73060. if (primitive.mode !== 4) {
  73061. // continue;
  73062. }
  73063. var attributes = primitive.attributes;
  73064. var accessor = null;
  73065. var buffer = null;
  73066. // Set positions, normal and uvs
  73067. for (var semantic in attributes) {
  73068. // Link accessor and buffer view
  73069. accessor = gltfRuntime.accessors[attributes[semantic]];
  73070. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73071. if (semantic === "NORMAL") {
  73072. tempVertexData.normals = new Float32Array(buffer.length);
  73073. tempVertexData.normals.set(buffer);
  73074. }
  73075. else if (semantic === "POSITION") {
  73076. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  73077. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  73078. for (var j = 0; j < buffer.length; j += 4) {
  73079. tempVertexData.positions[j] = buffer[j];
  73080. tempVertexData.positions[j + 1] = buffer[j + 1];
  73081. tempVertexData.positions[j + 2] = buffer[j + 2];
  73082. }
  73083. }
  73084. else {
  73085. tempVertexData.positions = new Float32Array(buffer.length);
  73086. tempVertexData.positions.set(buffer);
  73087. }
  73088. verticesCounts.push(tempVertexData.positions.length);
  73089. }
  73090. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  73091. var channel = Number(semantic.split("_")[1]);
  73092. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  73093. var uvs = new Float32Array(buffer.length);
  73094. uvs.set(buffer);
  73095. normalizeUVs(uvs);
  73096. tempVertexData.set(uvs, uvKind);
  73097. }
  73098. else if (semantic === "JOINT") {
  73099. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  73100. tempVertexData.matricesIndices.set(buffer);
  73101. }
  73102. else if (semantic === "WEIGHT") {
  73103. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  73104. tempVertexData.matricesWeights.set(buffer);
  73105. }
  73106. else if (semantic === "COLOR") {
  73107. tempVertexData.colors = new Float32Array(buffer.length);
  73108. tempVertexData.colors.set(buffer);
  73109. }
  73110. }
  73111. // Indices
  73112. accessor = gltfRuntime.accessors[primitive.indices];
  73113. if (accessor) {
  73114. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73115. tempVertexData.indices = new Int32Array(buffer.length);
  73116. tempVertexData.indices.set(buffer);
  73117. indexCounts.push(tempVertexData.indices.length);
  73118. }
  73119. else {
  73120. // Set indices on the fly
  73121. var indices = [];
  73122. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  73123. indices.push(j);
  73124. }
  73125. tempVertexData.indices = new Int32Array(indices);
  73126. indexCounts.push(tempVertexData.indices.length);
  73127. }
  73128. vertexData.merge(tempVertexData);
  73129. tempVertexData = undefined;
  73130. // Sub material
  73131. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  73132. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  73133. // Update vertices start and index start
  73134. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  73135. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  73136. }
  73137. }
  73138. // Apply geometry
  73139. geometry.setAllVerticesData(vertexData, false);
  73140. newMesh.computeWorldMatrix(true);
  73141. // Apply submeshes
  73142. newMesh.subMeshes = [];
  73143. var index = 0;
  73144. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  73145. var meshID = meshes[meshIndex];
  73146. var mesh = gltfRuntime.meshes[meshID];
  73147. if (!mesh) {
  73148. continue;
  73149. }
  73150. for (var i = 0; i < mesh.primitives.length; i++) {
  73151. if (mesh.primitives[i].mode !== 4) {
  73152. //continue;
  73153. }
  73154. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  73155. index++;
  73156. }
  73157. }
  73158. // Finish
  73159. return newMesh;
  73160. };
  73161. /**
  73162. * Configure node transformation from position, rotation and scaling
  73163. */
  73164. var configureNode = function (newNode, position, rotation, scaling) {
  73165. if (newNode.position) {
  73166. newNode.position = position;
  73167. }
  73168. if (newNode.rotationQuaternion || newNode.rotation) {
  73169. newNode.rotationQuaternion = rotation;
  73170. }
  73171. if (newNode.scaling) {
  73172. newNode.scaling = scaling;
  73173. }
  73174. };
  73175. /**
  73176. * Configures node from transformation matrix
  73177. */
  73178. var configureNodeFromMatrix = function (newNode, node, parent) {
  73179. if (node.matrix) {
  73180. var position = new BABYLON.Vector3(0, 0, 0);
  73181. var rotation = new BABYLON.Quaternion();
  73182. var scaling = new BABYLON.Vector3(0, 0, 0);
  73183. var mat = BABYLON.Matrix.FromArray(node.matrix);
  73184. mat.decompose(scaling, rotation, position);
  73185. configureNode(newNode, position, rotation, scaling);
  73186. }
  73187. else {
  73188. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  73189. }
  73190. newNode.computeWorldMatrix(true);
  73191. };
  73192. /**
  73193. * Imports a node
  73194. */
  73195. var importNode = function (gltfRuntime, node, id, parent) {
  73196. var lastNode = null;
  73197. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  73198. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  73199. return null;
  73200. }
  73201. }
  73202. // Meshes
  73203. if (node.skin) {
  73204. if (node.meshes) {
  73205. var skin = gltfRuntime.skins[node.skin];
  73206. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  73207. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  73208. if (newMesh.skeleton === null) {
  73209. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  73210. if (!skin.babylonSkeleton) {
  73211. skin.babylonSkeleton = newMesh.skeleton;
  73212. }
  73213. }
  73214. lastNode = newMesh;
  73215. }
  73216. }
  73217. else if (node.meshes) {
  73218. /**
  73219. * Improve meshes property
  73220. */
  73221. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  73222. lastNode = newMesh;
  73223. }
  73224. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  73225. var light = gltfRuntime.lights[node.light];
  73226. if (light) {
  73227. if (light.type === "ambient") {
  73228. var ambienLight = light[light.type];
  73229. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73230. hemiLight.name = node.name;
  73231. if (ambienLight.color) {
  73232. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  73233. }
  73234. lastNode = hemiLight;
  73235. }
  73236. else if (light.type === "directional") {
  73237. var directionalLight = light[light.type];
  73238. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73239. dirLight.name = node.name;
  73240. if (directionalLight.color) {
  73241. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  73242. }
  73243. lastNode = dirLight;
  73244. }
  73245. else if (light.type === "point") {
  73246. var pointLight = light[light.type];
  73247. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73248. ptLight.name = node.name;
  73249. if (pointLight.color) {
  73250. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  73251. }
  73252. lastNode = ptLight;
  73253. }
  73254. else if (light.type === "spot") {
  73255. var spotLight = light[light.type];
  73256. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  73257. spLight.name = node.name;
  73258. if (spotLight.color) {
  73259. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  73260. }
  73261. if (spotLight.fallOfAngle) {
  73262. spLight.angle = spotLight.fallOfAngle;
  73263. }
  73264. if (spotLight.fallOffExponent) {
  73265. spLight.exponent = spotLight.fallOffExponent;
  73266. }
  73267. lastNode = spLight;
  73268. }
  73269. }
  73270. }
  73271. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  73272. var camera = gltfRuntime.cameras[node.camera];
  73273. if (camera) {
  73274. if (camera.type === "orthographic") {
  73275. var orthographicCamera = camera[camera.type];
  73276. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73277. orthoCamera.name = node.name;
  73278. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  73279. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  73280. lastNode = orthoCamera;
  73281. }
  73282. else if (camera.type === "perspective") {
  73283. var perspectiveCamera = camera[camera.type];
  73284. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73285. persCamera.name = node.name;
  73286. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  73287. if (!perspectiveCamera.aspectRatio) {
  73288. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  73289. }
  73290. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  73291. persCamera.maxZ = perspectiveCamera.zfar;
  73292. persCamera.minZ = perspectiveCamera.znear;
  73293. }
  73294. lastNode = persCamera;
  73295. }
  73296. }
  73297. }
  73298. // Empty node
  73299. if (!node.jointName) {
  73300. if (node.babylonNode) {
  73301. return node.babylonNode;
  73302. }
  73303. else if (lastNode === null) {
  73304. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  73305. node.babylonNode = dummy;
  73306. lastNode = dummy;
  73307. }
  73308. }
  73309. if (lastNode !== null) {
  73310. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  73311. configureNodeFromMatrix(lastNode, node, parent);
  73312. }
  73313. else {
  73314. var translation = node.translation || [0, 0, 0];
  73315. var rotation = node.rotation || [0, 0, 0, 1];
  73316. var scale = node.scale || [1, 1, 1];
  73317. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  73318. }
  73319. lastNode.updateCache(true);
  73320. node.babylonNode = lastNode;
  73321. }
  73322. return lastNode;
  73323. };
  73324. /**
  73325. * Traverses nodes and creates them
  73326. */
  73327. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  73328. var node = gltfRuntime.nodes[id];
  73329. var newNode = null;
  73330. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  73331. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  73332. meshIncluded = true;
  73333. }
  73334. else {
  73335. meshIncluded = false;
  73336. }
  73337. }
  73338. else {
  73339. meshIncluded = true;
  73340. }
  73341. if (!node.jointName && meshIncluded) {
  73342. newNode = importNode(gltfRuntime, node, id, parent);
  73343. if (newNode !== null) {
  73344. newNode.id = id;
  73345. newNode.parent = parent;
  73346. }
  73347. }
  73348. if (node.children) {
  73349. for (var i = 0; i < node.children.length; i++) {
  73350. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  73351. }
  73352. }
  73353. };
  73354. /**
  73355. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  73356. */
  73357. var postLoad = function (gltfRuntime) {
  73358. // Nodes
  73359. var currentScene = gltfRuntime.currentScene;
  73360. if (currentScene) {
  73361. for (var i = 0; i < currentScene.nodes.length; i++) {
  73362. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73363. }
  73364. }
  73365. else {
  73366. for (var thing in gltfRuntime.scenes) {
  73367. currentScene = gltfRuntime.scenes[thing];
  73368. for (var i = 0; i < currentScene.nodes.length; i++) {
  73369. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73370. }
  73371. }
  73372. }
  73373. // Set animations
  73374. loadAnimations(gltfRuntime);
  73375. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  73376. var skeleton = gltfRuntime.scene.skeletons[i];
  73377. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  73378. }
  73379. };
  73380. /**
  73381. * onBind shaderrs callback to set uniforms and matrices
  73382. */
  73383. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  73384. var materialValues = material.values || technique.parameters;
  73385. for (var unif in unTreatedUniforms) {
  73386. var uniform = unTreatedUniforms[unif];
  73387. var type = uniform.type;
  73388. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  73389. if (uniform.semantic && !uniform.source && !uniform.node) {
  73390. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  73391. }
  73392. else if (uniform.semantic && (uniform.source || uniform.node)) {
  73393. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  73394. if (source === null) {
  73395. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  73396. }
  73397. if (source === null) {
  73398. continue;
  73399. }
  73400. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  73401. }
  73402. }
  73403. else {
  73404. var value = materialValues[technique.uniforms[unif]];
  73405. if (!value) {
  73406. continue;
  73407. }
  73408. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  73409. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  73410. if (texture === null || texture === undefined) {
  73411. continue;
  73412. }
  73413. shaderMaterial.getEffect().setTexture(unif, texture);
  73414. }
  73415. else {
  73416. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  73417. }
  73418. }
  73419. }
  73420. onSuccess(shaderMaterial);
  73421. };
  73422. /**
  73423. * Prepare uniforms to send the only one time
  73424. * Loads the appropriate textures
  73425. */
  73426. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  73427. var materialValues = material.values || technique.parameters;
  73428. var techniqueUniforms = technique.uniforms;
  73429. /**
  73430. * Prepare values here (not matrices)
  73431. */
  73432. for (var unif in unTreatedUniforms) {
  73433. var uniform = unTreatedUniforms[unif];
  73434. var type = uniform.type;
  73435. var value = materialValues[techniqueUniforms[unif]];
  73436. if (value === undefined) {
  73437. // In case the value is the same for all materials
  73438. value = uniform.value;
  73439. }
  73440. if (!value) {
  73441. continue;
  73442. }
  73443. var onLoadTexture = function (uniformName) {
  73444. return function (texture) {
  73445. if (uniform.value) {
  73446. // Static uniform
  73447. shaderMaterial.setTexture(uniformName, texture);
  73448. delete unTreatedUniforms[uniformName];
  73449. }
  73450. };
  73451. };
  73452. // Texture (sampler2D)
  73453. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  73454. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  73455. }
  73456. else {
  73457. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  73458. // Static uniform
  73459. delete unTreatedUniforms[unif];
  73460. }
  73461. }
  73462. }
  73463. };
  73464. /**
  73465. * Shader compilation failed
  73466. */
  73467. var onShaderCompileError = function (program, shaderMaterial, onError) {
  73468. return function (effect, error) {
  73469. shaderMaterial.dispose(true);
  73470. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  73471. };
  73472. };
  73473. /**
  73474. * Shader compilation success
  73475. */
  73476. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  73477. return function (_) {
  73478. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  73479. shaderMaterial.onBind = function (mesh) {
  73480. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  73481. };
  73482. };
  73483. };
  73484. /**
  73485. * Returns the appropriate uniform if already handled by babylon
  73486. */
  73487. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  73488. for (var unif in technique.uniforms) {
  73489. var uniform = technique.uniforms[unif];
  73490. var uniformParameter = technique.parameters[uniform];
  73491. if (tokenizer.currentIdentifier === unif) {
  73492. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  73493. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  73494. if (transformIndex !== -1) {
  73495. delete unTreatedUniforms[unif];
  73496. return babylonTransforms[transformIndex];
  73497. }
  73498. }
  73499. }
  73500. }
  73501. return tokenizer.currentIdentifier;
  73502. };
  73503. /**
  73504. * All shaders loaded. Create materials one by one
  73505. */
  73506. var importMaterials = function (gltfRuntime) {
  73507. // Create materials
  73508. for (var mat in gltfRuntime.materials) {
  73509. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  73510. }
  73511. };
  73512. /**
  73513. * Implementation of the base glTF spec
  73514. */
  73515. var GLTFLoaderBase = (function () {
  73516. function GLTFLoaderBase() {
  73517. }
  73518. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  73519. var gltfRuntime = {
  73520. extensions: {},
  73521. accessors: {},
  73522. buffers: {},
  73523. bufferViews: {},
  73524. meshes: {},
  73525. lights: {},
  73526. cameras: {},
  73527. nodes: {},
  73528. images: {},
  73529. textures: {},
  73530. shaders: {},
  73531. programs: {},
  73532. samplers: {},
  73533. techniques: {},
  73534. materials: {},
  73535. animations: {},
  73536. skins: {},
  73537. extensionsUsed: [],
  73538. scenes: {},
  73539. buffersCount: 0,
  73540. shaderscount: 0,
  73541. scene: scene,
  73542. rootUrl: rootUrl,
  73543. loadedBufferCount: 0,
  73544. loadedBufferViews: {},
  73545. loadedShaderCount: 0,
  73546. importOnlyMeshes: false,
  73547. dummyNodes: []
  73548. };
  73549. // Parse
  73550. if (parsedData.extensions) {
  73551. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  73552. }
  73553. if (parsedData.extensionsUsed) {
  73554. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  73555. }
  73556. if (parsedData.buffers) {
  73557. parseBuffers(parsedData.buffers, gltfRuntime);
  73558. }
  73559. if (parsedData.bufferViews) {
  73560. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  73561. }
  73562. if (parsedData.accessors) {
  73563. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  73564. }
  73565. if (parsedData.meshes) {
  73566. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  73567. }
  73568. if (parsedData.lights) {
  73569. parseObject(parsedData.lights, "lights", gltfRuntime);
  73570. }
  73571. if (parsedData.cameras) {
  73572. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  73573. }
  73574. if (parsedData.nodes) {
  73575. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  73576. }
  73577. if (parsedData.images) {
  73578. parseObject(parsedData.images, "images", gltfRuntime);
  73579. }
  73580. if (parsedData.textures) {
  73581. parseObject(parsedData.textures, "textures", gltfRuntime);
  73582. }
  73583. if (parsedData.shaders) {
  73584. parseShaders(parsedData.shaders, gltfRuntime);
  73585. }
  73586. if (parsedData.programs) {
  73587. parseObject(parsedData.programs, "programs", gltfRuntime);
  73588. }
  73589. if (parsedData.samplers) {
  73590. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  73591. }
  73592. if (parsedData.techniques) {
  73593. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  73594. }
  73595. if (parsedData.materials) {
  73596. parseObject(parsedData.materials, "materials", gltfRuntime);
  73597. }
  73598. if (parsedData.animations) {
  73599. parseObject(parsedData.animations, "animations", gltfRuntime);
  73600. }
  73601. if (parsedData.skins) {
  73602. parseObject(parsedData.skins, "skins", gltfRuntime);
  73603. }
  73604. if (parsedData.scenes) {
  73605. gltfRuntime.scenes = parsedData.scenes;
  73606. }
  73607. if (parsedData.scene && parsedData.scenes) {
  73608. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  73609. }
  73610. return gltfRuntime;
  73611. };
  73612. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  73613. var buffer = gltfRuntime.buffers[id];
  73614. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  73615. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  73616. }
  73617. else {
  73618. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  73619. onError(request.status + " " + request.statusText);
  73620. });
  73621. }
  73622. };
  73623. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  73624. var texture = gltfRuntime.textures[id];
  73625. if (!texture || !texture.source) {
  73626. onError(null);
  73627. return;
  73628. }
  73629. if (texture.babylonTexture) {
  73630. onSuccess(null);
  73631. return;
  73632. }
  73633. var source = gltfRuntime.images[texture.source];
  73634. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  73635. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  73636. }
  73637. else {
  73638. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  73639. onError(request.status + " " + request.statusText);
  73640. });
  73641. }
  73642. };
  73643. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  73644. var texture = gltfRuntime.textures[id];
  73645. if (texture.babylonTexture) {
  73646. onSuccess(texture.babylonTexture);
  73647. return;
  73648. }
  73649. var sampler = gltfRuntime.samplers[texture.sampler];
  73650. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  73651. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  73652. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  73653. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  73654. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  73655. var blob = new Blob([buffer]);
  73656. var blobURL = URL.createObjectURL(blob);
  73657. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  73658. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  73659. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  73660. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  73661. newTexture.name = id;
  73662. texture.babylonTexture = newTexture;
  73663. onSuccess(newTexture);
  73664. };
  73665. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  73666. var shader = gltfRuntime.shaders[id];
  73667. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  73668. var shaderString = atob(shader.uri.split(",")[1]);
  73669. onSuccess(shaderString);
  73670. }
  73671. else {
  73672. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  73673. onError(request.status + " " + request.statusText);
  73674. });
  73675. }
  73676. };
  73677. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  73678. var material = gltfRuntime.materials[id];
  73679. var technique = gltfRuntime.techniques[material.technique];
  73680. if (!technique) {
  73681. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  73682. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  73683. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  73684. onSuccess(defaultMaterial);
  73685. return;
  73686. }
  73687. var program = gltfRuntime.programs[technique.program];
  73688. var states = technique.states;
  73689. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  73690. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  73691. var newVertexShader = "";
  73692. var newPixelShader = "";
  73693. var vertexTokenizer = new Tokenizer(vertexShader);
  73694. var pixelTokenizer = new Tokenizer(pixelShader);
  73695. var unTreatedUniforms = {};
  73696. var uniforms = [];
  73697. var attributes = [];
  73698. var samplers = [];
  73699. // Fill uniform, sampler2D and attributes
  73700. for (var unif in technique.uniforms) {
  73701. var uniform = technique.uniforms[unif];
  73702. var uniformParameter = technique.parameters[uniform];
  73703. unTreatedUniforms[unif] = uniformParameter;
  73704. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  73705. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  73706. if (transformIndex !== -1) {
  73707. uniforms.push(babylonTransforms[transformIndex]);
  73708. delete unTreatedUniforms[unif];
  73709. }
  73710. else {
  73711. uniforms.push(unif);
  73712. }
  73713. }
  73714. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  73715. samplers.push(unif);
  73716. }
  73717. else {
  73718. uniforms.push(unif);
  73719. }
  73720. }
  73721. for (var attr in technique.attributes) {
  73722. var attribute = technique.attributes[attr];
  73723. var attributeParameter = technique.parameters[attribute];
  73724. if (attributeParameter.semantic) {
  73725. attributes.push(getAttribute(attributeParameter));
  73726. }
  73727. }
  73728. // Configure vertex shader
  73729. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  73730. var tokenType = vertexTokenizer.currentToken;
  73731. if (tokenType !== ETokenType.IDENTIFIER) {
  73732. newVertexShader += vertexTokenizer.currentString;
  73733. continue;
  73734. }
  73735. var foundAttribute = false;
  73736. for (var attr in technique.attributes) {
  73737. var attribute = technique.attributes[attr];
  73738. var attributeParameter = technique.parameters[attribute];
  73739. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  73740. newVertexShader += getAttribute(attributeParameter);
  73741. foundAttribute = true;
  73742. break;
  73743. }
  73744. }
  73745. if (foundAttribute) {
  73746. continue;
  73747. }
  73748. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  73749. }
  73750. // Configure pixel shader
  73751. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  73752. var tokenType = pixelTokenizer.currentToken;
  73753. if (tokenType !== ETokenType.IDENTIFIER) {
  73754. newPixelShader += pixelTokenizer.currentString;
  73755. continue;
  73756. }
  73757. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  73758. }
  73759. // Create shader material
  73760. var shaderPath = {
  73761. vertex: program.vertexShader + id,
  73762. fragment: program.fragmentShader + id
  73763. };
  73764. var options = {
  73765. attributes: attributes,
  73766. uniforms: uniforms,
  73767. samplers: samplers,
  73768. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  73769. };
  73770. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  73771. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  73772. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  73773. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  73774. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  73775. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  73776. if (states && states.functions) {
  73777. var functions = states.functions;
  73778. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  73779. shaderMaterial.backFaceCulling = false;
  73780. }
  73781. var blendFunc = functions.blendFuncSeparate;
  73782. if (blendFunc) {
  73783. 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) {
  73784. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  73785. }
  73786. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  73787. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  73788. }
  73789. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  73790. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  73791. }
  73792. 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) {
  73793. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  73794. }
  73795. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  73796. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  73797. }
  73798. 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) {
  73799. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  73800. }
  73801. }
  73802. }
  73803. };
  73804. return GLTFLoaderBase;
  73805. }());
  73806. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  73807. /**
  73808. * glTF V1 Loader
  73809. */
  73810. var GLTFLoader = (function () {
  73811. function GLTFLoader() {
  73812. }
  73813. GLTFLoader.RegisterExtension = function (extension) {
  73814. if (GLTFLoader.Extensions[extension.name]) {
  73815. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  73816. return;
  73817. }
  73818. GLTFLoader.Extensions[extension.name] = extension;
  73819. };
  73820. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  73821. var _this = this;
  73822. scene.useRightHandedSystem = true;
  73823. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  73824. gltfRuntime.importOnlyMeshes = true;
  73825. if (meshesNames === "") {
  73826. gltfRuntime.importMeshesNames = [];
  73827. }
  73828. else if (typeof meshesNames === "string") {
  73829. gltfRuntime.importMeshesNames = [meshesNames];
  73830. }
  73831. else if (meshesNames && !(meshesNames instanceof Array)) {
  73832. gltfRuntime.importMeshesNames = [meshesNames];
  73833. }
  73834. else {
  73835. gltfRuntime.importMeshesNames = [];
  73836. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  73837. }
  73838. // Create nodes
  73839. _this._createNodes(gltfRuntime);
  73840. var meshes = [];
  73841. var skeletons = [];
  73842. // Fill arrays of meshes and skeletons
  73843. for (var nde in gltfRuntime.nodes) {
  73844. var node = gltfRuntime.nodes[nde];
  73845. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  73846. meshes.push(node.babylonNode);
  73847. }
  73848. }
  73849. for (var skl in gltfRuntime.skins) {
  73850. var skin = gltfRuntime.skins[skl];
  73851. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  73852. skeletons.push(skin.babylonSkeleton);
  73853. }
  73854. }
  73855. // Load buffers, shaders, materials, etc.
  73856. _this._loadBuffersAsync(gltfRuntime, function () {
  73857. _this._loadShadersAsync(gltfRuntime, function () {
  73858. importMaterials(gltfRuntime);
  73859. postLoad(gltfRuntime);
  73860. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  73861. onSuccess(meshes, null, skeletons);
  73862. }
  73863. });
  73864. }, onProgress);
  73865. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  73866. onSuccess(meshes, null, skeletons);
  73867. }
  73868. }, onError);
  73869. return true;
  73870. };
  73871. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  73872. var _this = this;
  73873. scene.useRightHandedSystem = true;
  73874. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  73875. // Load runtime extensios
  73876. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  73877. // Create nodes
  73878. _this._createNodes(gltfRuntime);
  73879. // Load buffers, shaders, materials, etc.
  73880. _this._loadBuffersAsync(gltfRuntime, function () {
  73881. _this._loadShadersAsync(gltfRuntime, function () {
  73882. importMaterials(gltfRuntime);
  73883. postLoad(gltfRuntime);
  73884. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  73885. onSuccess();
  73886. }
  73887. });
  73888. });
  73889. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  73890. onSuccess();
  73891. }
  73892. }, onError);
  73893. }, onError);
  73894. };
  73895. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  73896. var hasShaders = false;
  73897. var processShader = function (sha, shader) {
  73898. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  73899. gltfRuntime.loadedShaderCount++;
  73900. if (shaderString) {
  73901. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  73902. }
  73903. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  73904. onload();
  73905. }
  73906. }, function () {
  73907. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  73908. });
  73909. };
  73910. for (var sha in gltfRuntime.shaders) {
  73911. hasShaders = true;
  73912. var shader = gltfRuntime.shaders[sha];
  73913. if (shader) {
  73914. processShader.bind(this, sha, shader)();
  73915. }
  73916. else {
  73917. BABYLON.Tools.Error("No shader named: " + sha);
  73918. }
  73919. }
  73920. if (!hasShaders) {
  73921. onload();
  73922. }
  73923. };
  73924. ;
  73925. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  73926. var hasBuffers = false;
  73927. var processBuffer = function (buf, buffer) {
  73928. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  73929. gltfRuntime.loadedBufferCount++;
  73930. if (bufferView) {
  73931. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  73932. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  73933. }
  73934. gltfRuntime.loadedBufferViews[buf] = bufferView;
  73935. }
  73936. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  73937. onLoad();
  73938. }
  73939. }, function () {
  73940. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  73941. });
  73942. };
  73943. for (var buf in gltfRuntime.buffers) {
  73944. hasBuffers = true;
  73945. var buffer = gltfRuntime.buffers[buf];
  73946. if (buffer) {
  73947. processBuffer.bind(this, buf, buffer)();
  73948. }
  73949. else {
  73950. BABYLON.Tools.Error("No buffer named: " + buf);
  73951. }
  73952. }
  73953. if (!hasBuffers) {
  73954. onLoad();
  73955. }
  73956. };
  73957. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  73958. var currentScene = gltfRuntime.currentScene;
  73959. if (currentScene) {
  73960. // Only one scene even if multiple scenes are defined
  73961. for (var i = 0; i < currentScene.nodes.length; i++) {
  73962. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73963. }
  73964. }
  73965. else {
  73966. // Load all scenes
  73967. for (var thing in gltfRuntime.scenes) {
  73968. currentScene = gltfRuntime.scenes[thing];
  73969. for (var i = 0; i < currentScene.nodes.length; i++) {
  73970. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73971. }
  73972. }
  73973. }
  73974. };
  73975. GLTFLoader.Extensions = {};
  73976. return GLTFLoader;
  73977. }());
  73978. GLTF1.GLTFLoader = GLTFLoader;
  73979. ;
  73980. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  73981. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  73982. })(BABYLON || (BABYLON = {}));
  73983. //# sourceMappingURL=babylon.glTFLoader.js.map
  73984. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73985. var BABYLON;
  73986. (function (BABYLON) {
  73987. var GLTF1;
  73988. (function (GLTF1) {
  73989. /**
  73990. * Utils functions for GLTF
  73991. */
  73992. var GLTFUtils = (function () {
  73993. function GLTFUtils() {
  73994. }
  73995. /**
  73996. * Sets the given "parameter" matrix
  73997. * @param scene: the {BABYLON.Scene} object
  73998. * @param source: the source node where to pick the matrix
  73999. * @param parameter: the GLTF technique parameter
  74000. * @param uniformName: the name of the shader's uniform
  74001. * @param shaderMaterial: the shader material
  74002. */
  74003. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  74004. var mat = null;
  74005. if (parameter.semantic === "MODEL") {
  74006. mat = source.getWorldMatrix();
  74007. }
  74008. else if (parameter.semantic === "PROJECTION") {
  74009. mat = scene.getProjectionMatrix();
  74010. }
  74011. else if (parameter.semantic === "VIEW") {
  74012. mat = scene.getViewMatrix();
  74013. }
  74014. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  74015. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  74016. }
  74017. else if (parameter.semantic === "MODELVIEW") {
  74018. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  74019. }
  74020. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  74021. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  74022. }
  74023. else if (parameter.semantic === "MODELINVERSE") {
  74024. mat = source.getWorldMatrix().invert();
  74025. }
  74026. else if (parameter.semantic === "VIEWINVERSE") {
  74027. mat = scene.getViewMatrix().invert();
  74028. }
  74029. else if (parameter.semantic === "PROJECTIONINVERSE") {
  74030. mat = scene.getProjectionMatrix().invert();
  74031. }
  74032. else if (parameter.semantic === "MODELVIEWINVERSE") {
  74033. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  74034. }
  74035. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  74036. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  74037. }
  74038. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  74039. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  74040. }
  74041. else {
  74042. debugger;
  74043. }
  74044. switch (parameter.type) {
  74045. case GLTF1.EParameterType.FLOAT_MAT2:
  74046. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  74047. break;
  74048. case GLTF1.EParameterType.FLOAT_MAT3:
  74049. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  74050. break;
  74051. case GLTF1.EParameterType.FLOAT_MAT4:
  74052. shaderMaterial.setMatrix(uniformName, mat);
  74053. break;
  74054. default: break;
  74055. }
  74056. };
  74057. /**
  74058. * Sets the given "parameter" matrix
  74059. * @param shaderMaterial: the shader material
  74060. * @param uniform: the name of the shader's uniform
  74061. * @param value: the value of the uniform
  74062. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  74063. */
  74064. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  74065. switch (type) {
  74066. case GLTF1.EParameterType.FLOAT:
  74067. shaderMaterial.setFloat(uniform, value);
  74068. return true;
  74069. case GLTF1.EParameterType.FLOAT_VEC2:
  74070. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  74071. return true;
  74072. case GLTF1.EParameterType.FLOAT_VEC3:
  74073. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  74074. return true;
  74075. case GLTF1.EParameterType.FLOAT_VEC4:
  74076. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  74077. return true;
  74078. default: return false;
  74079. }
  74080. };
  74081. /**
  74082. * If the uri is a base64 string
  74083. * @param uri: the uri to test
  74084. */
  74085. GLTFUtils.IsBase64 = function (uri) {
  74086. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  74087. };
  74088. /**
  74089. * Decode the base64 uri
  74090. * @param uri: the uri to decode
  74091. */
  74092. GLTFUtils.DecodeBase64 = function (uri) {
  74093. var decodedString = atob(uri.split(",")[1]);
  74094. var bufferLength = decodedString.length;
  74095. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  74096. for (var i = 0; i < bufferLength; i++) {
  74097. bufferView[i] = decodedString.charCodeAt(i);
  74098. }
  74099. return bufferView.buffer;
  74100. };
  74101. /**
  74102. * Returns the wrap mode of the texture
  74103. * @param mode: the mode value
  74104. */
  74105. GLTFUtils.GetWrapMode = function (mode) {
  74106. switch (mode) {
  74107. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  74108. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  74109. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  74110. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  74111. }
  74112. };
  74113. /**
  74114. * Returns the byte stride giving an accessor
  74115. * @param accessor: the GLTF accessor objet
  74116. */
  74117. GLTFUtils.GetByteStrideFromType = function (accessor) {
  74118. // Needs this function since "byteStride" isn't requiered in glTF format
  74119. var type = accessor.type;
  74120. switch (type) {
  74121. case "VEC2": return 2;
  74122. case "VEC3": return 3;
  74123. case "VEC4": return 4;
  74124. case "MAT2": return 4;
  74125. case "MAT3": return 9;
  74126. case "MAT4": return 16;
  74127. default: return 1;
  74128. }
  74129. };
  74130. /**
  74131. * Returns the texture filter mode giving a mode value
  74132. * @param mode: the filter mode value
  74133. */
  74134. GLTFUtils.GetTextureFilterMode = function (mode) {
  74135. switch (mode) {
  74136. case GLTF1.ETextureFilterType.LINEAR:
  74137. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  74138. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  74139. case GLTF1.ETextureFilterType.NEAREST:
  74140. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  74141. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  74142. }
  74143. };
  74144. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  74145. var byteOffset = bufferView.byteOffset + byteOffset;
  74146. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  74147. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  74148. throw new Error("Buffer access is out of range");
  74149. }
  74150. var buffer = loadedBufferView.buffer;
  74151. byteOffset += loadedBufferView.byteOffset;
  74152. switch (componentType) {
  74153. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  74154. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  74155. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  74156. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  74157. default: return new Float32Array(buffer, byteOffset, byteLength);
  74158. }
  74159. };
  74160. /**
  74161. * Returns a buffer from its accessor
  74162. * @param gltfRuntime: the GLTF runtime
  74163. * @param accessor: the GLTF accessor
  74164. */
  74165. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  74166. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  74167. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  74168. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  74169. };
  74170. /**
  74171. * Decodes a buffer view into a string
  74172. * @param view: the buffer view
  74173. */
  74174. GLTFUtils.DecodeBufferToText = function (view) {
  74175. var result = "";
  74176. var length = view.byteLength;
  74177. for (var i = 0; i < length; ++i) {
  74178. result += String.fromCharCode(view[i]);
  74179. }
  74180. return result;
  74181. };
  74182. /**
  74183. * Returns the default material of gltf. Related to
  74184. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  74185. * @param scene: the Babylon.js scene
  74186. */
  74187. GLTFUtils.GetDefaultMaterial = function (scene) {
  74188. if (!GLTFUtils._DefaultMaterial) {
  74189. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  74190. "precision highp float;",
  74191. "",
  74192. "uniform mat4 worldView;",
  74193. "uniform mat4 projection;",
  74194. "",
  74195. "attribute vec3 position;",
  74196. "",
  74197. "void main(void)",
  74198. "{",
  74199. " gl_Position = projection * worldView * vec4(position, 1.0);",
  74200. "}"
  74201. ].join("\n");
  74202. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  74203. "precision highp float;",
  74204. "",
  74205. "uniform vec4 u_emission;",
  74206. "",
  74207. "void main(void)",
  74208. "{",
  74209. " gl_FragColor = u_emission;",
  74210. "}"
  74211. ].join("\n");
  74212. var shaderPath = {
  74213. vertex: "GLTFDefaultMaterial",
  74214. fragment: "GLTFDefaultMaterial"
  74215. };
  74216. var options = {
  74217. attributes: ["position"],
  74218. uniforms: ["worldView", "projection", "u_emission"],
  74219. samplers: [],
  74220. needAlphaBlending: false
  74221. };
  74222. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  74223. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  74224. }
  74225. return GLTFUtils._DefaultMaterial;
  74226. };
  74227. // The GLTF default material
  74228. GLTFUtils._DefaultMaterial = null;
  74229. return GLTFUtils;
  74230. }());
  74231. GLTF1.GLTFUtils = GLTFUtils;
  74232. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74233. })(BABYLON || (BABYLON = {}));
  74234. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  74235. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74236. var BABYLON;
  74237. (function (BABYLON) {
  74238. var GLTF1;
  74239. (function (GLTF1) {
  74240. var GLTFLoaderExtension = (function () {
  74241. function GLTFLoaderExtension(name) {
  74242. this._name = name;
  74243. }
  74244. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  74245. get: function () {
  74246. return this._name;
  74247. },
  74248. enumerable: true,
  74249. configurable: true
  74250. });
  74251. /**
  74252. * Defines an override for loading the runtime
  74253. * Return true to stop further extensions from loading the runtime
  74254. */
  74255. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74256. return false;
  74257. };
  74258. /**
  74259. * Defines an onverride for creating gltf runtime
  74260. * Return true to stop further extensions from creating the runtime
  74261. */
  74262. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74263. return false;
  74264. };
  74265. /**
  74266. * Defines an override for loading buffers
  74267. * Return true to stop further extensions from loading this buffer
  74268. */
  74269. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74270. return false;
  74271. };
  74272. /**
  74273. * Defines an override for loading texture buffers
  74274. * Return true to stop further extensions from loading this texture data
  74275. */
  74276. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74277. return false;
  74278. };
  74279. /**
  74280. * Defines an override for creating textures
  74281. * Return true to stop further extensions from loading this texture
  74282. */
  74283. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74284. return false;
  74285. };
  74286. /**
  74287. * Defines an override for loading shader strings
  74288. * Return true to stop further extensions from loading this shader data
  74289. */
  74290. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74291. return false;
  74292. };
  74293. /**
  74294. * Defines an override for loading materials
  74295. * Return true to stop further extensions from loading this material
  74296. */
  74297. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74298. return false;
  74299. };
  74300. // ---------
  74301. // Utilities
  74302. // ---------
  74303. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74304. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74305. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  74306. }, function () {
  74307. setTimeout(function () {
  74308. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  74309. });
  74310. });
  74311. };
  74312. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74313. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74314. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  74315. }, function () {
  74316. setTimeout(function () {
  74317. onSuccess();
  74318. });
  74319. });
  74320. };
  74321. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74322. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74323. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  74324. }, function () {
  74325. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  74326. });
  74327. };
  74328. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  74329. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  74330. };
  74331. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74332. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74333. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  74334. }, function () {
  74335. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  74336. });
  74337. };
  74338. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74339. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74340. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  74341. }, function () {
  74342. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  74343. });
  74344. };
  74345. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74346. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74347. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  74348. }, function () {
  74349. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  74350. });
  74351. };
  74352. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74353. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74354. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  74355. }, function () {
  74356. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  74357. });
  74358. };
  74359. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  74360. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  74361. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  74362. if (func(loaderExtension)) {
  74363. return;
  74364. }
  74365. }
  74366. defaultFunc();
  74367. };
  74368. return GLTFLoaderExtension;
  74369. }());
  74370. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  74371. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74372. })(BABYLON || (BABYLON = {}));
  74373. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  74374. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74375. var BABYLON;
  74376. (function (BABYLON) {
  74377. var GLTF1;
  74378. (function (GLTF1) {
  74379. var BinaryExtensionBufferName = "binary_glTF";
  74380. var EContentFormat;
  74381. (function (EContentFormat) {
  74382. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  74383. })(EContentFormat || (EContentFormat = {}));
  74384. ;
  74385. ;
  74386. ;
  74387. var GLTFBinaryExtension = (function (_super) {
  74388. __extends(GLTFBinaryExtension, _super);
  74389. function GLTFBinaryExtension() {
  74390. return _super.call(this, "KHR_binary_glTF") || this;
  74391. }
  74392. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74393. var extensionsUsed = data.json.extensionsUsed;
  74394. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  74395. return false;
  74396. }
  74397. this._bin = data.bin;
  74398. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  74399. return true;
  74400. };
  74401. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74402. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  74403. return false;
  74404. }
  74405. if (id !== BinaryExtensionBufferName) {
  74406. return false;
  74407. }
  74408. onSuccess(this._bin);
  74409. return true;
  74410. };
  74411. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74412. var texture = gltfRuntime.textures[id];
  74413. var source = gltfRuntime.images[texture.source];
  74414. if (!source.extensions || !(this.name in source.extensions)) {
  74415. return false;
  74416. }
  74417. var sourceExt = source.extensions[this.name];
  74418. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  74419. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  74420. onSuccess(buffer);
  74421. return true;
  74422. };
  74423. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74424. var shader = gltfRuntime.shaders[id];
  74425. if (!shader.extensions || !(this.name in shader.extensions)) {
  74426. return false;
  74427. }
  74428. var binaryExtensionShader = shader.extensions[this.name];
  74429. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  74430. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  74431. setTimeout(function () {
  74432. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  74433. onSuccess(shaderString);
  74434. });
  74435. return true;
  74436. };
  74437. return GLTFBinaryExtension;
  74438. }(GLTF1.GLTFLoaderExtension));
  74439. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  74440. var BinaryReader = (function () {
  74441. function BinaryReader(arrayBuffer) {
  74442. this._arrayBuffer = arrayBuffer;
  74443. this._dataView = new DataView(arrayBuffer);
  74444. this._byteOffset = 0;
  74445. }
  74446. BinaryReader.prototype.getUint32 = function () {
  74447. var value = this._dataView.getUint32(this._byteOffset, true);
  74448. this._byteOffset += 4;
  74449. return value;
  74450. };
  74451. BinaryReader.prototype.getUint8Array = function (length) {
  74452. if (!length) {
  74453. length = this._arrayBuffer.byteLength - this._byteOffset;
  74454. }
  74455. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  74456. this._byteOffset += length;
  74457. return value;
  74458. };
  74459. return BinaryReader;
  74460. }());
  74461. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  74462. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74463. })(BABYLON || (BABYLON = {}));
  74464. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  74465. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74466. var BABYLON;
  74467. (function (BABYLON) {
  74468. var GLTF1;
  74469. (function (GLTF1) {
  74470. ;
  74471. ;
  74472. ;
  74473. var GLTFMaterialsCommonExtension = (function (_super) {
  74474. __extends(GLTFMaterialsCommonExtension, _super);
  74475. function GLTFMaterialsCommonExtension() {
  74476. return _super.call(this, "KHR_materials_common") || this;
  74477. }
  74478. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74479. if (!gltfRuntime.extensions)
  74480. return false;
  74481. var extension = gltfRuntime.extensions[this.name];
  74482. if (!extension)
  74483. return false;
  74484. // Create lights
  74485. var lights = extension.lights;
  74486. if (lights) {
  74487. for (var thing in lights) {
  74488. var light = lights[thing];
  74489. switch (light.type) {
  74490. case "ambient":
  74491. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  74492. var ambient = light.ambient;
  74493. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  74494. break;
  74495. case "point":
  74496. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  74497. var point = light.point;
  74498. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  74499. break;
  74500. case "directional":
  74501. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  74502. var directional = light.directional;
  74503. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  74504. break;
  74505. case "spot":
  74506. var spot = light.spot;
  74507. 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);
  74508. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  74509. break;
  74510. default:
  74511. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  74512. break;
  74513. }
  74514. }
  74515. }
  74516. return false;
  74517. };
  74518. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74519. var material = gltfRuntime.materials[id];
  74520. if (!material || !material.extensions)
  74521. return false;
  74522. var extension = material.extensions[this.name];
  74523. if (!extension)
  74524. return false;
  74525. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  74526. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74527. if (extension.technique === "CONSTANT") {
  74528. standardMaterial.disableLighting = true;
  74529. }
  74530. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  74531. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  74532. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  74533. // Ambient
  74534. if (typeof extension.values.ambient === "string") {
  74535. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  74536. }
  74537. else {
  74538. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  74539. }
  74540. // Diffuse
  74541. if (typeof extension.values.diffuse === "string") {
  74542. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  74543. }
  74544. else {
  74545. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  74546. }
  74547. // Emission
  74548. if (typeof extension.values.emission === "string") {
  74549. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  74550. }
  74551. else {
  74552. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  74553. }
  74554. // Specular
  74555. if (typeof extension.values.specular === "string") {
  74556. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  74557. }
  74558. else {
  74559. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  74560. }
  74561. return true;
  74562. };
  74563. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  74564. // Create buffer from texture url
  74565. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  74566. // Create texture from buffer
  74567. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  74568. }, onError);
  74569. };
  74570. return GLTFMaterialsCommonExtension;
  74571. }(GLTF1.GLTFLoaderExtension));
  74572. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  74573. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  74574. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74575. })(BABYLON || (BABYLON = {}));
  74576. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  74577. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74578. var BABYLON;
  74579. (function (BABYLON) {
  74580. var GLTF2;
  74581. (function (GLTF2) {
  74582. /**
  74583. * Enums
  74584. */
  74585. var EComponentType;
  74586. (function (EComponentType) {
  74587. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  74588. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  74589. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  74590. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  74591. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  74592. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  74593. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  74594. var EMeshPrimitiveMode;
  74595. (function (EMeshPrimitiveMode) {
  74596. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  74597. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  74598. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  74599. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  74600. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  74601. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  74602. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  74603. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  74604. var ETextureMagFilter;
  74605. (function (ETextureMagFilter) {
  74606. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  74607. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  74608. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  74609. var ETextureMinFilter;
  74610. (function (ETextureMinFilter) {
  74611. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  74612. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  74613. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  74614. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  74615. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  74616. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  74617. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  74618. var ETextureWrapMode;
  74619. (function (ETextureWrapMode) {
  74620. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  74621. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  74622. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  74623. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  74624. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  74625. })(BABYLON || (BABYLON = {}));
  74626. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  74627. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74628. var BABYLON;
  74629. (function (BABYLON) {
  74630. var GLTF2;
  74631. (function (GLTF2) {
  74632. var GLTFLoader = (function () {
  74633. function GLTFLoader(parent) {
  74634. this._renderReady = false;
  74635. this._disposed = false;
  74636. this._blockPendingTracking = false;
  74637. // Observable with boolean indicating success or error.
  74638. this._renderReadyObservable = new BABYLON.Observable();
  74639. // Count of pending work that needs to complete before the asset is rendered.
  74640. this._renderPendingCount = 0;
  74641. // Count of pending work that needs to complete before the loader is cleared.
  74642. this._loaderPendingCount = 0;
  74643. this._parent = parent;
  74644. }
  74645. GLTFLoader.RegisterExtension = function (extension) {
  74646. if (GLTFLoader.Extensions[extension.name]) {
  74647. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  74648. return;
  74649. }
  74650. GLTFLoader.Extensions[extension.name] = extension;
  74651. // Keep the order of registration so that extensions registered first are called first.
  74652. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  74653. };
  74654. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  74655. get: function () {
  74656. return this._gltf;
  74657. },
  74658. enumerable: true,
  74659. configurable: true
  74660. });
  74661. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  74662. get: function () {
  74663. return this._babylonScene;
  74664. },
  74665. enumerable: true,
  74666. configurable: true
  74667. });
  74668. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  74669. if (this._renderReady) {
  74670. func();
  74671. }
  74672. else {
  74673. this._renderReadyObservable.add(func);
  74674. }
  74675. };
  74676. GLTFLoader.prototype.dispose = function () {
  74677. if (this._disposed) {
  74678. return;
  74679. }
  74680. this._disposed = true;
  74681. // Revoke object urls created during load
  74682. if (this._gltf.textures) {
  74683. this._gltf.textures.forEach(function (texture) {
  74684. if (texture.url) {
  74685. URL.revokeObjectURL(texture.url);
  74686. }
  74687. });
  74688. }
  74689. this._gltf = undefined;
  74690. this._babylonScene = undefined;
  74691. this._rootUrl = undefined;
  74692. this._defaultMaterial = undefined;
  74693. this._successCallback = undefined;
  74694. this._errorCallback = undefined;
  74695. this._renderReady = false;
  74696. this._renderReadyObservable.clear();
  74697. this._renderPendingCount = 0;
  74698. this._loaderPendingCount = 0;
  74699. };
  74700. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  74701. var _this = this;
  74702. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  74703. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  74704. }, onProgress, onError);
  74705. };
  74706. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  74707. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  74708. };
  74709. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  74710. this._loadData(data);
  74711. this._babylonScene = scene;
  74712. this._rootUrl = rootUrl;
  74713. this._successCallback = onSuccess;
  74714. this._progressCallback = onProgress;
  74715. this._errorCallback = onError;
  74716. this.addPendingData(this);
  74717. this._loadScene(nodeNames);
  74718. this._loadAnimations();
  74719. this.removePendingData(this);
  74720. };
  74721. GLTFLoader.prototype._onError = function (message) {
  74722. this._errorCallback(message);
  74723. this.dispose();
  74724. };
  74725. GLTFLoader.prototype._onProgress = function (event) {
  74726. this._progressCallback(event);
  74727. };
  74728. GLTFLoader.prototype._onRenderReady = function () {
  74729. switch (this._parent.coordinateSystemMode) {
  74730. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  74731. if (!this._babylonScene.useRightHandedSystem) {
  74732. this._addRightHandToLeftHandRootTransform();
  74733. }
  74734. break;
  74735. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  74736. // do nothing
  74737. break;
  74738. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  74739. this._babylonScene.useRightHandedSystem = true;
  74740. break;
  74741. default:
  74742. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  74743. break;
  74744. }
  74745. this._showMeshes();
  74746. this._startAnimations();
  74747. this._successCallback();
  74748. this._renderReadyObservable.notifyObservers(this);
  74749. };
  74750. GLTFLoader.prototype._onLoaderComplete = function () {
  74751. if (this._parent.onComplete) {
  74752. this._parent.onComplete();
  74753. }
  74754. };
  74755. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  74756. if (this._parent.onFirstLODComplete) {
  74757. this._parent.onFirstLODComplete();
  74758. }
  74759. };
  74760. GLTFLoader.prototype._loadData = function (data) {
  74761. this._gltf = data.json;
  74762. var binaryBuffer;
  74763. var buffers = this._gltf.buffers;
  74764. if (buffers && buffers[0].uri === undefined) {
  74765. binaryBuffer = buffers[0];
  74766. }
  74767. if (data.bin) {
  74768. if (binaryBuffer) {
  74769. if (binaryBuffer.byteLength != data.bin.byteLength) {
  74770. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  74771. }
  74772. }
  74773. else {
  74774. BABYLON.Tools.Warn("Unexpected BIN chunk");
  74775. }
  74776. binaryBuffer.loadedData = data.bin;
  74777. }
  74778. };
  74779. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  74780. this._rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  74781. this._rootMesh.isVisible = false;
  74782. this._rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  74783. this._rootMesh.rotation.y = Math.PI;
  74784. var nodes = this._gltf.nodes;
  74785. if (nodes) {
  74786. for (var i = 0; i < nodes.length; i++) {
  74787. var mesh = nodes[i].babylonMesh;
  74788. if (mesh && !mesh.parent) {
  74789. mesh.parent = this._rootMesh;
  74790. }
  74791. }
  74792. }
  74793. };
  74794. GLTFLoader.prototype._getMeshes = function () {
  74795. var meshes = [];
  74796. if (this._rootMesh) {
  74797. meshes.push(this._rootMesh);
  74798. }
  74799. var nodes = this._gltf.nodes;
  74800. if (nodes) {
  74801. nodes.forEach(function (node) {
  74802. if (node.babylonMesh) {
  74803. meshes.push(node.babylonMesh);
  74804. }
  74805. });
  74806. }
  74807. return meshes;
  74808. };
  74809. GLTFLoader.prototype._getSkeletons = function () {
  74810. var skeletons = [];
  74811. var skins = this._gltf.skins;
  74812. if (skins) {
  74813. skins.forEach(function (skin) {
  74814. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  74815. skeletons.push(skin.babylonSkeleton);
  74816. }
  74817. });
  74818. }
  74819. return skeletons;
  74820. };
  74821. GLTFLoader.prototype._getAnimationTargets = function () {
  74822. var targets = [];
  74823. var animations = this._gltf.animations;
  74824. if (animations) {
  74825. animations.forEach(function (animation) {
  74826. targets.push.apply(targets, animation.targets);
  74827. });
  74828. }
  74829. return targets;
  74830. };
  74831. GLTFLoader.prototype._showMeshes = function () {
  74832. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  74833. };
  74834. GLTFLoader.prototype._startAnimations = function () {
  74835. var _this = this;
  74836. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  74837. };
  74838. GLTFLoader.prototype._loadScene = function (nodeNames) {
  74839. var _this = this;
  74840. var scene = this._gltf.scenes[this._gltf.scene || 0];
  74841. var nodeIndices = scene.nodes;
  74842. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  74843. node.index = index;
  74844. node.parent = parentNode;
  74845. return true;
  74846. });
  74847. var materials = this._gltf.materials;
  74848. if (materials) {
  74849. materials.forEach(function (material, index) { return material.index = index; });
  74850. }
  74851. if (nodeNames) {
  74852. if (!(nodeNames instanceof Array)) {
  74853. nodeNames = [nodeNames];
  74854. }
  74855. var filteredNodeIndices = new Array();
  74856. this._traverseNodes(nodeIndices, function (node) {
  74857. if (nodeNames.indexOf(node.name) === -1) {
  74858. return true;
  74859. }
  74860. filteredNodeIndices.push(node.index);
  74861. return false;
  74862. });
  74863. nodeIndices = filteredNodeIndices;
  74864. }
  74865. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  74866. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  74867. };
  74868. GLTFLoader.prototype._loadSkin = function (node) {
  74869. var _this = this;
  74870. if (node.skin !== undefined) {
  74871. var skin = this._gltf.skins[node.skin];
  74872. var skeletonId = "skeleton" + node.skin;
  74873. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  74874. skin.index = node.skin;
  74875. for (var i = 0; i < skin.joints.length; i++) {
  74876. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  74877. }
  74878. if (skin.skeleton === undefined) {
  74879. // TODO: handle when skeleton is not defined
  74880. throw new Error("Not implemented");
  74881. }
  74882. if (skin.inverseBindMatrices === undefined) {
  74883. // TODO: handle when inverse bind matrices are not defined
  74884. throw new Error("Not implemented");
  74885. }
  74886. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  74887. this._loadAccessorAsync(accessor, function (data) {
  74888. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  74889. });
  74890. }
  74891. return true;
  74892. };
  74893. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  74894. var jointIndex = skin.joints.indexOf(node.index);
  74895. if (jointIndex === -1) {
  74896. this._createBone(node, skin);
  74897. }
  74898. var babylonBone = node.babylonSkinToBones[skin.index];
  74899. // TODO: explain the math
  74900. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  74901. matrix.invertToRef(matrix);
  74902. if (parentNode) {
  74903. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  74904. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  74905. }
  74906. babylonBone.updateMatrix(matrix);
  74907. return true;
  74908. };
  74909. GLTFLoader.prototype._createBone = function (node, skin) {
  74910. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  74911. node.babylonSkinToBones = node.babylonSkinToBones || {};
  74912. node.babylonSkinToBones[skin.index] = babylonBone;
  74913. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  74914. node.babylonAnimationTargets.push(babylonBone);
  74915. return babylonBone;
  74916. };
  74917. GLTFLoader.prototype._loadMesh = function (node) {
  74918. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  74919. babylonMesh.isVisible = false;
  74920. this._loadTransform(node, babylonMesh);
  74921. if (node.mesh !== undefined) {
  74922. var mesh = this._gltf.meshes[node.mesh];
  74923. this._loadMeshData(node, mesh, babylonMesh);
  74924. }
  74925. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  74926. node.babylonMesh = babylonMesh;
  74927. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  74928. node.babylonAnimationTargets.push(node.babylonMesh);
  74929. if (node.skin !== undefined) {
  74930. var skin = this._gltf.skins[node.skin];
  74931. babylonMesh.skeleton = skin.babylonSkeleton;
  74932. }
  74933. if (node.camera !== undefined) {
  74934. // TODO: handle cameras
  74935. }
  74936. return true;
  74937. };
  74938. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  74939. var _this = this;
  74940. babylonMesh.name = mesh.name || babylonMesh.name;
  74941. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  74942. babylonMesh.material = babylonMultiMaterial;
  74943. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  74944. var vertexData = new BABYLON.VertexData();
  74945. vertexData.positions = [];
  74946. vertexData.indices = [];
  74947. var subMeshInfos = [];
  74948. var loadedPrimitives = 0;
  74949. var totalPrimitives = mesh.primitives.length;
  74950. var _loop_1 = function (i) {
  74951. var primitive = mesh.primitives[i];
  74952. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  74953. // TODO: handle other primitive modes
  74954. throw new Error("Not implemented");
  74955. }
  74956. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  74957. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  74958. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  74959. subMeshInfos.push({
  74960. materialIndex: i,
  74961. verticesStart: vertexData.positions.length,
  74962. verticesCount: subVertexData.positions.length,
  74963. indicesStart: vertexData.indices.length,
  74964. indicesCount: subVertexData.indices.length,
  74965. loadMaterial: function () {
  74966. if (primitive.material === undefined) {
  74967. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  74968. }
  74969. else {
  74970. var material = _this._gltf.materials[primitive.material];
  74971. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  74972. if (isNew && _this._parent.onMaterialLoaded) {
  74973. _this._parent.onMaterialLoaded(babylonMaterial);
  74974. }
  74975. if (_this._parent.onBeforeMaterialReadyAsync) {
  74976. _this.addLoaderPendingData(material);
  74977. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  74978. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  74979. _this.removeLoaderPendingData(material);
  74980. });
  74981. }
  74982. else {
  74983. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  74984. }
  74985. });
  74986. }
  74987. }
  74988. });
  74989. vertexData.merge(subVertexData);
  74990. if (++loadedPrimitives === totalPrimitives) {
  74991. geometry.setAllVerticesData(vertexData, false);
  74992. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  74993. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  74994. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  74995. babylonMesh.subMeshes = [];
  74996. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  74997. }
  74998. });
  74999. };
  75000. var this_1 = this;
  75001. for (var i = 0; i < totalPrimitives; i++) {
  75002. _loop_1(i);
  75003. }
  75004. };
  75005. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  75006. var _this = this;
  75007. var attributes = primitive.attributes;
  75008. if (!attributes) {
  75009. this._onError("Primitive has no attributes");
  75010. return;
  75011. }
  75012. var vertexData = new BABYLON.VertexData();
  75013. var loadedAttributes = 0;
  75014. var totalAttributes = Object.keys(attributes).length;
  75015. var _loop_2 = function (semantic) {
  75016. accessor = this_2._gltf.accessors[attributes[semantic]];
  75017. this_2._loadAccessorAsync(accessor, function (data) {
  75018. switch (semantic) {
  75019. case "NORMAL":
  75020. vertexData.normals = data;
  75021. break;
  75022. case "POSITION":
  75023. vertexData.positions = data;
  75024. break;
  75025. case "TANGENT":
  75026. vertexData.tangents = data;
  75027. break;
  75028. case "TEXCOORD_0":
  75029. vertexData.uvs = data;
  75030. break;
  75031. case "TEXCOORD_1":
  75032. vertexData.uvs2 = data;
  75033. break;
  75034. case "JOINTS_0":
  75035. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  75036. break;
  75037. case "WEIGHTS_0":
  75038. vertexData.matricesWeights = data;
  75039. break;
  75040. case "COLOR_0":
  75041. vertexData.colors = data;
  75042. break;
  75043. default:
  75044. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  75045. break;
  75046. }
  75047. if (++loadedAttributes === totalAttributes) {
  75048. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  75049. if (indicesAccessor) {
  75050. _this._loadAccessorAsync(indicesAccessor, function (data) {
  75051. vertexData.indices = data;
  75052. onSuccess(vertexData);
  75053. });
  75054. }
  75055. else {
  75056. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  75057. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  75058. onSuccess(vertexData);
  75059. }
  75060. }
  75061. });
  75062. };
  75063. var this_2 = this, accessor;
  75064. for (var semantic in attributes) {
  75065. _loop_2(semantic);
  75066. }
  75067. };
  75068. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  75069. var targets = primitive.targets;
  75070. if (!targets) {
  75071. return;
  75072. }
  75073. if (!babylonMesh.morphTargetManager) {
  75074. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  75075. }
  75076. for (var index = 0; index < targets.length; index++) {
  75077. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  75078. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  75079. }
  75080. };
  75081. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  75082. var targets = primitive.targets;
  75083. if (!targets) {
  75084. return;
  75085. }
  75086. var _loop_3 = function () {
  75087. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  75088. attributes = targets[index];
  75089. var _loop_4 = function (semantic) {
  75090. accessor = this_3._gltf.accessors[attributes[semantic]];
  75091. this_3._loadAccessorAsync(accessor, function (data) {
  75092. if (accessor.name) {
  75093. babylonMorphTarget.name = accessor.name;
  75094. }
  75095. // glTF stores morph target information as deltas while babylon.js expects the final data.
  75096. // As a result we have to add the original data to the delta to calculate the final data.
  75097. var values = data;
  75098. switch (semantic) {
  75099. case "NORMAL":
  75100. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  75101. babylonMorphTarget.setNormals(values);
  75102. break;
  75103. case "POSITION":
  75104. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  75105. babylonMorphTarget.setPositions(values);
  75106. break;
  75107. case "TANGENT":
  75108. // Tangent data for morph targets is stored as xyz delta.
  75109. // The vertexData.tangent is stored as xyzw.
  75110. // So we need to skip every fourth vertexData.tangent.
  75111. for (var i = 0, j = 0; i < values.length; i++, j++) {
  75112. values[i] += vertexData.tangents[j];
  75113. if ((i + 1) % 3 == 0) {
  75114. j++;
  75115. }
  75116. }
  75117. babylonMorphTarget.setTangents(values);
  75118. break;
  75119. default:
  75120. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  75121. break;
  75122. }
  75123. });
  75124. };
  75125. for (var semantic in attributes) {
  75126. _loop_4(semantic);
  75127. }
  75128. };
  75129. var this_3 = this, attributes, accessor;
  75130. for (var index = 0; index < targets.length; index++) {
  75131. _loop_3();
  75132. }
  75133. };
  75134. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  75135. var position = BABYLON.Vector3.Zero();
  75136. var rotation = BABYLON.Quaternion.Identity();
  75137. var scaling = BABYLON.Vector3.One();
  75138. if (node.matrix) {
  75139. var mat = BABYLON.Matrix.FromArray(node.matrix);
  75140. mat.decompose(scaling, rotation, position);
  75141. }
  75142. else {
  75143. if (node.translation)
  75144. position = BABYLON.Vector3.FromArray(node.translation);
  75145. if (node.rotation)
  75146. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  75147. if (node.scale)
  75148. scaling = BABYLON.Vector3.FromArray(node.scale);
  75149. }
  75150. babylonMesh.position = position;
  75151. babylonMesh.rotationQuaternion = rotation;
  75152. babylonMesh.scaling = scaling;
  75153. };
  75154. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  75155. if (parentNode === void 0) { parentNode = null; }
  75156. for (var i = 0; i < indices.length; i++) {
  75157. this._traverseNode(indices[i], action, parentNode);
  75158. }
  75159. };
  75160. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  75161. if (parentNode === void 0) { parentNode = null; }
  75162. var node = this._gltf.nodes[index];
  75163. if (!action(node, index, parentNode)) {
  75164. return;
  75165. }
  75166. if (node.children) {
  75167. for (var i = 0; i < node.children.length; i++) {
  75168. this._traverseNode(node.children[i], action, node);
  75169. }
  75170. }
  75171. };
  75172. GLTFLoader.prototype._loadAnimations = function () {
  75173. var animations = this._gltf.animations;
  75174. if (!animations || animations.length === 0) {
  75175. return;
  75176. }
  75177. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  75178. var animation = animations[animationIndex];
  75179. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  75180. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  75181. }
  75182. }
  75183. };
  75184. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  75185. var channel = animation.channels[channelIndex];
  75186. var samplerIndex = channel.sampler;
  75187. var sampler = animation.samplers[samplerIndex];
  75188. var targetNode = this._gltf.nodes[channel.target.node];
  75189. if (!targetNode) {
  75190. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  75191. return;
  75192. }
  75193. var targetPath = {
  75194. "translation": "position",
  75195. "rotation": "rotationQuaternion",
  75196. "scale": "scaling",
  75197. "weights": "influence"
  75198. }[channel.target.path];
  75199. if (!targetPath) {
  75200. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  75201. return;
  75202. }
  75203. var animationType = {
  75204. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  75205. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  75206. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  75207. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  75208. }[targetPath];
  75209. var inputData;
  75210. var outputData;
  75211. var checkSuccess = function () {
  75212. if (!inputData || !outputData) {
  75213. return;
  75214. }
  75215. var outputBufferOffset = 0;
  75216. var getNextOutputValue = {
  75217. "position": function () {
  75218. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  75219. outputBufferOffset += 3;
  75220. return value;
  75221. },
  75222. "rotationQuaternion": function () {
  75223. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  75224. outputBufferOffset += 4;
  75225. return value;
  75226. },
  75227. "scaling": function () {
  75228. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  75229. outputBufferOffset += 3;
  75230. return value;
  75231. },
  75232. "influence": function () {
  75233. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  75234. var value = new Array(numTargets);
  75235. for (var i = 0; i < numTargets; i++) {
  75236. value[i] = outputData[outputBufferOffset++];
  75237. }
  75238. return value;
  75239. },
  75240. }[targetPath];
  75241. var getNextKey = {
  75242. "LINEAR": function (frameIndex) { return ({
  75243. frame: inputData[frameIndex],
  75244. value: getNextOutputValue()
  75245. }); },
  75246. "CUBICSPLINE": function (frameIndex) { return ({
  75247. frame: inputData[frameIndex],
  75248. inTangent: getNextOutputValue(),
  75249. value: getNextOutputValue(),
  75250. outTangent: getNextOutputValue()
  75251. }); },
  75252. }[sampler.interpolation];
  75253. var keys = new Array(inputData.length);
  75254. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  75255. keys[frameIndex] = getNextKey(frameIndex);
  75256. }
  75257. animation.targets = animation.targets || [];
  75258. if (targetPath === "influence") {
  75259. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  75260. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  75261. var morphTarget = morphTargetManager.getTarget(targetIndex);
  75262. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  75263. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  75264. babylonAnimation.setKeys(keys.map(function (key) { return ({
  75265. frame: key.frame,
  75266. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  75267. value: key.value[targetIndex],
  75268. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  75269. }); }));
  75270. morphTarget.animations.push(babylonAnimation);
  75271. animation.targets.push(morphTarget);
  75272. }
  75273. }
  75274. else {
  75275. var animationName = animation.name || "anim" + animationIndex;
  75276. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  75277. babylonAnimation.setKeys(keys);
  75278. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  75279. var target = targetNode.babylonAnimationTargets[i];
  75280. target.animations.push(babylonAnimation.clone());
  75281. animation.targets.push(target);
  75282. }
  75283. }
  75284. };
  75285. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  75286. inputData = data;
  75287. checkSuccess();
  75288. });
  75289. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  75290. outputData = data;
  75291. checkSuccess();
  75292. });
  75293. };
  75294. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  75295. var _this = this;
  75296. var buffer = this._gltf.buffers[index];
  75297. this.addPendingData(buffer);
  75298. if (buffer.loadedData) {
  75299. setTimeout(function () {
  75300. onSuccess(buffer.loadedData);
  75301. _this.removePendingData(buffer);
  75302. });
  75303. }
  75304. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  75305. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  75306. buffer.loadedData = new Uint8Array(data);
  75307. setTimeout(function () {
  75308. onSuccess(buffer.loadedData);
  75309. _this.removePendingData(buffer);
  75310. });
  75311. }
  75312. else if (buffer.loadedObservable) {
  75313. buffer.loadedObservable.add(function (buffer) {
  75314. onSuccess(buffer.loadedData);
  75315. _this.removePendingData(buffer);
  75316. });
  75317. }
  75318. else {
  75319. buffer.loadedObservable = new BABYLON.Observable();
  75320. buffer.loadedObservable.add(function (buffer) {
  75321. onSuccess(buffer.loadedData);
  75322. _this.removePendingData(buffer);
  75323. });
  75324. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  75325. buffer.loadedData = new Uint8Array(data);
  75326. buffer.loadedObservable.notifyObservers(buffer);
  75327. buffer.loadedObservable = null;
  75328. }, function (event) {
  75329. if (!_this._disposed) {
  75330. _this._onProgress(event);
  75331. }
  75332. }, this._babylonScene.database, true, function (request) {
  75333. if (!_this._disposed) {
  75334. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  75335. _this.removePendingData(buffer);
  75336. }
  75337. });
  75338. }
  75339. };
  75340. GLTFLoader.prototype._buildInt8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75341. if (!byteStride) {
  75342. return new Int8Array(buffer, byteOffset, byteLength);
  75343. }
  75344. var sourceBuffer = new Int8Array(buffer, byteOffset);
  75345. var targetBuffer = new Int8Array(byteLength);
  75346. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  75347. return targetBuffer;
  75348. };
  75349. GLTFLoader.prototype._buildUint8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75350. if (!byteStride) {
  75351. return new Uint8Array(buffer, byteOffset, byteLength);
  75352. }
  75353. var sourceBuffer = new Uint8Array(buffer, byteOffset);
  75354. var targetBuffer = new Uint8Array(byteLength);
  75355. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  75356. return targetBuffer;
  75357. };
  75358. GLTFLoader.prototype._buildInt16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75359. if (!byteStride) {
  75360. return new Int16Array(buffer, byteOffset, byteLength);
  75361. }
  75362. var sourceBuffer = new Int16Array(buffer, byteOffset);
  75363. var targetBuffer = new Int16Array(byteLength);
  75364. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  75365. return targetBuffer;
  75366. };
  75367. GLTFLoader.prototype._buildUint16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75368. if (!byteStride) {
  75369. return new Uint16Array(buffer, byteOffset, byteLength);
  75370. }
  75371. var sourceBuffer = new Uint16Array(buffer, byteOffset);
  75372. var targetBuffer = new Uint16Array(byteLength);
  75373. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  75374. return targetBuffer;
  75375. };
  75376. GLTFLoader.prototype._buildUint32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75377. if (!byteStride) {
  75378. return new Uint32Array(buffer, byteOffset, byteLength);
  75379. }
  75380. var sourceBuffer = new Uint32Array(buffer, byteOffset);
  75381. var targetBuffer = new Uint32Array(byteLength);
  75382. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  75383. return targetBuffer;
  75384. };
  75385. GLTFLoader.prototype._buildFloat32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75386. if (!byteStride) {
  75387. return new Float32Array(buffer, byteOffset, byteLength);
  75388. }
  75389. var sourceBuffer = new Float32Array(buffer, byteOffset);
  75390. var targetBuffer = new Float32Array(byteLength);
  75391. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  75392. return targetBuffer;
  75393. };
  75394. GLTFLoader.prototype._extractInterleavedData = function (sourceBuffer, targetBuffer, bytePerComponent, stride, length) {
  75395. var tempIndex = 0;
  75396. var sourceIndex = 0;
  75397. var storageSize = bytePerComponent;
  75398. while (tempIndex < length) {
  75399. for (var cursor = 0; cursor < storageSize; cursor++) {
  75400. targetBuffer[tempIndex] = sourceBuffer[sourceIndex + cursor];
  75401. tempIndex++;
  75402. }
  75403. sourceIndex += stride;
  75404. }
  75405. };
  75406. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, bytePerComponent, componentType, onSuccess) {
  75407. var _this = this;
  75408. byteOffset += (bufferView.byteOffset || 0);
  75409. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  75410. if (byteOffset + byteLength > bufferData.byteLength) {
  75411. _this._onError("Buffer access is out of range");
  75412. return;
  75413. }
  75414. var buffer = bufferData.buffer;
  75415. byteOffset += bufferData.byteOffset;
  75416. var bufferViewData;
  75417. switch (componentType) {
  75418. case GLTF2.EComponentType.BYTE:
  75419. bufferViewData = _this._buildInt8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75420. break;
  75421. case GLTF2.EComponentType.UNSIGNED_BYTE:
  75422. bufferViewData = _this._buildUint8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75423. break;
  75424. case GLTF2.EComponentType.SHORT:
  75425. bufferViewData = _this._buildInt16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75426. break;
  75427. case GLTF2.EComponentType.UNSIGNED_SHORT:
  75428. bufferViewData = _this._buildUint16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75429. break;
  75430. case GLTF2.EComponentType.UNSIGNED_INT:
  75431. bufferViewData = _this._buildUint32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75432. break;
  75433. case GLTF2.EComponentType.FLOAT:
  75434. bufferViewData = _this._buildFloat32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75435. break;
  75436. default:
  75437. _this._onError("Invalid component type (" + componentType + ")");
  75438. return;
  75439. }
  75440. onSuccess(bufferViewData);
  75441. });
  75442. };
  75443. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  75444. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  75445. var byteOffset = accessor.byteOffset || 0;
  75446. var bytePerComponent = this._getByteStrideFromType(accessor);
  75447. var byteLength = accessor.count * bytePerComponent;
  75448. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, bytePerComponent, accessor.componentType, onSuccess);
  75449. };
  75450. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  75451. switch (accessor.type) {
  75452. case "SCALAR": return 1;
  75453. case "VEC2": return 2;
  75454. case "VEC3": return 3;
  75455. case "VEC4": return 4;
  75456. case "MAT2": return 4;
  75457. case "MAT3": return 9;
  75458. case "MAT4": return 16;
  75459. default:
  75460. this._onError("Invalid accessor type (" + accessor.type + ")");
  75461. return 0;
  75462. }
  75463. };
  75464. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  75465. set: function (value) {
  75466. this._blockPendingTracking = value;
  75467. },
  75468. enumerable: true,
  75469. configurable: true
  75470. });
  75471. GLTFLoader.prototype.addPendingData = function (data) {
  75472. if (!this._renderReady) {
  75473. this._renderPendingCount++;
  75474. }
  75475. this.addLoaderPendingData(data);
  75476. };
  75477. GLTFLoader.prototype.removePendingData = function (data) {
  75478. if (!this._renderReady) {
  75479. if (--this._renderPendingCount === 0) {
  75480. this._renderReady = true;
  75481. this._onRenderReady();
  75482. }
  75483. }
  75484. this.removeLoaderPendingData(data);
  75485. };
  75486. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  75487. if (!this._nonBlockingData) {
  75488. this._nonBlockingData = new Array();
  75489. }
  75490. this._nonBlockingData.push(data);
  75491. };
  75492. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  75493. if (this._blockPendingTracking) {
  75494. this.addLoaderNonBlockingPendingData(data);
  75495. return;
  75496. }
  75497. this._loaderPendingCount++;
  75498. };
  75499. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  75500. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  75501. if (indexInPending !== -1) {
  75502. this._nonBlockingData.splice(indexInPending, 1);
  75503. }
  75504. else if (--this._loaderPendingCount === 0) {
  75505. this._onLoaderFirstLODComplete();
  75506. }
  75507. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  75508. this._onLoaderComplete();
  75509. this.dispose();
  75510. }
  75511. };
  75512. GLTFLoader.prototype._getDefaultMaterial = function () {
  75513. if (!this._defaultMaterial) {
  75514. var id = "__gltf_default";
  75515. var material = this._babylonScene.getMaterialByName(id);
  75516. if (!material) {
  75517. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  75518. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  75519. material.metallic = 1;
  75520. material.roughness = 1;
  75521. }
  75522. this._defaultMaterial = material;
  75523. }
  75524. return this._defaultMaterial;
  75525. };
  75526. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  75527. var babylonMaterial = material.babylonMaterial;
  75528. // Ensure metallic workflow
  75529. babylonMaterial.metallic = 1;
  75530. babylonMaterial.roughness = 1;
  75531. var properties = material.pbrMetallicRoughness;
  75532. if (!properties) {
  75533. return;
  75534. }
  75535. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  75536. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  75537. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  75538. if (properties.baseColorTexture) {
  75539. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  75540. }
  75541. if (properties.metallicRoughnessTexture) {
  75542. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  75543. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  75544. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  75545. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  75546. }
  75547. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  75548. };
  75549. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  75550. if (material.babylonMaterial) {
  75551. assign(material.babylonMaterial, false);
  75552. return;
  75553. }
  75554. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  75555. return;
  75556. }
  75557. this.createPbrMaterial(material);
  75558. this.loadMaterialBaseProperties(material);
  75559. this._loadMaterialMetallicRoughnessProperties(material);
  75560. assign(material.babylonMaterial, true);
  75561. };
  75562. GLTFLoader.prototype.createPbrMaterial = function (material) {
  75563. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  75564. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  75565. material.babylonMaterial = babylonMaterial;
  75566. };
  75567. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  75568. var babylonMaterial = material.babylonMaterial;
  75569. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  75570. if (material.doubleSided) {
  75571. babylonMaterial.backFaceCulling = false;
  75572. babylonMaterial.twoSidedLighting = true;
  75573. }
  75574. if (material.normalTexture) {
  75575. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  75576. babylonMaterial.invertNormalMapX = true;
  75577. babylonMaterial.invertNormalMapY = false;
  75578. if (material.normalTexture.scale !== undefined) {
  75579. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  75580. }
  75581. }
  75582. if (material.occlusionTexture) {
  75583. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  75584. babylonMaterial.useAmbientInGrayScale = true;
  75585. if (material.occlusionTexture.strength !== undefined) {
  75586. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  75587. }
  75588. }
  75589. if (material.emissiveTexture) {
  75590. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  75591. }
  75592. };
  75593. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  75594. var babylonMaterial = material.babylonMaterial;
  75595. var alphaMode = material.alphaMode || "OPAQUE";
  75596. switch (alphaMode) {
  75597. case "OPAQUE":
  75598. // default is opaque
  75599. break;
  75600. case "MASK":
  75601. case "BLEND":
  75602. if (colorFactor) {
  75603. babylonMaterial.alpha = colorFactor[3];
  75604. }
  75605. if (babylonMaterial.albedoTexture) {
  75606. babylonMaterial.albedoTexture.hasAlpha = true;
  75607. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  75608. }
  75609. break;
  75610. default:
  75611. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  75612. break;
  75613. }
  75614. babylonMaterial.alphaCutOff = material.alphaCutoff === undefined ? 0.5 : material.alphaCutoff;
  75615. };
  75616. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  75617. var _this = this;
  75618. var texture = this._gltf.textures[textureInfo.index];
  75619. var texCoord = textureInfo.texCoord || 0;
  75620. if (!texture || texture.source === undefined) {
  75621. return null;
  75622. }
  75623. var source = this._gltf.images[texture.source];
  75624. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  75625. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  75626. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  75627. this.addPendingData(texture);
  75628. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  75629. if (!_this._disposed) {
  75630. _this.removePendingData(texture);
  75631. }
  75632. }, function () {
  75633. if (!_this._disposed) {
  75634. _this._onError("Failed to load texture '" + source.uri + "'");
  75635. _this.removePendingData(texture);
  75636. }
  75637. });
  75638. if (texture.url) {
  75639. babylonTexture.updateURL(texture.url);
  75640. }
  75641. else if (texture.dataReadyObservable) {
  75642. texture.dataReadyObservable.add(function (texture) {
  75643. babylonTexture.updateURL(texture.url);
  75644. });
  75645. }
  75646. else {
  75647. texture.dataReadyObservable = new BABYLON.Observable();
  75648. texture.dataReadyObservable.add(function (texture) {
  75649. babylonTexture.updateURL(texture.url);
  75650. });
  75651. var setTextureData = function (data) {
  75652. texture.url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  75653. texture.dataReadyObservable.notifyObservers(texture);
  75654. };
  75655. if (!source.uri) {
  75656. var bufferView = this._gltf.bufferViews[source.bufferView];
  75657. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, 1, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  75658. }
  75659. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  75660. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  75661. }
  75662. else {
  75663. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  75664. if (!_this._disposed) {
  75665. _this._onProgress(event);
  75666. }
  75667. }, this._babylonScene.database, true, function (request) {
  75668. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  75669. });
  75670. }
  75671. }
  75672. babylonTexture.coordinatesIndex = texCoord;
  75673. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  75674. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  75675. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  75676. if (this._parent.onTextureLoaded) {
  75677. this._parent.onTextureLoaded(babylonTexture);
  75678. }
  75679. return babylonTexture;
  75680. };
  75681. GLTFLoader.Extensions = {};
  75682. return GLTFLoader;
  75683. }());
  75684. GLTF2.GLTFLoader = GLTFLoader;
  75685. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  75686. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75687. })(BABYLON || (BABYLON = {}));
  75688. //# sourceMappingURL=babylon.glTFLoader.js.map
  75689. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75690. var BABYLON;
  75691. (function (BABYLON) {
  75692. var GLTF2;
  75693. (function (GLTF2) {
  75694. /**
  75695. * Utils functions for GLTF
  75696. */
  75697. var GLTFUtils = (function () {
  75698. function GLTFUtils() {
  75699. }
  75700. /**
  75701. * If the uri is a base64 string
  75702. * @param uri: the uri to test
  75703. */
  75704. GLTFUtils.IsBase64 = function (uri) {
  75705. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  75706. };
  75707. /**
  75708. * Decode the base64 uri
  75709. * @param uri: the uri to decode
  75710. */
  75711. GLTFUtils.DecodeBase64 = function (uri) {
  75712. var decodedString = atob(uri.split(",")[1]);
  75713. var bufferLength = decodedString.length;
  75714. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  75715. for (var i = 0; i < bufferLength; i++) {
  75716. bufferView[i] = decodedString.charCodeAt(i);
  75717. }
  75718. return bufferView.buffer;
  75719. };
  75720. GLTFUtils.ForEach = function (view, func) {
  75721. for (var index = 0; index < view.length; index++) {
  75722. func(view[index], index);
  75723. }
  75724. };
  75725. GLTFUtils.GetTextureWrapMode = function (mode) {
  75726. // Set defaults if undefined
  75727. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  75728. switch (mode) {
  75729. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  75730. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  75731. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  75732. default:
  75733. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  75734. return BABYLON.Texture.WRAP_ADDRESSMODE;
  75735. }
  75736. };
  75737. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  75738. // Set defaults if undefined
  75739. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  75740. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  75741. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  75742. switch (minFilter) {
  75743. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  75744. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  75745. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  75746. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  75747. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  75748. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  75749. default:
  75750. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  75751. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  75752. }
  75753. }
  75754. else {
  75755. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  75756. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  75757. }
  75758. switch (minFilter) {
  75759. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  75760. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  75761. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  75762. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  75763. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  75764. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  75765. default:
  75766. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  75767. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  75768. }
  75769. }
  75770. };
  75771. /**
  75772. * Decodes a buffer view into a string
  75773. * @param view: the buffer view
  75774. */
  75775. GLTFUtils.DecodeBufferToText = function (view) {
  75776. var result = "";
  75777. var length = view.byteLength;
  75778. for (var i = 0; i < length; ++i) {
  75779. result += String.fromCharCode(view[i]);
  75780. }
  75781. return result;
  75782. };
  75783. return GLTFUtils;
  75784. }());
  75785. GLTF2.GLTFUtils = GLTFUtils;
  75786. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75787. })(BABYLON || (BABYLON = {}));
  75788. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  75789. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75790. var BABYLON;
  75791. (function (BABYLON) {
  75792. var GLTF2;
  75793. (function (GLTF2) {
  75794. var GLTFLoaderExtension = (function () {
  75795. function GLTFLoaderExtension() {
  75796. this.enabled = true;
  75797. }
  75798. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  75799. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  75800. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  75801. };
  75802. GLTFLoaderExtension._ApplyExtensions = function (action) {
  75803. var extensions = GLTFLoaderExtension._Extensions;
  75804. if (!extensions) {
  75805. return;
  75806. }
  75807. for (var i = 0; i < extensions.length; i++) {
  75808. var extension = extensions[i];
  75809. if (extension.enabled && action(extension)) {
  75810. return true;
  75811. }
  75812. }
  75813. return false;
  75814. };
  75815. //
  75816. // Utilities
  75817. //
  75818. GLTFLoaderExtension._Extensions = [];
  75819. return GLTFLoaderExtension;
  75820. }());
  75821. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  75822. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75823. })(BABYLON || (BABYLON = {}));
  75824. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  75825. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  75826. var BABYLON;
  75827. (function (BABYLON) {
  75828. var GLTF2;
  75829. (function (GLTF2) {
  75830. var Extensions;
  75831. (function (Extensions) {
  75832. var MSFTLOD = (function (_super) {
  75833. __extends(MSFTLOD, _super);
  75834. function MSFTLOD() {
  75835. return _super !== null && _super.apply(this, arguments) || this;
  75836. }
  75837. Object.defineProperty(MSFTLOD.prototype, "name", {
  75838. get: function () {
  75839. return "MSFT_lod";
  75840. },
  75841. enumerable: true,
  75842. configurable: true
  75843. });
  75844. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  75845. if (!material.extensions) {
  75846. return false;
  75847. }
  75848. var properties = material.extensions[this.name];
  75849. if (!properties) {
  75850. return false;
  75851. }
  75852. // Clear out the extension so that it won't get loaded again.
  75853. material.extensions[this.name] = undefined;
  75854. // Tell the loader not to clear its state until the highest LOD is loaded.
  75855. var materialLODs = [material.index].concat(properties.ids);
  75856. loader.addLoaderPendingData(material);
  75857. for (var index = 0; index < materialLODs.length; index++) {
  75858. loader.addLoaderNonBlockingPendingData(index);
  75859. }
  75860. // Start with the lowest quality LOD.
  75861. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  75862. return true;
  75863. };
  75864. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  75865. var _this = this;
  75866. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  75867. if (lod !== materialLODs.length - 1) {
  75868. loader.blockPendingTracking = true;
  75869. }
  75870. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  75871. assign(babylonMaterial, isNew);
  75872. loader.removeLoaderPendingData(lod);
  75873. // Loading is considered complete if this is the lowest quality LOD.
  75874. if (lod === materialLODs.length - 1) {
  75875. loader.removeLoaderPendingData(material);
  75876. }
  75877. if (lod === 0) {
  75878. loader.blockPendingTracking = false;
  75879. return;
  75880. }
  75881. // Load the next LOD when the loader is ready to render and
  75882. // all active material textures of the current LOD are loaded.
  75883. loader.executeWhenRenderReady(function () {
  75884. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  75885. setTimeout(function () {
  75886. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  75887. }, MSFTLOD.MinimalLODDelay);
  75888. });
  75889. });
  75890. });
  75891. };
  75892. /**
  75893. * Specify the minimal delay between LODs in ms (default = 250)
  75894. */
  75895. MSFTLOD.MinimalLODDelay = 250;
  75896. return MSFTLOD;
  75897. }(GLTF2.GLTFLoaderExtension));
  75898. Extensions.MSFTLOD = MSFTLOD;
  75899. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  75900. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  75901. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75902. })(BABYLON || (BABYLON = {}));
  75903. //# sourceMappingURL=MSFT_lod.js.map
  75904. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  75905. var BABYLON;
  75906. (function (BABYLON) {
  75907. var GLTF2;
  75908. (function (GLTF2) {
  75909. var Extensions;
  75910. (function (Extensions) {
  75911. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  75912. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  75913. function KHRMaterialsPbrSpecularGlossiness() {
  75914. return _super !== null && _super.apply(this, arguments) || this;
  75915. }
  75916. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  75917. get: function () {
  75918. return "KHR_materials_pbrSpecularGlossiness";
  75919. },
  75920. enumerable: true,
  75921. configurable: true
  75922. });
  75923. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  75924. if (!material.extensions) {
  75925. return false;
  75926. }
  75927. var properties = material.extensions[this.name];
  75928. if (!properties) {
  75929. return false;
  75930. }
  75931. loader.createPbrMaterial(material);
  75932. loader.loadMaterialBaseProperties(material);
  75933. this._loadSpecularGlossinessProperties(loader, material, properties);
  75934. assign(material.babylonMaterial, true);
  75935. return true;
  75936. };
  75937. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  75938. var babylonMaterial = material.babylonMaterial;
  75939. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  75940. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  75941. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  75942. if (properties.diffuseTexture) {
  75943. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  75944. }
  75945. if (properties.specularGlossinessTexture) {
  75946. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  75947. babylonMaterial.reflectivityTexture.hasAlpha = true;
  75948. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  75949. }
  75950. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  75951. };
  75952. return KHRMaterialsPbrSpecularGlossiness;
  75953. }(GLTF2.GLTFLoaderExtension));
  75954. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  75955. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  75956. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  75957. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75958. })(BABYLON || (BABYLON = {}));
  75959. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  75960. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  75961. module.exports = BABYLON;
  75962. };